標籤:des style blog 資料 2014 os
Description
A為一個方陣,則Tr A表示A的跡(就是主對角線上各項的和),現要求Tr(A^k)%9973。
Input
資料的第一行是一個T,表示有T組資料。
每組資料的第一行有n(2 <= n <= 10)和k(2 <= k < 10^9)兩個資料。接下來有n行,每行有n個資料,每個資料的範圍是[0,9],表示方陣A的內容。
Output
對應每組資料,輸出Tr(A^k)%9973。
Sample Input
22 21 00 13 999999991 2 34 5 67 8 9
Sample Output
22686
思路:就是一道矩陣乘法快速冪
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MOD = 9973;struct Matrix {int arr[12][12];}init, unit;int n,k;Matrix Mul(Matrix a, Matrix b) {Matrix c;for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {c.arr[i][j] = 0;for (int k = 0; k < n; k++)c.arr[i][j] = (c.arr[i][j]+(a.arr[i][k]*b.arr[k][j])%MOD)%MOD;}return c;}Matrix Pow(Matrix a, Matrix b, int x) {while (x) {if (x & 1)b = Mul(b, a);x >>= 1;a = Mul(a, a);}return b;}int main() {int t;scanf("%d", &t);while (t--) {scanf("%d%d", &n, &k);for (int i = 0; i < n; i++)for (int j = 0; j < n; j++) {scanf("%d", &init.arr[i][j]);unit.arr[i][j] = init.arr[i][j];}Matrix res = Pow(init, unit, k-1);int ans = 0;for (int i = 0; i < n; i++) ans = (ans + res.arr[i][i]) % MOD;printf("%d\n", ans%MOD);}return 0;}