考虑 的第 位的所有可能的和是什么。把它看成一个图论问题, 的边权是 ,那么相当于求所有经过 条边且起点为 ,终点为 的路径的边权乘积的和。对于一条 的边,设一条路径经过它的次数为 ,那么一条路径的贡献即为 。
先特判 。发现对于 ,只有 或 时 在模 意义下非 (此时值为 ),对于其余的 , 在模 意义下都为 。证明大概是取离散对数,发现当 或 时 在模 意义下都为 ,当 为其余值时 在模 意义下取遍 的所有值,而因为 所以 是 的倍数。
这意味着对于每条 权边,只有经过它恰好 次或 次,整条路径的贡献才非 ,且设总共有 条 权边,路径经过的非 权边的乘积为 ,那么此时这条路径的贡献为 。考虑先算出 表示不考虑经过 权边时 的路径的和作为初始答案,那么只有当 时路径才可能经过每条 权边恰好 次或 次。然后分类讨论:
- 当 且 时,路径可能形如 ,贡献 。
- 当 且 时,路径可能形如 ,贡献 。
- 特别地,当 且 且 ,路径可能形如 ,贡献 。
那么就做完了,瓶颈在算 。时间复杂度 。
// 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;
}