Matrix Power Series

Description

Time Limit: 3000MS Memory Limit: 131072K
Given a nn 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(n30) , k(k109) 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

Solution & Code

法一: k 的范围是109,考虑分治。
Si=A+A2+...+Ai
S2i=Ai+1+Ai+2+...+A2i
S2i=SiAi

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

typedef long long ll;

const int maxr = 35;

int n, k;
ll m;

struct matrix{ll val[maxr][maxr];};
matrix U, V, Z, I;

matrix multiply(matrix A, matrix B){

    matrix C = Z;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            for(int k = 1; k <= n; ++k){
                C.val[i][j] += A.val[i][k] * B.val[k][j];
                C.val[i][j] %= m;
            }
    return C;
}

matrix add(matrix A, matrix B){

    matrix C = Z;
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j){
            C.val[i][j] = A.val[i][j] + B.val[i][j];
            C.val[i][j] %= m;
        }
    return C;
}

matrix powmod(matrix A, int x){

    matrix B = I;
    while(x){
        if(x & 1) B = multiply(B, A);
        x = x >> 1;
        A = multiply(A, A);
    }
    return B;
}

matrix calc(int x){

    if(x == 1) return U;
    int y = x >> 1;
    matrix L = calc(y);
    matrix R = multiply(L, powmod(U, y));
    if(y * 2 != x) return add(add(L, R), powmod(U, x));
        else return add(L, R);
}

int main(){

    cin >> n >> k >> m;
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= n; ++j) cin >> U.val[i][j];
        I.val[i][i] = 1;
    }
    V = calc(k);
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= n; ++j) printf("%lld ", V.val[i][j]);
        puts("");
    }

    return 0;
}

法二:如果求 s=a+a2+...ak 我们可以考虑用矩阵快速幂对其进行加速,求 S=A+A2+A3++Ak 时则可以构造一个元素为矩阵的矩阵,然后用矩阵快速幂加速。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值