1. 程式人生 > 實用技巧 >POJ3233 Matrix Power Series

POJ3233 Matrix Power Series

Matrix Power Series

Description

Given an×nmatrixAand a positive integerk, find the sumS=A+A2+A3+ … +Ak.

Input

The input contains exactly one test case. The first line of input contains three positive integersn(n≤ 30),k(k≤ 109) andm(m< 104). Then follownlines each containingnnonnegative integers below 32,768, givingA

’s elements in row-major order.

Output

Output the elements ofSmodulomin the same way asAis given.

Sample Input

2 2 4
0 1
1 1

Sample Output

1 2
2 3


題目大意:給出一個一個n*n的矩陣、k和m,求 S = A + A

2

 + A

3

 + ... + A

k

.輸出矩陣S(每個元素對m取模)

AC程式碼:
#include<iostream>
#include<cstring>
using namespace std;
#define ll long long const int maxn=30; int mod=10000; ll T,n,k; struct matrix{ ll a[maxn][maxn]; matrix(){ memset(a,0,sizeof(a)); } }; struct Matrix{ matrix b[2][2]; Matrix(){ memset(b,0,sizeof(b)); } }; matrix mul(matrix a,matrix b){ matrix res; for(int i=0;i<n;i++)
for(int j=0;j<n;j++) for(int k=0;k<n;k++) res.a[i][j] = (res.a[i][j] + a.a[i][k] * b.a[k][j])%mod; return res; } matrix add(matrix a,matrix b){ matrix res; for(int i=0;i<n;i++) for(int j=0;j<n;j++) res.a[i][j] = (a.a[i][j] + b.a[i][j])%mod; return res; } Matrix mul(Matrix a,Matrix b){ Matrix res; for(int i=0;i<2;i++) for(int j=0;j<2;j++) for(int k=0;k<2;k++) res.b[i][j] = add(res.b[i][j] , mul(a.b[i][k] , b.b[k][j])); return res; } matrix qpow(matrix A,ll m){//方陣A的m次冪 matrix ans; for(int i=0;i<n;i++) ans.a[i][i]=1; //單位矩陣 while(m){ if(m&1)ans=mul(ans,A); A=mul(A,A); m>>=1; } return ans; } Matrix qpow(Matrix A,ll m){ Matrix ans; for(int i=0;i<2;i++) for(int j=0;j<n;j++) ans.b[i][i].a[j][j]=1; //單位矩陣 while(m){ if(m&1)ans=mul(ans,A); A=mul(A,A); m>>=1; } return ans; } Matrix M; int main() { cin>>n>>k>>mod; matrix A; for(int i=0;i<n;i++) for(int j=0;j<n;j++) cin>>M.b[0][0].a[i][j]; for(int i=0;i<n;i++){ M.b[0][1].a[i][i]=1; M.b[1][1].a[i][i]=1; } Matrix res=qpow(M,k+1); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(i==j){ if(res.b[0][1].a[i][j]==0) cout<<mod-1<<' '; else cout<<res.b[0][1].a[i][j]-1<<' '; }else cout<<res.b[0][1].a[i][j]<<' '; } cout<<endl; } }