当k是偶数,A^1+A^2+...+A^k = (A^1 + A^2 + A^3 +... + A^k/2) + A^k/2 (A^1 + A^2 + A^3 +... + A^k/2),
当k是奇数,A^1+A^2+...+A^k = (A^1 + A^2 + A^3 +... + A^k/2) + A^(1+k/2) + A^(1+k/2) (A^1 + A^2 + A^3 +... + A^k/2)。
然后就可以递归地搞了。
#include <iostream> #include <cstring> using namespace std; #define maxn 33 struct m { int a[maxn][maxn]; void show (int n) { cout << "........." << endl; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cout << a[i][j] << " "; } cout << endl; } cout << "........." << endl; } }gg; int n, mod, k; m add (m a, m b) { m ans; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { ans.a[i][j] = a.a[i][j] + b.a[i][j]; ans.a[i][j] %= mod; } } return ans; } m mul (m a, m b) { m ans; memset (ans.a, 0, sizeof ans.a); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { for (int l = 1; l <= n; l++) { ans.a[i][j] += a.a[i][l]*b.a[l][j]; ans.a[i][j] %= mod; } } } return ans; } m qpow (m res, int k) { if (k == 1) return res; m ans = qpow (res, k/2); ans = mul (ans, ans); if (k&1) ans = mul (ans, res); return ans; } m solve (m res, int k) { if (k == 1) return res; m ans = solve (res, k/2); if (k&1) { m fuck = qpow (res, 1+(int)(k/2)); ans = add (add (fuck, mul (fuck, ans)), ans); } else { m fuck = qpow (res, k/2); ans = add (ans, mul (fuck, ans)); } return ans; } int main () { ios::sync_with_stdio(0); while (cin >> n >> k >> mod) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { cin >> gg.a[i][j]; } } gg = solve (gg, k); for (int i = 1; i <= n; i++) { for (int j = 1; j < n; j++) { cout << gg.a[i][j]%mod << " "; } cout << gg.a[i][n]%mod << endl; } } return 0; }