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;
}