Tr A(矩陣快速冪)

題目連接:http://acm.hdu.edu.cn/showproblem.php?pid=1575php

題目:spa

Problem 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
2
2 2
1 0
0 1
3 99999999
1 2 3
4 5 6
7 8 9
 
Sample Output
2
2686
 
 思路:本題要想用矩陣快速冪就得藉助單位矩陣(或許是其餘方法我沒想到吧……),而後就又是一個套模板的題了>_<
 
代碼實現以下:
 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 const int mod = 9973;  5 int t, n, k;  6 int a[15][15], T[15][15];  7 
 8 void mul(int a[15][15], int b[15][15]) {  9     int c[15][15]; 10     memset(c, 0, sizeof(c)); 11     for(int i = 0; i < n; i++) { 12         for(int j = 0; j < n; j++) { 13             for(int k = 0; k < n; k++) { 14                 c[i][j] = (c[i][j] + (long long)a[i][k] * b[k][j] % mod) % mod; 15  } 16  } 17  } 18     memcpy(a, c, sizeof(c)); 19 } 20 
21 
22 int main() { 23     scanf("%d", &t); 24     while(t--) { 25         scanf("%d%d", &n, &k); 26         memset(T, 0, sizeof(T)); 27         for(int i = 0; i < n; i++) { 28             T[i][i] = 1; 29             for(int j = 0; j < n; j++) { 30                 scanf("%d", &a[i][j]); 31  } 32  } 33         for(; k; k >>= 1) { 34             if(k & 1) mul(T, a); 35  mul(a, a); 36  } 37         long long ans = 0; 38         for(int i = 0; i < n; i++) { 39             ans = (ans + T[i][i]) % mod; 40  } 41         printf("%lld\n", ans % mod); 42  } 43     return 0; 44 }
相關文章
相關標籤/搜索