Time Limit: 3000MS | Memory Limit: 131072K | |
Total Submissions: 12686 | Accepted: 5431 |
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
Source
题型:数论
题意:A是n*n的矩阵,计算 S = A + A^2 + A^3 + … + A^k。
分析:
首先可以想到用矩阵快速幂算出A^k,但是TLE,因为加的项过多,所以要将计算规模减小。
使用二分的思想进行处理:
对于k=2n,设B = A + A^2 + .. + A^n ,则 S = B * An + B。
对于k=2n+1,S = B * A^n + B + A^(2n+1)。
这样就可以不断递归,每次规模减小一半。
(一开始用了LL,TLE了好久。。。)
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n,k,m;
struct Matrix
{
int mat[31][31];
};
Matrix Mod(Matrix a){
Matrix res;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
res.mat[i][j]=a.mat[i][j]%m;
}
}
return res;
}
Matrix mul(Matrix m1,Matrix m2)
{
Matrix ans;
memset(ans.mat,0,sizeof(ans.mat));
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
ans.mat[i][j]=(ans.mat[i][j]+m1.mat[i][k]*m2.mat[k][j]%m)%m;
return Mod(ans);
}
Matrix pow(Matrix m1,int b)
{
Matrix ans;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
ans.mat[i][j]=(i==j?1:0);
while(b)
{
if(b&1)
ans=mul(ans,m1);
m1=mul(m1,m1);
b/=2;
}
return ans;
}
Matrix Add(Matrix a,Matrix b){
Matrix res;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
res.mat[i][j]=(a.mat[i][j]+b.mat[i][j])%m;
}
}
return res;
}
Matrix Sum(Matrix b,int t){
Matrix res;
Matrix a=Mod(b);
if(t==1){
res=a;
return res;
}
else{
Matrix k=Sum(a,t/2);
if(t&1){
Matrix o=pow(a,t/2+1);
return Add(Add(k,o),mul(o,k));
}
else{
Matrix o=pow(a,t/2);
return Add(k,mul(k,o));
}
}
}
int main(){
Matrix a;
scanf("%d%d%d",&n,&k,&m);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d",&a.mat[i][j]);
a.mat[i][j]%=m;
}
}
Matrix ans=Sum(a,k);
for(int i=0;i<n;i++){
printf("%d",ans.mat[i][0]);
for(int j=1;j<n;j++){
printf(" %d",ans.mat[i][j]);
}
printf("\n");
}
return 0;
}