【矩阵快速幂】HDU1575Tr A【模板】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wlxsq/article/details/78895324

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1575

题目描述:

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

题目代码:

#include <iostream>
#include <bits/stdc++.h>
#define MOD 9973
#define N 15
using namespace std;
int n, k, t;
struct Matrix {
    int m[N][N];
    Matrix()
    {
        memset(m, 0, sizeof(m));
    }
};
Matrix mul(Matrix a, Matrix b)
{
    Matrix res;
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            for(int k = 0; k < n; k++) {
                res.m[i][j] = (res.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
            }
        }
    }
    return res;
}
Matrix solve(Matrix a, int k)
{
    Matrix r;
    for(int i = 0; i < n; i++) r.m[i][i] = 1;
    while(k) {
        if(k & 1) r = mul(r, a);
        k >>= 1;
        a = mul(a, a);
    }
    return r;
}
int main()
{
    Matrix a;
    cin.sync_with_stdio(false);
    cin >> t;
    while(t--) {
        cin >> n >> k;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                cin >> a.m[i][j];
        Matrix tmp = solve(a, k);
        int ans = 0;
        for(int i = 0; i < n; i++)
            ans = (ans + tmp.m[i][i]) % MOD;
        cout << ans << endl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/wlxsq/article/details/78895324