Tr A

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

矩阵快速幂模板题。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <cmath>
#include <list>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
int n;
long long k;   // n是矩阵大小,k是倍数
const int N=9973;
struct node{long long  a[105][105];};
node shu,ans,mp;
node matrix(node x,node y){
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++){
            mp.a[i][j]=0;
            for(int p=1;p<=n;p++)
                mp.a[i][j]=(mp.a[i][j]+(x.a[i][p] * y.a[p][j]))%N;
        }
    return mp;
}
void work(long long k){
    while(k){
        if(k&1)
            ans=matrix(ans,shu);
        k>>=1;
        shu=matrix(shu,shu);
    }
}
int main(){
    long long  T;
    cin>>T;
    while(T--)
    {
    cin>>n>>k;
    memset(ans.a,0,sizeof(ans.a));
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++)
            scanf("%lld",&shu.a[i][j]);
        ans.a[i][i]=1;
    }
    work(k);
    long long sum=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++)
        {
            if(i==j)
            {
                sum+=ans.a[i][j];
                sum=sum%9973;
            }
         //printf("%d ",ans.a[i][j]);
        }
       // printf("\n");
    }
    cout<<sum<<endl;
    sum=0;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40941611/article/details/81269964
tr