分治即可
当然也可以把矩阵看成元素用矩阵快速幂做
#include <iostream>
#include <cstdio>
using namespace std;
int n, k, m;
struct Matrix{
int num[35][35];
Matrix operator*(const Matrix &x)const{
Matrix re;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++){
re.num[i][j] = 0;
for(int k=1; k<=n; k++)
re.num[i][j] = (re.num[i][j] + num[i][k] * x.num[k][j]) % m;
}
return re;
}
Matrix operator+(const Matrix &x)const{
Matrix re;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
re.num[i][j] = (num[i][j] + x.num[i][j]) % m;
return re;
}
}a, dan;
Matrix ksm(Matrix aa, int b){
Matrix re=dan;
while(b){
if(b&1) re = re * aa;
aa = aa * aa;
b >>= 1;
}
return re;
}
Matrix sum(int x){
if(x==1) return a;
Matrix tmp=sum(x/2);
if((x&1)==0)
return tmp+tmp*ksm(a, x/2);
else
return tmp+tmp*ksm(a, x/2)+ksm(a, x);
}
int main(){
cin>>n>>k>>m;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(i==j) dan.num[i][j] = 1;
else dan.num[i][j] = 0;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
scanf("%d", &a.num[i][j]);
Matrix ans=sum(k);
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++)
printf("%d ", ans.num[i][j]);
printf("
");
}
return 0;
}