您的位置:首页 > 其它

poj 3233 Matrix Power Series

2014-05-21 09:46 197 查看
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

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

struct mat
{
int t[65][65];
void set()
{
memset(t,0,sizeof(t));
}
} a,b;

mat multiple(mat a,mat b,int n,int p)
{
int i,j,k;
mat temp;
temp.set();
for(i=0; i<n; i++)
for(j=0; j<n; j++)
{
if(a.t[i][j]>0)
for(k=0; k<n; k++)
temp.t[i][k]=(temp.t[i][k]+a.t[i][j]*b.t[j][k])%p;
}
return temp;
}

mat quick_mod(mat b,int n,int m,int p)
{
mat t;
t.set();
for(int i=0;i<n;i++) t.t[i][i]=1;
while(m)
{
if(m&1)
{
t=multiple(t,b,n,p);
}
m>>=1;
b=multiple(b,b,n,p);
}
return t;
}
void init(int n,int m,int p)
{
a.set();
b.set();
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
scanf("%d",&b.t[i][j]);
b.t[i][j+n]=b.t[i][j];
a.t[i][j]=b.t[i][j];
}
for(int i=n;i<2*n;i++)
for(int j=n;j<2*n;j++)
if(i==j) b.t[i][j]=1;

for(int i=n;i<2*n;i++)
for(int j=0;j<n;j++)
if(j+n==i) a.t[i][j]=1;

b=quick_mod(b,2*n,m-1,p);

mat temp;
temp.set();
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
{
for(int k=0; k<2*n; k++)
temp.t[i][j]=(temp.t[i][j]+b.t[i][k]*a.t[k][j])%p;   //错误一点,无限WA
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
printf("%d ",temp.t[i][j]);
puts("");
}
}
int main()
{
int n,m,p;
while(cin>>n>>m>>p)
{
init(n,m,p);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: