POJ-3233 Matrix Power Series(矩阵快速幂)

Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 23032 Accepted: 9606

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看成一个数,可以构建这样一个矩阵

|A 0|    *    |  A  |

|E E|         |sum|

其中sum为所求答案,E为单位矩阵

#include<cstdio>
#include<algorithm>
#include<string.h>
using namespace std;
int n,mod;
struct Mat{
    int x[31][31],sz;
    Mat(){
        memset(x,0,sizeof(x));
        sz=n;
    }
    void init(){
        for(int i=0;i<sz;i++) x[i][i]=1;
    }
    Mat operator*(const Mat& m)const{
        Mat ret;
        for(int i=0;i<sz;i++)
            for(int j=0;j<sz;j++)
                for(int k=0;k<sz;k++)
                    ret.x[i][j]=(ret.x[i][j]+x[i][k]*m.x[k][j])%mod;
        return ret;
    }
    Mat operator+(const Mat& m)const{
        Mat ret;
        for(int i=0;i<sz;i++)
            for(int j=0;j<sz;j++)
                ret.x[i][j]=(ret.x[i][j]+x[i][j]+m.x[i][j])%mod;
        return ret;
    }
    void print(){
        for(int i=0;i<sz;i++)
            for(int j=0;j<sz;j++)
                printf("%d%c",x[i][j],j==sz-1?'\n':' ');
    }
};
struct MMat{
    Mat a[2][2];
    MMat(){
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                memset(a[i][j].x,0,sizeof(a[i][j].x));
    }
    void init(){
        for(int i=0;i<2;i++) a[i][i].init();
    }
    MMat operator*(const MMat& m)const{
        MMat ret;
        for(int i=0;i<2;i++)
            for(int j=0;j<2;j++)
                for(int k=0;k<2;k++)
                    ret.a[i][j]=ret.a[i][j]+a[i][k]*m.a[k][j];
        return ret;
    }
};
MMat pow(MMat A,int k){
    MMat ret;
    ret.init();
    while(k){
        if(k&1) ret=ret*A;
        A=A*A;
        k>>=1;
    }
    return ret;
}
Mat solve(int k){
    Mat A;
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            scanf("%d",&A.x[i][j]);
    MMat MA,MB;
    MA.a[0][0]=A;
    MA.a[1][0].init();MA.a[1][1].init();
    MB.a[0][0]=A;
    MA=pow(MA,k);
    return (MA*MB).a[1][0];
}
int main(){
    int k;
    //freopen("in.txt","r",stdin);
    while(~scanf("%d%d%d",&n,&k,&mod)){
        Mat A=solve(k);
        A.print();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值