zoukankan      html  css  js  c++  java
  • HDU1575-Tr A(矩阵高速幂)

    题目链接


    题意:A为一个方阵,则Tr A表示A的迹(就是主对角线上各项的和),现要求Tr(A^k)%9973。

    思路:简单的矩阵高速幂

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    
    using namespace std;
    
    //typedef long long ll;
    typedef __int64 ll;
    
    const int MOD = 9973;
    const int N = 15;
    
    ll k;
    int n;
    
    struct mat{
        int s[N][N];    
        mat() {
            memset(s, 0, sizeof(s)); 
        }
        mat operator * (const mat& c) {
            mat ans; 
            for (int i = 0; i < N; i++)
                for (int j = 0; j < N; j++)
                    for (int k = 0; k < N; k++) 
                        ans.s[i][j] = (ans.s[i][j] + s[i][k] * c.s[k][j]) % MOD;
            return ans;
        }
    };
    
    mat state;
    
    mat pow_mod(ll k) {
        if (k == 1)
            return state;
        mat a = pow_mod(k / 2);
        mat ans = a * a;
        if (k % 2)
            ans = ans * state;
        return ans;
    }
    
    int main() {
        int cas; 
        scanf("%d", &cas);
        while (cas--) {
            scanf("%d%I64d", &n, &k);    
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    scanf("%d", &state.s[i][j]);
            mat c = pow_mod(k);
            int ans = 0;
            for (int i = 0; i < n; i++)
                for (int j = 0; j < n; j++)
                    if (i == j)
                        ans += c.s[i][j];
            printf("%d
    ", ans % MOD);
        }
        return 0;
    }

    题目链接

  • 相关阅读:
    《代码整洁之道》读书笔记六
    第九周总结
    《构建之法》读后感(五)
    学习进度条-第十二周
    3. 统计数字
    《构建之法》读后感(四)
    学习进度条-第十一周
    4. 丑数 II
    《构建之法》读后感(三)
    学习进度条-第十周
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5096857.html
Copyright © 2011-2022 走看看