#include"stdio.h"
#include"iostream"
#include"algorithm"
#include"map"
using namespace std;
int n,k,M;
struct Matrix
{
void init()
{
memset(m,0,sizeof(m));
}
Matrix operator *(Matrix t)
{
Matrix t1;
t1.init();
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
{ for(int k=0;k<n;++k)
t1.m[i][j]+=m[i][k]*t.m[k][j];
t1.m[i][j]%=M;
}
return t1;
}
Matrix operator+(Matrix t)
{
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
t.m[i][j]=(t.m[i][j]+m[i][j])%M;
return t;
}
void print()
{
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
printf(j==0?"%d":" %d",m[i][j]);
puts("");
}
}
int m[35][35];
};
map< int ,Matrix > mp,mp1;
Matrix ma,s;
inline Matrix mu1(Matrix ma,int k)
{
if(mp.count(k))
return mp[k];
if(k==1)
return ma;
Matrix s=mu1(ma,k/2),tk=s*s;
if(k&1)
mp[k]=tk*ma;
else
mp[k]=tk;
return mp[k];
}
inline Matrix add(Matrix ma,int k)
{
if(mp1.count(k))
return mp1[k];
if(k==1)
return ma;
Matrix t=add(ma,k/2),t1=t+mu1(ma,k/2)*t;
if(k&1)
mp1[k]=t1+mu1(ma,k);
else
mp1[k]=t1;
return mp1[k];
}
int main()
{
while(scanf("%d%d%d",&n,&k,&M)!=EOF)
{
mp.clear();
mp1.clear();
ma.init();s.init();
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
scanf("%d",&ma.m[i][j]),ma.m[i][j]%=M;
s=add(ma,k);
s.print( );
}
return 0;
}
来源:https://www.cnblogs.com/QQbai/archive/2011/08/09/2132034.html