poj 3233 矩阵快速幂

Matrix Power Series
Time Limit: 3000MS Memory Limit: 131072K
Total Submissions: 17981 Accepted: 7608

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


#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;
#define LL long long
#define N 60 + 5
int n, k, mod;

struct Matrix
{
    LL m[N][N];
    Matrix()
    {
        memset(m, 0, sizeof m);
    }
};

Matrix Mul(Matrix a, Matrix b)
{
    int t = 2 * n;
    Matrix tmp;
    for(int k = 1; k <= t; k++)
        for(int i = 1; i <= t; i++)
            for(int j = 1; j <= t; j++)
                tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k]*b.m[k][j]) % mod;
    return tmp;
}

Matrix mul_pow(Matrix a, int k)
{
    Matrix res;
    for(int i = 1; i <= 2 * n; i++)
    res.m[i][i] = 1;
    while(k)
    {
        if(k & 1)
        res = Mul(res, a);
        a = Mul(a, a);
        k >>= 1;
    }
    return res;
}

int main()
{
    while(~scanf("%d%d%d", &n, &k, &mod))
    {
        Matrix M;
        for(int i = 1; i <= n; i++)
        {
            for(int j = 1; j <= n; j++)
            {
                scanf("%lld", &M.m[i][j]);
            }
            M.m[i+n][i] = M.m[i+n][i+n] = 1;
        }
        M = mul_pow(M, k + 1);

        for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
        {
            LL a = M.m[i+n][j];
            if(i == j) a = (a + mod - 1) % mod;
            j == n ? printf("%lld\n", a) : printf("%lld ", a);
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值