1. 程式人生 > >HDU 1575 Tr A 【矩陣經典2 矩陣快速冪入門】

HDU 1575 Tr A 【矩陣經典2 矩陣快速冪入門】

others i++ 輸出 pro 技術分享 targe rip color mis

任意門:http://acm.hdu.edu.cn/showproblem.php?pid=1575

Tr A

Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7572 Accepted Submission(s): 5539


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

題意概括:如題幹

解題思路:矩陣快速冪(本質是二分優化快速進行冪運算)矩陣快速冪模板題

註意:單位矩陣初始化

AC code:

技術分享圖片
 1 #include <cstdio>
 2 #include <iostream>
 3 #include <cstring>
 4 #include <cmath>
 5
#define LL long long 6 using namespace std; 7 const int MAXN = 11; 8 const int Mod = 9973; 9 int N; 10 struct mat 11 { 12 int m[MAXN][MAXN]; 13 }base; 14 15 mat muti(mat a, mat b) 16 { 17 mat res; 18 memset(res.m, 0, sizeof(res.m)); 19 for(int i = 1; i <= N; i++) 20 for(int
j = 1; j <= N; j++){ 21 if(a.m[i][j]){ 22 for(int k = 1; k <= N; k++){ 23 res.m[i][k] = (res.m[i][k] + a.m[i][j]*b.m[j][k])%Mod; 24 } 25 } 26 } 27 28 return res; 29 } 30 31 mat qpow(mat a, int n) 32 { 33 mat res; 34 memset(res.m, 0, sizeof(res.m)); 35 for(int i = 1; i <= N; i++) res.m[i][i] = 1; 36 while(n){ 37 if(n&1) res = muti(res, a); 38 n>>=1; 39 a = muti(a, a); 40 } 41 return res; 42 } 43 44 45 int main() 46 { 47 int K, T_case; 48 scanf("%d", &T_case); 49 while(T_case--){ 50 memset(base.m, 0, sizeof(base.m)); 51 scanf("%d %d", &N, &K); 52 for(int i = 1; i <= N; i++){ 53 for(int j = 1; j <= N; j++){ 54 scanf("%d", &base.m[i][j]); 55 } 56 } 57 base = qpow(base, K); 58 int ans = 0; 59 for(int i = 1; i <= N; i++){ 60 ans = (ans + base.m[i][i])%Mod; 61 } 62 printf("%d\n", ans); 63 } 64 65 return 0; 66 }
View Code

HDU 1575 Tr A 【矩陣經典2 矩陣快速冪入門】