最近越来越爱写面向对象了,可是我还是没有对象。
题意:
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.
可以找递推矩阵,写矩阵快速幂,(Sk, Ak)=(I, A; 0, A)*(Sk-1, Ak-1),或者快速幂的思维,直接二分,
S= ( I+A )*( A+A^2+...+A^(k/2) )
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
#define mxn 40
int N,K,M;
struct matrix{
int a[mxn][mxn];
int n;
void init(int x){
n=x;
memset(a,0,sizeof(a));
}
matrix(int x=0){
init(x);
}
matrix operator + (const matrix& in)const{
matrix ret(n);
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
ret.a[i][j]=(a[i][j]+in.a[i][j])%M;
return ret;
}
matrix operator * (const matrix& in)const{
matrix ret(n);
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
for(int k=0;k<n;++k){
ret.a[i][j]+=a[i][k]*in.a[k][j];
ret.a[i][j]%=M;
}
return ret;
}
void read(){
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
scanf("%d",&a[i][j]);
}
void print(){
for(int i=0;i<n;++i){
for(int j=0;j<n;++j)
!j ? printf("%d",a[i][j]) : printf(" %d",a[i][j]);
puts("");
}
}
}A,ans,I;
matrix quick_power(matrix x,int k){
if(k==1) return x;
matrix tem=quick_power(x,k/2);
if(k%2) return tem*tem*x;
return tem*tem;
}
matrix solve(int k){
if(k==1) return A;
matrix tem=solve(k/2);
if(k%2) return (I+quick_power(A,k/2))*tem+quick_power(A,k);
return (I+quick_power(A,k/2))*tem;
}
int main(){
while(scanf("%d%d%d",&N,&K,&M)!=EOF){
A.init(N);
I.init(N);
for(int i=0;i<I.n;++i) I.a[i][i]=1;
A.read();
ans=solve(K);
ans.print();
}
return 0;
}