- 问答
- 2015-07-16 11:36:24 @
题目大意是给你一个A矩阵,然后求S=A+A^2+A^3+...+A^k(原题POJ3233);
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cstdio>
#include <queue>
#include <ctime>
long long a[61][61];
long long b[61][61];
long long ans[61][61];
long long c[31][61];
long long i,j,k,l,n,m;
long long work(long long a,long long b,long long c){
long long ans=0;
while (b>0) {
if (b%2==1) ans=(ans+a)%m;
a=(a+a)%m;
b=b/2;
}
ans=(ans+c)%m;
return ans;
}
int main(){
freopen("Poj 3233.in","r",stdin);
freopen("Poj 3233.out","w",stdout);
scanf("%I64d%I64d%I64d",&n,&k,&m);
for (i=1;i<=n;i++){
for (j=1;j<=n;j++){
if (i==j){
c[i][j]=a[i][j]=ans[i][j]=ans[i+n][j+n]=1;
}
scanf("%I64d",&c[i][j+n]);
a[i][j+n]=a[i+n][j+n]=c[i][j+n];
}
}
k-=1;
while (k>0) {
if (k%2==1){
for (i=1;i<=2*n;i++){
for (j=1;j<=2*n;j++){
for (l=1;l<=2*n;l++){
b[i][j]=work(ans[i][l],a[l][j],b[i][j]);
}
}
}
for (i=1;i<=2*n;i++){
for (j=1;j<=2*n;j++){
ans[i][j]=b[i][j];
b[i][j]=0;
}
}
}
for (i=1;i<=2*n;i++){
for (j=1;j<=2*n;j++){
for (l=1;l<=2*n;l++){
b[i][j]=work(a[i][l],a[l][j],b[i][j]);
}
}
}
for (i=1;i<=2*n;i++){
for (j=1;j<=2*n;j++){
a[i][j]=b[i][j];
b[i][j]=0;
}
}
k=k/2;
}
for (i=1;i<=n;i++){
for (j=1;j<=2*n;j++){
for (l=1;l<=2*n;l++){
b[i][j]=work(c[i][l],ans[l][j],b[i][j]);
}
}
}
for (i=1;i<=n;i++){
for (j=n+1;j<=2*n;j++){
printf("%I64d ",b[i][j]);
}
printf("\n");
}
fclose(stdin); fclose(stdout);
}