当前位置: 代码迷 >> 综合 >> 洛谷 P3390 【模板】矩阵快速幂
  详细解决方案

洛谷 P3390 【模板】矩阵快速幂

热度:106   发布时间:2023-09-20 18:36:18.0

矩阵乘法百度上已经讲得很清楚了

https://baike.baidu.com/item/%E7%9F%A9%E9%98%B5%E4%B9%98%E6%B3%95/5446029?fr=aladdin

这个模板题记得全部都要开long long

#include<cstdio>
#include<cstring>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
#define _for(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;typedef long long ll;
const int MAXN = 100 + 10;
const int MOD = 1e9 + 7;
struct mat
{ll m[MAXN][MAXN];mat() { memset(m, 0, sizeof(m)); }
}a, e;
ll n, k;mat operator * (const mat& a, const mat& b)
{mat res;_for(i, 1, n)_for(j, 1, n)_for(k, 1, n)res.m[i][j] = (res.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;return res;
}mat pow(mat a, ll b)
{mat res;_for(i, 1, n) res.m[i][i] = 1;for(; b; b >>= 1){if(b & 1) res = res * a;a = a * a;}return res;
}int main()
{scanf("%lld%lld", &n, &k);_for(i, 1, n)_for(j, 1, n)scanf("%lld", &a.m[i][j]);mat ans = pow(a, k);_for(i, 1, n)_for(j, 1, n){printf("%lld", ans.m[i][j]);printf("%c", j == n ? '\n' : ' ');}return 0;
}