TZOJ7929: Matrix Power Series(矩阵k次幂前缀和模板、二分优化)

TZOJ7929: Matrix Power Series

题目传送门

描述

Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.

输入

The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 10^9) and m (m < 10^4). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.

输出

Output the elements of S modulo m in the same way as A is given.

样例输入
2 2 4
0 1
1 1
样例输出
1 2
2 3
解题思路

很明显这是一道矩阵k次幂前缀和模板题目,然而k达到1e9,如果直接使用矩阵快速幂求解肯定会超时,所以考虑进行二分优化。参考

代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define IOS ios::sync_with_stdio(0), cin.tie(0)
const ll N = 1e1 * 3 + 5;
struct node {
    ll a[N][N];
    node() { memset(a, 0, sizeof a);}
};
ll n, kk, mod;
node mul(node x, node y) {
    node z;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            for (int k = 0; k < n; ++k) {
                z.a[i][j] = (z.a[i][j] + x.a[i][k] * y.a[k][j]) % mod;
            }
        }
    }
    return z;
}
node add(node x, node y) {
    node z;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            z.a[i][j] = (x.a[i][j] + y.a[i][j]) % mod;
        }
    }
    return z;
}
node fqpow(node a, ll b) {
    node res;
    for (int i = 0; i < n; ++i) {
        res.a[i][i] = 1;
    }
    while (b) {
        if(b & 1) res = mul(res, a);
        a = mul(a, a);
        b >>= 1;
    }
    return res;
}
node erfen(node a, ll x) {
    if(x == 1) return a;
    node res;
    for (int i = 0; i < n; ++i) {
        res.a[i][i] = 1;
    }
    res = add(res, fqpow(a, x / 2));
    res = mul(res, erfen(a, x / 2));
    if(x & 1) res = add(res, fqpow(a, x));
    return res;
}
void solve() {
    cin >> n >> kk >> mod;
    node A;
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            cin >> A.a[i][j];
        }
    }
    node ans = erfen(A, kk);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if(j) cout << " ";
            cout << ans.a[i][j];
        }
        cout << endl;
    }
}

int main( ){
    IOS;
//    ll t; cin >> t;
    ll t = 1;
    while (t--) solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值