HDU1575 Tr A

http://acm.hdu.edu.cn/showproblem.php?pid=1575

矩阵快速幂

矩阵快速幂模板题,直接套

把矩阵装进一个结构体,然后重载\(*\)运算符,直接用普通快速幂的方式解决

\(C++ Code:\)

#include<cstdio>
#include<iostream>
#include<cmath>
#define mod 9973
#define N 15
using namespace std;
int T,n,k;
struct matrix
{
    int a[N][N];
    matrix operator * (matrix b)
    {
        matrix g;
        for (int i=1;i<=n;i++)
            for (int j=1;j<=n;j++)
                g.a[i][j]=0;
        for (int k=1;k<=n;k++)
            for (int i=1;i<=n;i++)
                for (int j=1;j<=n;j++)
                    g.a[i][j]=(g.a[i][j]+a[i][k]*b.a[k][j])%mod;
        return g;
    } 
}S,zero;
matrix ksm(matrix x,int y)
{
    matrix ans=zero;
    while (y)
    {
        if (y&1)
            ans=ans*x;
        x=x*x;
        y >>=1;
    }
    return ans;
}
int main()
{
    scanf("%d",&T);
    while (T --> 0)
    {
        scanf("%d%d",&n,&k);
        for (int i=1;i<=n;i++)
            zero.a[i][i]=1;
        for (int i=1;i<=n;i++)
            for (int j=1;j<=n;j++)
                scanf("%d",&S.a[i][j]),S.a[i][j]%=mod;
        S=ksm(S,k);
        int ans=0;
        for (int i=1;i<=n;i++)
            ans=(ans+S.a[i][i])%mod;
        cout << ans << endl;
    }
    return 0;
}
posted @ 2020-07-25 07:24  GK0328  阅读(60)  评论(0编辑  收藏  举报