Poj 3233 Matrix Power Series(矩陣乘法)

Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K
Description
Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.
Input
The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.
Output
Output the elements of S modulo m in the same way as A is given.
Sample Input
2 2 4
0 1
1 1
Sample Output
1 2
2 3
Source
POJ Monthly–2007.06.03, Huang, Jinsong
給定矩陣A,求A + A^2 + A^3 + … + A^k的結果

/*
矩陣乘法經典題.
一開始並沒有想出來orz.
發現正解好神奇.
這種題就應該先推出遞推式子再構造矩陣.
本來還想矩陣套矩陣來着
弱啊.
學習了一下單位矩陣的用法.
題解:http://www.cnblogs.com/justPassBy/p/4448630.html 
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#define MAXN 61
#define LL long long
using namespace std;
LL n,m,k,ans[MAXN][MAXN],b[MAXN][MAXN],c[MAXN][MAXN];
LL mul(LL x,LL y)
{
    LL tot=0;
    while(y)
    {
        if(y&1) tot=(tot+x)%m;
        x=(x+x)%m;
        y>>=1;
    }
    return tot;
}
void mi()
{
    while(k)
    {
        if(k&1)
        {
            for(int i=1;i<=n*2;i++)
              for(int j=1;j<=n*2;j++)
                for(int k=1;k<=n*2;k++)
                  c[i][j]=(c[i][j]+ans[i][k]*b[k][j]%m)%m;
            for(int i=1;i<=n*2;i++)
              for(int j=1;j<=n*2;j++)
                ans[i][j]=c[i][j],c[i][j]=0;
        }
        for(int i=1;i<=n*2;i++)
          for(int j=1;j<=n*2;j++)
            for(int k=1;k<=n*2;k++)
              c[i][j]=(c[i][j]+b[i][k]*b[k][j]%m)%m;
        for(int i=1;i<=n*2;i++)
          for(int j=1;j<=n*2;j++)
            b[i][j]=c[i][j],c[i][j]=0;
        k>>=1;
    }
}
void slove()
{
    k--;
    mi();
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
          cout<<ans[i][j]<<" ";
        printf("\n");
    }
}
void Clear()
{
    memset(b,0,sizeof b);
    memset(ans,0,sizeof ans);
}
int main()
{
    while(~scanf("%lld%lld%lld",&n,&k,&m))
    {
        Clear();
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                cin>>b[i][j];b[i][j]%=m;
                ans[i][j]=ans[i][n+j]=b[i][j];
            }
            b[n+i][i]=b[n+i][n+i]=1;
        }
        slove();
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章