当前位置: 代码迷 >> 综合 >> 51Nod 1113——矩阵快速幂【矩阵快速幂模板】
  详细解决方案

51Nod 1113——矩阵快速幂【矩阵快速幂模板】

热度:99   发布时间:2023-12-16 22:51:56.0

题目传送门


给出一个N * N的矩阵,其中的元素均为正整数。求这个矩阵的M次方。由于M次方的计算结果太大,只需要输出每个元素Mod (10^9 + 7)的结果。

Input

第1行:2个数N和M,中间用空格分隔。N为矩阵的大小,M为M次方。(2 <= N <= 100, 1 <= M <= 10^9) 第2 - N + 1行:每行N个数,对应N * N矩阵中的1行。(0 <= Ni <= 10^9)

Output

共N行,每行N个数,对应M次方Mod (10^9 + 7)的结果。

Sample Input

2 3
1 1
1 1

Sample Output

4 4
4 4


题解

  • 矩阵快速幂模板题

AC-Code

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 110;
const int mod = 1e9 + 7;
#define mod(x) ((x)%mod)int n;struct mat {
    int m[maxn][maxn];mat() {
    memset(m, 0, sizeof m);}
}unit;mat operator * (mat a, mat b) {
    mat ret;ll x;for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j) {
    x = 0;for (int k = 0; k < n; ++k)x += mod((ll)a.m[i][k] * b.m[k][j]);ret.m[i][j] = mod(x);}return ret;
}void init_unit() {
    for (int i = 0; i < maxn; ++i)unit.m[i][i] = 1;
}mat pow_mat(mat a, ll n) {
    mat ret = unit;while (n) {
    if (n & 1)	ret = ret * a;a = a * a;n >>= 1;}return ret;
}int main() {
    ll x;init_unit();while (cin >> n >> x) {
    mat a;for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j)cin >> a.m[i][j];a = pow_mat(a, x);for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j) {
    if (j + 1 == n)cout << a.m[i][j] << endl;else cout << a.m[i][j] << " ";}}return 0;
}