UVA 11149-Power of Matrix (等比矩阵求和)


Download as PDF

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



和POJ 3233 - Matrix Power Series一样http://blog.csdn.net/kalilili/article/details/44926947

// 172 ms 
 
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

int n,m;
struct mat
{
    int a[45][45];
    mat()
    {
        memset(a,0,sizeof(a));
    }
};

mat A;
mat I;

mat add(mat m1,mat m2)
{
    mat ans;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            ans.a[i][j]=(m1.a[i][j]+m2.a[i][j])%10;
    return ans;
}
mat mul(mat m1,mat m2)
{
    mat ans;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            if(m1.a[i][j])
                for(int k=1;k<=n;k++)
                    ans.a[i][k]=(ans.a[i][k]+m1.a[i][j]*m2.a[j][k])%10;
    return ans;
}
mat quickmul(mat m,int k)
{
    mat ans=I;
    while(k)
    {
        if(k&1) ans=mul(ans,m);
        m=mul(m,m);
        k>>=1;
    }
    return ans;
}
void print(mat m)
{
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            printf("%d%c",m.a[i][j],j==n? '\n':' ');
}

mat getsum(int k)
{
    if(k==1) return A;
    mat ans=getsum(k/2);
    if(k&1)
    {
        mat t=quickmul(A,k/2+1);
        ans=add(mul(add(I,t),ans),t);
    }
    else
    {
        mat t=quickmul(A,k/2);
        ans=mul(add(I,t),ans);
    }
    return ans;
}

int main()
{
    while(scanf("%d%d",&n,&m),n)
    {
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&A.a[i][j]),A.a[i][j]%=10;

        for(int i=1;i<=n;i++) I.a[i][i]=1;
        mat ans=getsum(m);
        print(ans);
        puts("");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值