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
跟上一题差不多,只不过元素要换成矩阵。
然后递推式就是:
[00A10]∗[110A]n
当然这里的元素指的是矩阵。0代表0矩阵,1代表单位矩阵,A代表所给的矩阵。
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
int n,k,mod;
struct matrix
{
int a[30][30];
matrix operator *(const matrix &b)const
{
matrix ans;
for(int i = 0; i < n; ++i)
for(int k = 0; k < n; ++k)if(a[i][k])
for(int j = 0; j < n; ++j)
{
ans.a[i][j] = (ans.a[i][j] + a[i][k]*b.a[k][j])%mod;
}
return ans;
}
matrix operator +(const matrix &b)const
{
matrix ans;
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
{
ans.a[i][j] = (a[i][j]+b.a[i][j])%mod;
}
return ans;
}
matrix()
{
memset(a,0,sizeof a);
}
} A,one;
struct Bmatrix
{
matrix a[2][2];
Bmatrix operator *(const Bmatrix &b)const
{
Bmatrix ans;
for(int i = 0; i < 2; ++i)
for(int k = 0; k < 2; ++k)
for(int j = 0; j < 2; ++j)
{
ans.a[i][j] = ans.a[i][j] + a[i][k]*b.a[k][j];
}
return ans;
}
};
matrix F()
{
Bmatrix ans,base;
ans.a[0][1] = A;
base.a[0][0] = base.a[1][0] = one;
base.a[1][1] = A;
while(k)
{
if(k&1)ans = ans*base;
base = base*base;
k >>= 1;
}
return ans.a[0][0];
}
int main()
{
scanf("%d%d%d",&n,&k,&mod);
for(int i = 0; i < n; ++i)
{
one.a[i][i] = 1;
for(int j = 0; j < n; ++j)
{
scanf("%d",&A.a[i][j]);
A.a[i][j] %= mod;
}
}
matrix ans = F();
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
{
if(j == n-1)printf("%d\n",ans.a[i][j]);
else printf("%d ",ans.a[i][j]);
}
return 0;
}