uva 11149(矩阵倍增)

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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值