poj 3233 Matrix Power Series(矩阵幂的和,矩阵快速幂)

此题要求的是A+A^2+A^3...+A^k,当然逐个求出作和n^3*k复杂度肯定是要超时的。 所以可以构造一个矩阵Sk = I(单位矩阵) + A + A^2 + A^3...+ A^k-1,


Sk = Sk-1 + Ak-1.


所以就可以构造出矩阵快速幂的形式:



每个方格就是一个n*n的矩阵。 要求A+A^2+A^3...+A^k就是要求Sk+1 - I,求出矩阵的k+1次幂后的2n*2n的大矩阵的右上角的小矩阵即使Sk+1,然后减去单位矩阵即是答案。



代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
ll n, k, mod;

struct node
{
    ll s[100][100];
    void init(void){ memset(s, 0, sizeof(s)); }
};

void show(node a, int t)
{
    for(int i = 0; i < t; i++)
        for(int j = 0; j < t; j++)
        {
            printf("%d ", a.s[i][j]);
            if(j == t-1) printf("\n");
        }
}

node mul(node a, node b)
{
    node t;
    t.init();
    for(int i = 0; i < 2*n; i++)
        for(int j = 0; j < 2*n; j++)
            for(int k = 0; k < 2*n; k++)
                t.s[i][j] = (t.s[i][j]+a.s[i][k]*b.s[k][j])%mod;
    return t;
}

node mt_pow(node p, int m)
{
    node q;
    q.init();
    for(int i = 0; i < 2*n; i++)
        q.s[i][i] = 1;
    while(m)
    {
        if(m&1) q = mul(q, p);
        p = mul(p, p);
        m /= 2;
    }
    return q;
}

int main(void)
{
    while(~scanf("%lld%lld%lld", &n, &k, &mod))
    {
        node base;
        base.init();
        for(int i = 0; i < n; i++)
            for(int j = 0; j < 2*n; j  ++)
                if(i == j || i+n == j) base.s[i][j] = 1;
        for(int i = n; i < 2*n; i++)
            for(int j = n; j < 2*n; j++)
                scanf("%d", &base.s[i][j]);
//        show(base, 2*n);
        node ans = mt_pow(base, k+1);
//        show(ans, 2*n);
        for(int i = 0; i < n; i++)
        {
            for(int j = n; j < 2*n; j++)
            {
                if(j-n) printf(" ");
                if(i+n == j) printf("%lld", (ans.s[i][j]-1+mod)%mod);
                else printf("%lld", ans.s[i][j]%mod);
            }
            printf("\n");
        }
    }
    return 0;
}



Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 21455 Accepted: 8997

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

Source

POJ Monthly--2007.06.03, Huang, Jinsong

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值