- 题意(原题): 给出矩阵A,求A+A^2…A^k。
- 思路: 手推一下,即可算出A+A^2…A^k = A+A^2…+A^k/2+A^k/2(A+A^2…+A^k/2)。
二分+矩阵快速幂即可。 注意奇数的时候多加一个A^k。 - 代码:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#define GETMOD %Mod
using namespace std;
int n,k,Mod;
struct node
{
int xcnt,ycnt;
int a[31][31];
node()
{
xcnt=n;ycnt=n;
memset(a,0,sizeof(a));
}
}a;
node dw()
{
node ans;
for(int i=1;i<=n;i++)ans.a[i][i]=1;
return ans;
}
node cf(node x,node y)
{
node ans;
for(int i=1;i<=ans.xcnt;i++)
for(int j=1;j<=ans.ycnt;j++)
for(int k=1;k<=x.ycnt;k++)
ans.a[i][j]=(ans.a[i][j]+x.a[i][k]*y.a[k][j]GETMOD)GETMOD;
return ans;
}
node jf(node x,node y)
{
node ans;
for(int i=1;i<=x.xcnt;i++)
for(int j=1;j<=x.ycnt;j++)
ans.a[i][j]=(x.a[i][j]+y.a[i][j])GETMOD;
return ans;
}
node power(int k)
{
node ans=dw(),x=a;
while(k)
{
if(k%2==1)ans=cf(ans,x);
x=cf(x,x);
k/=2;
}
return ans;
}
node getSum(int x)
{
if(x==1)return a;
node ans,t=getSum(x/2);
node y=power(x/2);
ans=cf(y,t);
ans=jf(t,ans);
if(x&1)ans=jf(ans,power(x));
return ans;
}
int main()
{
scanf("%d%d%d",&n,&k,&Mod);
a.xcnt=n;a.ycnt=n;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&a.a[i][j]);
node ans=getSum(k);
for(int i=1;i<=ans.xcnt;i++)
{
for(int j=1;j<=ans.ycnt;j++)
printf("%d ",ans.a[i][j]);
printf("\n");
}
return 0;
}