这题还不错。。比较经典的题吧。。
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<cmath>
#include<cassert>
#include<cstring>
#include<iomanip>
using namespace std;
#ifdef _WIN32
#define i64 __int64
#define out64 "%I64d\n"
#define in64 "%I64d"
#else
#define i64 long long
#define out64 "%lld\n"
#define in64 "%lld"
#endif
/************ for topcoder by zz1215 *******************/
#define FOR(i,a,b) for( int i = (a) ; i <= (b) ; i ++)
#define FFF(i,a) for( int i = 0 ; i < (a) ; i ++)
#define FFD(i,a,b) for( int i = (a) ; i >= (b) ; i --)
#define S64(a) scanf(in64,&a)
#define SS(a) scanf("%d",&a)
#define LL(a) ((a)<<1)
#define RR(a) (((a)<<1)+1)
#define pb push_back
#define CL(Q) while(!Q.empty())Q.pop()
#define MM(name,what) memset(name,what,sizeof(name))
#define MC(a,b) memcpy(a,b,sizeof(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
#define read freopen("in.txt","r",stdin)
#define write freopen("out.txt","w",stdout)
const int inf = 0x3f3f3f3f;
const i64 inf64 = 0x3f3f3f3f3f3f3f3fLL;
const double oo = 10e9;
const double eps = 10e-9;
const double pi = acos(-1.0);
const int maxn = 33;
int n,k,m;
struct zz
{
int a[maxn][maxn];
zz operator += (zz & x)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
a[i][j]+=x.a[i][j];
a[i][j]%=m;
}
}
return *this;
}
zz operator *= (zz & x)
{
zz temp;
MM(temp.a,0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
for(int k=1;k<=n;k++)
{
temp.a[i][j]+=a[i][k]*x.a[k][j];
temp.a[i][j]%=m;
}
}
}
MC(a,temp.a);
return *this;
}
}zx;
zz mx;
zz f[maxn];
zz s[maxn];
int main()
{
while(cin>>n>>k>>m)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>mx.a[i][j];
}
}
for(int i=0;i<maxn;i++)
{
f[i]=mx;
mx*=mx;
}
s[0]=f[0];
zz now;
for(int i=1;i<maxn;i++)
{
now = f[i-1];
now *= s[i-1];
now+=s[i-1];
s[i]=now;
}
zz temp,ans;
MM(temp.a,0);
MM(ans.a,0);
for(int i=1;i<maxn;i++)
{
temp.a[i][i]=1;
}
for(int i=0;k;i++)
{
if(k&1)
{
now=temp;
now*=s[i];
ans+=now;
temp*=f[i];
}
k>>=1;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-1;j++)
{
cout<<ans.a[i][j]<<" ";
}
cout<<ans.a[i][n]<<endl;
}
}
return 0;
}