题目:
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
解题报告:是在一道等比数列的求和的基础上增加为矩阵的乘法,不过本质没有修改,还是对这个进行二分操作。
ac代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=35;
struct Mat{
int m[maxn][maxn];
};
int n,k,m;
Mat add(Mat a,Mat b)
{
Mat res;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
res.m[i][j]=(a.m[i][j]+b.m[i][j])%m;
}
return res;
}
Mat mult(Mat a,Mat b)
{
Mat c;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
c.m[i][j]=0;
for(int k=0;k<n;k++)
{
c.m[i][j]+=a.m[i][k]*b.m[k][j];
}
}
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
c.m[i][j]%=m;
return c;
}
Mat powk(Mat a,int k)
{//矩阵快速幂
Mat res;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
res.m[i][j]= (i==j);
while(k)
{
if(k&1)
res=mult(res,a);
a=mult(a,a);
k>>=1;
}
return res;
}
Mat sum(Mat a,int k)
{
if(k==1)
return a;
Mat t=sum(a,k/2);
if(k&1)
{
Mat cur=powk(a,k/2+1);
t=add(t,mult(cur,t));
t=add(t,cur);
}
else
{
Mat cur=powk(a,k/2);
t=add(t,mult(t,cur));
}
return t;
}
int main()
{
while(scanf("%d%d%d",&n,&k,&m)!=EOF)
{
Mat a;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
cin>>a.m[i][j];
a.m[i][j]%=m;
}
Mat ans=sum(a,k);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
printf("%d ",ans.m[i][j]);
printf("\n");
}
}
return 0;
}