Problem B : Power of Matrix |
Time limit: 10 seconds |
Consider an n-by-n matrix A. We define Ak = A * A * ... * A (k times). Here, * denotes the usual matrix multiplication.
You are to write a program that computes the matrix A + A2 + A3 + ... + Ak.
Example
Suppose A = . Then A2 = = , thus:
Such computation has various applications. For instance, the above example actually counts all the paths in the following graph:
Input
Input consists of no more than 20 test cases. The first line for each case contains two positive integers n (≤ 40) and k (≤ 1000000). This is followed by n lines, each containing n non-negative integers, giving the matrix A.
Input is terminated by a case where n = 0. This case need NOT be processed.
Output
For each case, your program should compute the matrix A + A2 + A3 + ... + Ak. Since the values may be very large, you only need to print their last digit. Print a blank line after each case.
Sample Input
3 2 0 2 0 0 0 2 0 0 0 0 0
Sample Output
0 2 4 0 0 2 0 0 0
Problemsetter: Mak Yan Kei
直接暴力肯定超时,用到二分的思想。
a[1] + a[2] + a[3] + ... a[n]
= (1+a[n/2])(a[1]+...+a[n/2])
等比数列求和公式不能直接用,因为(1-q)的逆矩阵不一定存在
开始把结构体中写成了long long 导致爆栈,原因是递归层数较多的时候申请的内存太大了
#include <cstdio>
struct M{
int m[45][45];
};
M ori,ans;
int n,k;
M mul(M a,M b){
M ret;
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
int tem = 0;
for(int k = 0;k < n;k++)
tem += (a.m[i][k]*b.m[k][j])%10;
ret.m[i][j] = tem%10;
}
}
return ret;
}
M sum(M a,M b){
M ret;
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
ret.m[i][j] = (a.m[i][j]%10 + b.m[i][j]%10)%10;
}
}
return ret;
}
M pow(int k){
if(k == 1)
return ori;
M tem = pow(k/2);
M ret = mul(tem,tem);
if(k % 2 == 1)
return mul(ori,ret);
else
return ret;
}
M cal(int k){
if(k == 1)
return ori;
M tem = cal(k/2);
M ret = sum(tem,mul(pow(k/2),tem));
if(k % 2 == 1){
return sum(pow(k),ret);
}
else{
return ret;
}
}
void print(M s){
int i,j;
for(i = 0;i < n;i++){
for(j = 0;j < n-1;j++){
printf("%d ",s.m[i][j]);
}
printf("%d\n",s.m[i][j]);
}
printf("\n");//别忘了格式
}
int main(){
while(scanf("%d%d",&n,&k) && n != 0){
int tem;
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
scanf("%d",&tem);
ori.m[i][j] = tem % 10;
}
}
print(cal(k));
}
return 0;
}