POJ -- 3233 求“等比矩阵”前n(n <=10^9)项和

时间:2023-03-10 01:53:30
POJ -- 3233  求“等比矩阵”前n(n <=10^9)项和
Matrix Power Series

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 思路:1.最基本的,需要用到矩阵快速幂 2.快速幂求完之后怎样快速求和?若逐项累加求和必然会超时,这时需要求递推公式:(1)若n为偶数,则:S(n) = A^(n/2)*S(n/2)+s(n/2);(2)若n为奇数 S(n) = A^(n/2+1) + S(n/2)*A^(n/2+1) + S(n/2),公式不难推,写几个就发现规律了。这样就把时间复杂度降下来了。
 #include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
int n, m;
typedef struct Matrix{
int m[][];
Matrix(){
memset(m, , sizeof(m));
}
}Matrix;
Matrix mtAdd(Matrix A, Matrix B){
for(int i = ;i < n;i ++)
for(int j = ;j < n;j ++){
A.m[i][j] += B.m[i][j];
A.m[i][j] %= m;
}
return A;
}
Matrix mtMul(Matrix A, Matrix B){
Matrix tmp;
for(int i = ;i < n;i ++)
for(int j = ;j < n;j ++)
for(int k = ;k < n;k ++){
tmp.m[i][j] += A.m[i][k]*B.m[k][j];
tmp.m[i][j] %= m;
}
return tmp;
}
Matrix mtPow(Matrix A, int k){
if(k == ) return A;
Matrix tmp = mtPow(A, k >> );
Matrix res = mtMul(tmp, tmp);
if(k&) res = mtMul(res, A);
return res;
}
Matrix mtSum(Matrix A, int k){
if(k == ) return A;
Matrix tmp = mtSum(A, k/);
if(k&){
Matrix t = mtPow(A, k/+);
Matrix tmp1 = mtMul(tmp, t);
Matrix tmp2 = mtAdd(t, tmp);
return mtAdd(tmp1, tmp2);
}else return mtAdd(tmp, mtMul(mtPow(A, k/), tmp));
}
int main(){
int k, tmp;
/* freopen("in.c", "r", stdin); */
while(~scanf("%d%d%d", &n, &k, &m)){
Matrix M;
for(int i = ;i < n;i ++)
for(int j = ;j < n;j ++){
scanf("%d", &tmp);
M.m[i][j] = tmp;
}
M = mtSum(M, k);
for(int i = ;i < n;i ++){
for(int j = ;j < n;j ++)
printf("%d ", M.m[i][j]);
puts("");
}
}
return ;
}