poj3233 Matrix Power Series

该博客介绍了一个问题,即给定一个n×n的矩阵A和一个正整数k,如何找到S=A+A^2+A^3+...+A^k的和,其中输入包含矩阵A的元素和范围限制,输出是对m取模后的矩阵S的元素。

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
跟上一题差不多,只不过元素要换成矩阵。
然后递推式就是:

[00A10][110A]n

当然这里的元素指的是矩阵。0代表0矩阵,1代表单位矩阵,A代表所给的矩阵。
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>

using namespace std;
int n,k,mod;

struct matrix
{
    int a[30][30];
    matrix operator *(const matrix &b)const
    {
        matrix ans;
        for(int i = 0; i < n; ++i)
            for(int k = 0; k < n; ++k)if(a[i][k])
                    for(int j = 0; j < n; ++j)
                    {
                        ans.a[i][j] = (ans.a[i][j] + a[i][k]*b.a[k][j])%mod;
                    }
        return ans;
    }
    matrix operator +(const matrix &b)const
    {
        matrix ans;
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < n; ++j)
            {
                ans.a[i][j] = (a[i][j]+b.a[i][j])%mod;
            }
        return ans;
    }
    matrix()
    {
        memset(a,0,sizeof a);
    }
} A,one;
struct Bmatrix
{
    matrix a[2][2];
    Bmatrix operator *(const Bmatrix &b)const
    {
        Bmatrix ans;
        for(int i = 0; i < 2; ++i)
            for(int k = 0; k < 2; ++k)
                for(int j = 0; j < 2; ++j)
                {
                    ans.a[i][j] = ans.a[i][j] + a[i][k]*b.a[k][j];
                }
        return ans;
    }

};

matrix F()
{
    Bmatrix ans,base;
    ans.a[0][1] = A;
    base.a[0][0] = base.a[1][0] = one;
    base.a[1][1] = A;
    while(k)
    {
        if(k&1)ans = ans*base;
        base = base*base;
        k >>= 1;
    }
    return ans.a[0][0];

}




int main()
{
    scanf("%d%d%d",&n,&k,&mod);
    for(int i = 0; i < n; ++i)
    {
        one.a[i][i] = 1;
        for(int j = 0; j < n; ++j)
        {
            scanf("%d",&A.a[i][j]);
            A.a[i][j] %= mod;
        }
    }
    matrix ans = F();
    for(int i = 0; i < n; ++i)
        for(int j = 0; j < n; ++j)
        {
            if(j == n-1)printf("%d\n",ans.a[i][j]);
            else printf("%d ",ans.a[i][j]);
        }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值