`
Simone_chou
  • 浏览: 184739 次
  • 性别: Icon_minigender_2
  • 来自: 广州
社区版块
存档分类
最新评论

Tr A(矩阵快速幂)

    博客分类:
  • HDOJ
 
阅读更多

Tr A

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2650    Accepted Submission(s): 1972


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

      思路:

      矩阵快速幂。按要求求出结果即可。

 

      AC:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

typedef vector<int> vec;
typedef vector<vec> mat;

const int MOD = 9973;

mat mul (mat a, mat b) {
    mat c(a.size(), vec(b[0].size()));

    for (int i = 0; i < a.size(); ++i) {
        for (int j = 0; j < b[0].size(); ++j) {
            for (int k = 0; k < b.size(); ++k) {
                c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
            }
        }
    }

    return c;
}

mat pow (mat a, int n) {
    mat b(a.size(), vec(a[0].size()));
    for (int i = 0; i < a.size(); ++i) {
        b[i][i] = 1;
    }

    while (n > 0) {
        if (n & 1) b = mul(b, a);
        a = mul(a, a);
        n >>= 1;
    }

    return b;
}

int main() {

    int t;
    scanf("%d", &t);

    while (t--) {
        int n, k;
        scanf("%d%d", &n, &k);

        mat a(n, vec(n));
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                scanf("%d", &a[i][j]);
            }
        }

        a = pow(a, k);
        int sum = 0;
        for (int i = 0; i < n; ++i) {
            sum = (sum + a[i][i]) % MOD;
        }

        printf("%d\n", sum);
    }

    return 0;
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics