poj 3233 Matrix Power Series

来源:互联网 发布:2017笔记本推荐 知乎 编辑:程序博客网 时间:2024/06/08 07:17

http://poj.org/problem?id=3233
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
题目大意:给你一个矩阵A,算出 S = A + A^2 + A^3 + … + A^k.并输出矩阵S;

解题思路:由于这题的k比较的而时间只有3秒,除了算快速幂还要求累加,这样很容易超时,所以我们要想办法优化。这里我们可以用二分的方法来优化。
如:S(10) = A + A^2 + A^3 + A^4 + A^5+ A^6 + A^7 + A^8 + A^9+ A^10;
= S(5) + A^5 *S(5);
S(5) = A + A^2 + A^3 + A^4 + A^5;
= S(2) + A^3 + A^3*S(2);
S(2) = S(1) + A * S(1);
S(1) = A;
看到这,我们不难发现规律,那就是当k为奇数时s(k) = s(k/2)+A^(k/2+1)+A^(k/2+1)* s(k/2);
当k为偶数时 s(k) = s(k/2)+A^(k/2)* s(k/2);
利用这个规律就可以吧线性的时间复杂度简化为log(n)了。
具体代码实现:

#include <cstdio>using namespace std;struct Matrix{    int m[35][35];}a;int m;Matrix Mult(Matrix a,Matrix b,int n){    Matrix temp;    for(int i=1;i<=n;i++){        for(int j=1;j<=n;j++)            temp.m[i][j] = 0;    }    for(int i=1;i<=n;i++){        for(int j=1;j<=n;j++)        for(int k=1;k<=n;k++)         temp.m[i][j] = (temp.m[i][j]+(a.m[i][k]*b.m[k][j])%m)%m;    }    return temp;}Matrix Add(Matrix a,Matrix b,int n){    Matrix temp;    for(int i=1;i<=n;i++){        for(int j=1;j<=n;j++)            temp.m[i][j] = 0;    }    for(int i=1;i<=n;i++){        for(int j=1;j<=n;j++)            temp.m[i][j] = (a.m[i][j]+b.m[i][j])%m;    }    return temp;}Matrix QuickPower(Matrix a,int n,int k){    Matrix ans,res;    for(int i=1;i<=n;i++)       for(int j=1;j<=n;j++)       if(i==j)ans.m[i][j] = 1;       else ans.m[i][j] = 0;    res = a;    while(k){        if(k&1)            ans = Mult(ans,res,n);        res = Mult(res,res,n);        k>>=1;    }    return ans;}Matrix work(int n,int k)///核心代码,因为这里我们只要二分分到1时可以直接得到答案,所以直到k=1时返回到上一层,///然后判断这一层的k是计数还是偶数,按照各自的规则算出他们的值然后再返回到上一层,直到结束,这样就可以算出s(k)了。{    if(k == 1)        return a;    Matrix res = work(n,k/2);    Matrix temp;    if(k&1){        temp = Add(res,QuickPower(a,n,k/2+1),n);        res = Add(temp,Mult(QuickPower(a,n,k/2+1),res,n),n);    }    else{        res = Add(res,Mult(QuickPower(a,n,k/2),res,n),n);    }    return res;}int main(){    int n,k;     scanf("%d %d %d",&n,&k,&m);     for(int i=1;i<=n;i++){        for(int j=1;j<=n;j++)            scanf("%d",&a.m[i][j]);     }    Matrix S = work(n,k);    for(int i=1;i<=n;i++)    {        printf("%d",S.m[i][1]);        for(int j=2;j<=n;j++)            printf(" %d",S.m[i][j]);        printf("\n");    }    return 0;}
原创粉丝点击