Hdu 1575-Tr A 矩阵快速幂
题目
Tr A
Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7316    Accepted Submission(s): 5370
 
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
题目链接http://acm.hdu.edu.cn/showproblem.php?pid=1575
思路
矩阵快速幂的入门题目,比较水。
代码
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 15;
const int m = 9973;
int n,k;
struct Matrix{
    int a[maxn][maxn];
};
Matrix mul(Matrix A,Matrix B){
    Matrix res;
    for(int i=0;i < n;i++){
        for(int j=0;j < n;j++){
            res.a[i][j] = 0;
            for(int k=0;k < n;k++){
                res.a[i][j] =  (res.a[i][j] + (A.a[i][k] * B.a[k][j])%m)%m;
            }
        }
    }
    return res;
}
Matrix poww(Matrix A,Matrix B,int b){
    while(b){
        if(b&1)B = mul(B,A);
        b >>= 1;
        A = mul(A,A);
    }
    return B;
}
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%d%d",&n,&k);
        Matrix p,q;
        for(int i=0;i < n;i++){
            for(int j=0;j < n;j++){
                scanf("%d",&p.a[i][j]);
                q.a[i][j] = p.a[i][j];
            }
        }
        p = poww(p,q,k-1);
        int res = 0;
        for(int i=0;i < n;i++){
                res = (res + p.a[i][i])%m;
        }
        printf("%d\n",res);
    }
    return 0;
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号