码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-10 18:07:31      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:


技术分享

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


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

标签:

原文地址:http://blog.csdn.net/kalilili/article/details/44980721

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!