Tr A
**Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7631 Accepted Submission(s): 5575**
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
Author
xhd
Source
HDU 2007-1 Programming Contest
Recommend
linle
题解
矩阵快速幂模板题。代码如下:
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <stack>
#include <queue>
#define ll long long
using namespace std ;
const ll MOD = 9973 ;
const int maxn = 15 ;
ll n , k ;
struct matrix{
int m[maxn][maxn] ;
}mat ;
matrix operator *(matrix a , matrix b){
matrix res ;
for ( int i = 0 ; i < n ; i ++ ){
for ( int j = 0 ; j < n ; j ++ ){
ll temp = 0 ;
for ( int k = 0 ; k < n ; k ++ ){
temp += ((a.m[i][k] % MOD) * (b.m[k][j] % MOD)) % MOD ;
}
res.m[i][j] = temp % MOD ;
}
}
return res ;
}
void init(){
for ( int i = 0 ; i < n ; i ++ ){
mat.m[i][i] = 1 ;
}
return ;
}
matrix quick_pow(matrix a, ll b){
matrix ans = mat ;
while (b){
if (b & 1){
ans = ans * a ;
}
a = a * a ;
b >>= 1 ;
}
return ans ;
}
ll tr_ans(matrix a){
ll sum = 0 ;
for ( int i = 0 ; i < n ; i ++ ){
sum = (sum % MOD + a.m[i][i] % MOD) % MOD ;
}
return sum ;
}
int main(){
int t ;
cin >> t ;
while (t --){
cin >> n >> k ;
init() ;
matrix a ;
for ( int i = 0 ; i < n ; i ++ ){
for ( int j = 0 ; j < n ; j ++ ){
cin >> a.m[i][j] ;
}
}
a = quick_pow(a , k) ;
// for ( int i = 0 ; i < n ; i ++ ){
// for ( int j = 0 ; j < n ; j ++ ){
// cout << a.m[i][j] << " " ;
// }
// cout << endl ;
// }
cout << tr_ans(a) << endl ;
}
return 0 ;
}