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),公式不难推,写几个就发现规律了。这样就把时间复杂度降下来了。

 1 #include<cstdio>
 2 #include<string>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 int n, m;
 7 typedef struct Matrix{
 8     int m[30][30];
 9     Matrix(){
10         memset(m, 0, sizeof(m));
11     }
12 }Matrix;
13 Matrix mtAdd(Matrix A, Matrix B){
14     for(int i = 0;i < n;i ++)
15         for(int j = 0;j < n;j ++){
16             A.m[i][j] += B.m[i][j];
17             A.m[i][j] %= m;
18         }
19     return A;
20 }
21 Matrix mtMul(Matrix A, Matrix B){
22     Matrix tmp;
23     for(int i = 0;i < n;i ++)
24         for(int j = 0;j < n;j ++)
25             for(int k = 0;k < n;k ++){
26                 tmp.m[i][j] += A.m[i][k]*B.m[k][j];
27                 tmp.m[i][j] %= m;
28             }
29     return tmp;
30 }
31 Matrix mtPow(Matrix A, int k){
32     if(k == 1) return A;
33     Matrix tmp = mtPow(A, k >> 1);
34     Matrix res = mtMul(tmp, tmp);
35     if(k&1) res = mtMul(res, A);
36     return res;
37 }
38 Matrix mtSum(Matrix A, int k){
39     if(k == 1) return A;
40     Matrix tmp = mtSum(A, k/2);
41     if(k&1){
42         Matrix t = mtPow(A, k/2+1);
43         Matrix tmp1 = mtMul(tmp, t);
44         Matrix tmp2 = mtAdd(t, tmp);
45         return mtAdd(tmp1, tmp2);
46     }else return mtAdd(tmp, mtMul(mtPow(A, k/2), tmp));
47 }
48 int main(){
49     int k, tmp;
50     /* freopen("in.c", "r", stdin); */
51     while(~scanf("%d%d%d", &n, &k, &m)){
52         Matrix M;
53         for(int i = 0;i < n;i ++)
54             for(int j = 0;j < n;j ++){
55                 scanf("%d", &tmp);
56                 M.m[i][j] = tmp;
57             }
58         M = mtSum(M, k);
59         for(int i = 0;i < n;i ++){
60             for(int j = 0;j < n;j ++)
61                 printf("%d ", M.m[i][j]);
62             puts("");
63         }
64     }
65     return 0;
66 }

原文地址:https://www.cnblogs.com/anhuizhiye/p/3689295.html