题目链接:51nod 1113 矩阵快速幂
模板题,学习下。
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N = ;
const int mod = 1e9+;
int n, m;
struct Mat{//矩阵
ll mat[N][N];
};
Mat operator * (Mat a, Mat b){//一次矩阵乘法
Mat c;
memset(c.mat, , sizeof(c.mat));
int i, j, k;
for(k = ; k <= n; ++k){
for(i = ; i <= n; ++i){
if(a.mat[i][k] <= ) continue;
for(j = ; j <= n; ++j){
if(b.mat[k][j] <= ) continue;
c.mat[i][j] += a.mat[i][k] * b.mat[k][j];
c.mat[i][j] %= mod;
}
}
}
return c;
}
Mat operator ^ (Mat a, int k){//矩阵快速幂,a^k
Mat c;
int i, j;
for(i = ; i <= n; ++i)
for(j = ; j <= n; ++j)
c.mat[i][j] = (i == j);//初始化为单位矩阵
while(k){
if(k & )
c = c * a;
a = a * a;
k >>= ;
}
return c;
}
int main(){
scanf("%d%d", &n, &m);
int i, j;
Mat a;
for(i = ; i <= n; ++i)
for(j = ; j <= n; ++j)
scanf("%lld", &a.mat[i][j]);
Mat c = a ^ m;
for(i = ; i <= n; ++i){
for(j = ; j < n; ++j)
printf("%lld ", c.mat[i][j]);
printf("%lld\n", c.mat[i][n]);
}
return ;
}