[HDU1575]Tr A(矩阵乘法)

题目描述

传送门

题意
给出一个矩阵A和整数k,求 Ak

代码

#include
#include
#include
using namespace std;
const int Mod=9973;
const int max_n=15;
int T,n,k,ans;
struct hp{int a[max_n][max_n];}st,m,matrix;

inline hp cheng(hp a,hp b)
{
    hp ans;
    memset(ans.a,0,sizeof(ans.a));
    for (int i=1;i<=n;++i)
        for (int j=1;j<=n;++j)
            for (int k=1;k<=n;++k)
                ans.a[i][j]=(ans.a[i][j]+a.a[i][k]*b.a[k][j]%Mod)%Mod;
    return ans;
}
inline hp matrix_fast_pow(hp a,int p)
{
    hp ans=st;
    for (;p;p>>=1,a=cheng(a,a))
        if (p&1)
            ans=cheng(ans,a);
    return ans;
}
int main()
{
    scanf("%d",&T);
    while (T--)
    {
        scanf("%d%d",&n,&k);
        memset(st.a,0,sizeof(st.a));
        for (int i=1;i<=n;++i) st.a[i][i]=1;
        for (int i=1;i<=n;++i)
            for (int j=1;j<=n;++j)
                scanf("%d",&m.a[i][j]);
        matrix=matrix_fast_pow(m,k);
        ans=0;
        for (int i=1;i<=n;++i)
            ans=(ans+matrix.a[i][i])%Mod;
        printf("%d\n",ans);
    }
}

你可能感兴趣的:(题解,矩阵)