ARC190D Matrix Pow Sum
EuphoricStar · · 题解
考虑
先特判
这意味着对于每条
- 当
A_{i, i} = 0 且A_{i, j} \ne 0 时,路径可能形如i \to i \to \cdots \to i \to j ,贡献(p - 1)^l A_{i, j} 。 - 当
A_{j, j} = 0 且A_{i, j} \ne 0 时,路径可能形如i \to j \to j \to \cdots \to j ,贡献(p - 1)^l A_{i, j} 。 - 特别地,当
p = 3 且A_{i, j} = 0 且A_{j, i} \ne 0 ,路径可能形如i \to j \to i \to j ,贡献(p - 1)^l A_{j, i} 。
那么就做完了,瓶颈在算
// Problem: D - Matrix Pow Sum
// Contest: AtCoder - AtCoder Regular Contest 190 (Div. 1)
// URL: https://atcoder.jp/contests/arc190/tasks/arc190_d
// Memory Limit: 1024 MB
// Time Limit: 2000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
#define pb emplace_back
#define fst first
#define scd second
#define mkp make_pair
#define uint unsigned
#define mems(a, x) memset((a), (x), sizeof(a))
using namespace std;
typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;
typedef pair<ll, ll> pii;
const int maxn = 110;
ll n, mod, a[maxn][maxn], b[maxn][maxn];
struct mat {
ll a[maxn][maxn];
mat() {
mems(a, 0);
}
} A, B;
inline mat operator * (const mat &a, const mat &b) {
mat res;
for (int k = 1; k <= n; ++k) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
res.a[i][j] = (res.a[i][j] + a.a[i][k] * b.a[k][j]) % mod;
}
}
}
return res;
}
inline mat qpow(mat a, ll p) {
mat res = a;
--p;
while (p) {
if (p & 1) {
res = res * a;
}
a = a * a;
p >>= 1;
}
return res;
}
void solve() {
scanf("%lld%lld", &n, &mod);
int k = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
scanf("%lld", &a[i][j]);
if (!a[i][j]) {
k ^= 1;
}
A.a[i][j] = a[i][j];
}
}
if (mod == 2) {
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
printf("%lld%c", n & 1, " \n"[j == n]);
}
}
return;
}
A = qpow(A, mod);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
ll ans = A.a[i][j];
if (i != j && !a[i][i] && a[i][j]) {
ans = (ans + a[i][j]) % mod;
}
if (i != j && !a[j][j] && a[i][j]) {
ans = (ans + a[i][j]) % mod;
}
if (mod == 3 && !a[i][j] && a[j][i]) {
ans = (ans + a[j][i]) % mod;
}
if (k & 1) {
ans = (mod - ans) % mod;
}
printf("%lld%c", ans, " \n"[j == n]);
}
}
}
int main() {
int T = 1;
// scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}