【Matrix Multiplication】 【POJ 3233】Matrix Power Series
topic
Given an × n matrix A and a positive integer k, find the sum S = A + A2 + A3 +… + Ak.
Given an n × n matrix a and a positive integer k, the sum S=a+A2+A3+ …+Ak.
Baidu translator
enter
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. The
input contains only 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 rows, each row contains n non-negative integers below 32768, and the elements of A are given in the main order of the row.
Output
Output the elements of S modulo m in the same way as A is given. Output the elements of S modulo m in the same way as A is given
.
Sample
input
2 2 4
0 1
1 1
output
1 2
2 3
Problem-solving ideas
Simplify
the meaning of the question first.
It is easy to deduce that the answer matrix is {a n-1 , sn-2} and the
multiplication matrix is
Then convert back.
The multiplication matrix (1,1) becomes matrix A
(1,2) and (2,2) becomes the identity matrix (that is, the value on the diagonal is 1, and the other grids are 0)
Because the product of a matrix multiplied by the identity matrix is equal to this matrix
, the multiplication matrix of the sample is as long as this
Code
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
struct lzf{
long long n,m,h[120][120];
}a,b,x;
long long n,k,mo;
lzf operator * (lzf l,lzf y)
{
x.n=l.n,x.m=y.m;
memset(x.h,0,sizeof(x.h));
for (int i=1;i<=x.n;i++)
for (int k=1;k<=l.m;k++)
for (int j=1;j<=x.m;j++)
x.h[i][j]=(x.h[i][j]+l.h[i][k]*y.h[k][j]%mo)%mo;
return x;
}
void power(long long n)
{
while (n)
{
if (n & 1) a=a*b;
b=b*b;
n>>=1;
}
}
int main()
{
scanf("%lld%lld%lld",&n,&k,&mo);
a.n=n,a.m=2*n;
b.n=b.m=2*n;
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
{
scanf("%lld",&a.h[i][j]); //输入矩阵A
b.h[i][j]=a.h[i][j]; //相乘矩阵(1,1)是矩阵A
}
for (int i=1;i<=n;i++)
b.h[i][i+n]=b.h[i+n][i+n]=1; //(1,2)(2,2)是正对角线为1
power(k);
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
printf("%lld ",a.h[i][j+n]);
printf("\n");
} //输出最后的和
return 0;
}