POJ 3233 矩阵快速幂

来源:互联网 发布:喜马拉雅 推荐 知乎 编辑:程序博客网 时间:2024/04/30 03:16
Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072KTotal Submissions: 18608 Accepted: 7867

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 40 11 1

Sample Output

1 22 3
#include<cstdio>#include<iostream>#include<cstring>using namespace std;const int MAX = 65;struct Matrix{    int  map[MAX][MAX];    Matrix()    {       memset(map,0,sizeof(map));}};int n=0,k=0,mod=0;int len=0;Matrix matrixmul(Matrix a,Matrix b) //矩阵乘法{       int i,j,k;       Matrix c;       for (i = 1 ; i <= len; i++)           for (j = 1; j <= len;j++)             {                 c.map[i][j] = 0;                 for (k = 1; k <= len; k++)                     c.map[i][j] += (a.map[i][k] * b.map[k][j])%mod;                 c.map[i][j] %= mod;             }       return c;}         Matrix haha(Matrix a,Matrix b,int n){    while(n)//矩阵的快速幂    {        if(n&1)            b=matrixmul(b,a);        n=n/2;        a=matrixmul(a,a);    }    return b;}int main(){while(scanf("%d%d%d",&n,&k,&mod)!=EOF){Matrix s,b;len=2*n;for(int i=1;i<=n;i++) for(int j=1;j<=n;j++)  scanf("%d",&s.map[i][j]);for(int i=1;i<=n;i++) for(int j=n+1;j<=2*n;j++) { if(j-n==i) { s.map[i][j]=1; } else  s.map[i][j]=0; }for(int i=n+1;i<=2*n;i++) for(int j=n+1;j<=2*n;j++) { if(j==i) { s.map[i][j]=1; } else  s.map[i][j]=0; }  for(int i=1;i<=2*n;i++)    b.map[i][i]=1;s=haha(s,b,k+1);for(int i=1;i<=n;i++)//减去单位矩阵          for(int j=n+1;j<=len;j++)           {                if(i+n==j)                    s.map[i][j]--;                while(s.map[i][j]<0)//为了防止溢出                    s.map[i][j]+=mod;           }        for(int i=1;i<=n;i++)        {            for(int j=n+1;j<len;j++)                printf("%d ",s.map[i][j]);            printf("%d\n",s.map[i][len]);        }}return 0;}
0 0
原创粉丝点击