您的位置:首页 > 其它

线性代数(矩阵乘法):POJ 3233 Matrix Power Series

2016-06-07 20:23 507 查看
Matrix Power Series

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 <cstring>
#include <cstdio>
using namespace std;
const int maxn=50;
int mod,n,K;
struct Matrix{
int mat[maxn][maxn];
Matrix(){
memset(mat,0,sizeof(mat));
}

Matrix operator +(Matrix a){
Matrix r;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
(r.mat[i][j]=(mat[i][j]+a.mat[i][j])%mod)%=mod;
return r;
}

Matrix operator *(Matrix a){
Matrix r;
for(int i=1,s;i<=n;i++)
for(int k=1;k<=n;k++){
s=mat[i][k];
for(int j=1;j<=n;j++)
(r.mat[i][j]+=(s*a.mat[k][j])%mod)%=mod;
}
return r;
}

Matrix operator ^(int k){
Matrix r,x;
for(int i=1;i<=n;i++)
r.mat[i][i]=1;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
x.mat[i][j]=mat[i][j];
while(k){
if(k&1)
r=r*x;
k>>=1;
x=x*x;
}
return r;
}
}A,B,ans;
Matrix Solve(int k){
if(k==1)return A;
if(k%2)return A+A*Solve(k-1);
else return ((A^(k/2))+B)*Solve(k/2);
}
int main(){
#ifndef ONLINE_JUDGE
//freopen("","r",stdin);
//freopen("","w",stdout);
#endif
scanf("%d%d%d",&n,&K,&mod);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%d",&A.mat[i][j]);

for(int i=1;i<=n;i++)
B.mat[i][i]=1;

ans=Solve(K);

for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++)
printf("%d ",ans.mat[i][j]);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: