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
在做了矩阵快速幂的入门之后,又做了这道题,发现好难呀,特别是找转移式子很难推,这次的题又用到了二分+快速幂,用的很巧妙,多看几遍就会了
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stdio.h>
using namespace std;
int n,m;
struct uuu
{
int u[50][50];
}s,v;
uuu mult(uuu x,uuu y)
{
uuu ans;
memset(ans.u,0,sizeof(ans.u));
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
{
for(int k=0;k<n;k++)
ans.u[a][b]=(ans.u[a][b]+x.u[a][k]*y.u[k][b])%m;
}
}
return ans;
}
uuu poww(uuu s,int k)
{
uuu ans;
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
{
if(a==b)
{
ans.u[a][b]=1;
}
else
ans.u[a][b]=0;
}
}
while(k)
{
if(k&1)
ans=mult(ans,s);
s=mult(s,s);
k>>=1;
}
return ans;
}
uuu add(uuu x,uuu y)
{
uuu ans;
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
ans.u[a][b]=(x.u[a][b]+y.u[a][b])%m;
}
return ans;
}
uuu sum(uuu s,int k)
{
uuu temp,y;
if(k==1)return s;
temp=sum(s,k/2);
if(k&1)
{
y=poww(s,k/2+1);
temp=add(temp,mult(temp,y));
return add(temp,y);
}
else
{
y=poww(s,k/2);
temp=add(mult(y,temp),temp);
return temp;
}
}
int main()
{
int k,x;
scanf("%d%d%d",&n,&k,&m);
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
{
scanf("%d",&x);
s.u[a][b]=x%m;
}
}
v=sum(s,k);
for(int a=0;a<n;a++)
{
for(int b=0;b<n;b++)
{
printf("%d",v.u[a][b]);
if(b!=n-1)
printf(" ");
}
printf("\n");
}
return 0;
}