您的位置:首页 > 其它

HDU 1575 Tr A【矩阵快速幂取模】

2016-11-09 17:49 387 查看


Tr A

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 4510    Accepted Submission(s): 3394

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代码:

#include<cstdio>
#include<cstring>

typedef long long LL;
const int MOD=9973;
const int MAXN=13;

typedef struct Matrix{
int M[MAXN][MAXN];
int n,m;
void clear() {
memset(M,0,sizeof(M)); n=m=0;
}
Matrix operator *(const Matrix &a) const {
Matrix tem; tem.clear();
tem.n=n, tem.m=a.m;
for(int i=0;i<n;++i ) {
for(int j=0;j<m;++j) if(M[i][j]) {
for(int k=0;k<a.m;++k) {
tem.M[i][k]=(tem.M[i][k]+(M[i][j]%MOD*(a.M[j][k]%MOD))%MOD)%MOD;
}
}
}
return tem;
}
// const Matrix operator %(int MOD) {
// Matrix tem; tem.clear();
// for(int i=0;i<n;++i) {
// for(int j=0;j<m;++j) if(M[i][j]) tem.M[i][j]=M[i][j]%MOD;
// }
// return tem;
// }
Matrix& operator =(const Matrix& a) {
for(int i=0;i<=a.n;++i) {
for(int j=0;j<=a.m;++j) M[i][j]=a.M[i][j];
}
return *this;
}
}Matrix;

LL Pow_Mod(Matrix base,LL y,int MOD)
{
Matrix ans; ans.clear(); ans.m=ans.n=base.m;
for(int i=0;i<ans.m;++i) ans.M[i][i]=1;
while(y) {
if(y&1) ans=base*ans;
y>>=1; base=base*base;
}
LL cnt=0;
for(int i=0;i<ans.n;++i ) cnt=(cnt+ans.M[i][i])%MOD;
return cnt;
}
int main()
{
int T; scanf("%d",&T);
while(T--) {
int N,K; scanf("%d%d",&N,&K);
Matrix a; a.m=N; a.n=N;
for(int i=0;i<N;++i) for(int j=0;j<N;++j) scanf("%d",&a.M[i][j]);
printf("%lld\n",Pow_Mod(a,K,MOD));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: