题目链接
https://www.luogu.org/problem/P4159
分析
如果边权为 111,则是简单的矩阵快速幂加速DP递推方程,又因为边权并不大,所以考虑拆点,新图中边权均为 111,将每个点暴力拆成相连的 999 个点,对于原先某条边 (u,v,w)(u, v, w)(u,v,w),可以转化为 uuu 拆成的点中第 www 个连向 vvv 拆成的点中第 111 个,其间恰好 www 条边。
AC代码
#include <cstdio>
#include <cstring>
const int maxn = 95, mod = 2009;
struct Matrix {
int n, x[maxn][maxn];
Matrix(int n = 0) : n(n) {
memset(x, 0, sizeof(x));
}
Matrix operator * (const Matrix& rhs) const {
Matrix ans(n);
for (int a = 1; a <= n; ++a)
for (int b = 1; b <= n; ++b)
for (int c = 1; c <= n; ++c)
ans.x[a][c] = (ans.x[a][c] + x[a][b] * rhs.x[b][c] % mod) % mod;
return ans;
}
};
inline Matrix qpow(Matrix a, int b) {
Matrix ans(a.n);
for (int i = 1; i <= a.n; ++i) ans.x[i][i] = 1;
while (b) {
if (b & 1) ans = ans * a;
a = a * a, b >>= 1;
}
return ans;
}
int main() {
int n, t;
scanf("%d%d", &n, &t);
Matrix A(9 * n);
for (int i = 1; i <= n; ++i) {
char s[15];
scanf("%s", s + 1);
for (int j = 1; j <= 8; ++j) A.x[(i - 1) * 9 + j][(i - 1) * 9 + j + 1] = 1;
for (int j = 1; j <= n; ++j) if (s[j] - '0')
A.x[(i - 1) * 9 + s[j] - '0'][(j - 1) * 9 + 1] = 1;
}
A = qpow(A, t);
printf("%d", A.x[1][(n - 1) * 9 + 1]);
return 0;
}