求矩阵幂的和。构造个2n*2n的矩阵,左上和右上为本矩阵,左下为0矩阵,右下为单位矩阵,求幂后,右上角为和。
#include<cstdio>
#include<string>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
#define N 2000005
#define INF 9973
typedef long long LL;
int n, m, inf;
struct Mar{
LL s[80][80];
};
Mar mut(Mar a, Mar b){
Mar ans;
for(int i = 0; i < n * 2; i++){
for(int j = 0; j < n * 2; j++){
ans.s[i][j] = 0;
for(int k = 0; k < n * 2; k++){
ans.s[i][j] += (a.s[i][k] * b.s[k][j]) % inf;
ans.s[i][j] %= inf;
}
}
}
return ans;
}
Mar Mpow(Mar a, int k){
Mar ret;
for(int i = 0; i < n * 2; i++){
for(int j = 0; j < n * 2; j++){
ret.s[i][j] = 0;
if(i == j)ret.s[i][j] = 1;
}
}
while(k){
if(k & 1)ret = mut(a, ret);
a = mut(a, a);
k >>= 1;
}
return ret;
}
int main(){
scanf("%d%d%d", &n, &m, &inf);
Mar a;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
scanf("%I64d", &a.s[i][j]);
a.s[i][j + n] = a.s[i][j];
a.s[i + n][j] = 0;
if(i == j)a.s[i + n][j + n] = 1;
else a.s[i + n][j + n] = 0;
}
}
Mar ans = Mpow(a, m);
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%I64d ", ans.s[i][j + n]);
}
printf("\n");
}
return 0;
}