原题链接



1113 矩阵快速幂



基准时间限制:3 秒 空间限制:131072 KB 分值: 40  难度:4级算法题



 收藏

 关注


Input


第1行:2个数N和M,中间用空格分隔。N为矩阵的大小,M为M次方。(2 <= N <= 100, 1 <= M <= 10^9)第2 - N + 1行:每行N个数,对应N * N矩阵中的1行。(0 <= N[i] <= 10^9)


Output


共N行,每行N个数,对应M次方Mod (10^9 + 7)的结果。


Input示例


2 31 11 1


Output示例


4 44 4



#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#define maxn 1000005
#define MOD 1000000007
using namespace std;
typedef long long ll;

ll ans[105][105], p[105][105], h[105][105];
int n, m;
void multi(ll (*k1)[105], ll (*k2)[105]){
	
	memset(h, 0, sizeof(h));
	for(int i = 1; i <= n; i++)
	 for(int j = 1; j <= n; j++){
	  for(int k = 1; k <= n; k++){
	  	(h[i][j] += k1[i][k] * k2[k][j] % MOD) %= MOD;
	  }
	  h[i][j] %= MOD; 
    }
	memcpy(k1, h, sizeof(h));
}
void print(ll (*t)[105]){
	for(int i = 1; i <= n; i++){
	 for(int j = 1; j <= n; j++){
	 	if(j != 1)
	 	 putchar(' ');
	 	printf("%I64d", t[i][j]);
	 }
	 puts("");
    }
}
int main(){
	
//	freopen("in.txt", "r", stdin);
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; i++){
		ans[i][i] = 1;
	 for(int j = 1; j <= n; j++){
	  scanf("%I64d", &p[i][j]);
     }
    }
	while(m){
		if(m&1)
		  multi(ans, p);
		multi(p, p);  
		m >>= 1;
	}
	print(ans);
    return 0;
}