CodeForces 814E An unavoidable detour for home
考虑给图分层,一层的点一一对应上一层的一些点。设 \(f_{i, j}\) 为考虑了前 \(i\) 个点,最后一层有 \(j\) 个点,除了最后一层点的其他点度数限制已经满足的方案数。
转移系数是 \(g_{i, j, k}\) 表示这一层有 \(i\) 个点,上一层有 \(j\) 个 \(2\) 度点,\(k\) 个 \(3\) 度点(实际上因为上一层已经和上上层连边所以是 \(1, 2\) 度点)。这个的递推是容易的。
时间复杂度就是 \(O(n^3)\)。
code
// Problem: E. An unavoidable detour for home
// Contest: Codeforces - Codeforces Round 418 (Div. 2)
// URL: https://codeforces.com/problemset/problem/814/E
// Memory Limit: 256 MB
// Time Limit: 3000 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 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 = 55;
const ll mod = 1000000007;
const ll inv2 = (mod + 1) / 2;
inline ll qpow(ll b, ll p) {
ll res = 1;
while (p) {
if (p & 1) {
res = res * b % mod;
}
b = b * b % mod;
p >>= 1;
}
return res;
}
ll n, a[maxn], fac[maxn], ifac[maxn], f[maxn][maxn], g[maxn][maxn][maxn];
inline ll C(ll n, ll m) {
if (n < m || n < 0 || m < 0) {
return 0;
} else {
return fac[n] * ifac[m] % mod * ifac[n - m] % mod;
}
}
void solve() {
scanf("%lld", &n);
for (int i = 1; i <= n; ++i) {
scanf("%lld", &a[i]);
}
fac[0] = 1;
for (int i = 1; i <= n; ++i) {
fac[i] = fac[i - 1] * i % mod;
}
ifac[n] = qpow(fac[n], mod - 2);
for (int i = n - 1; ~i; --i) {
ifac[i] = ifac[i + 1] * (i + 1) % mod;
}
g[0][0][0] = 1;
for (int i = 3; i <= n; ++i) {
for (int j = 3; j <= i; ++j) {
g[0][0][i] = (g[0][0][i] + g[0][0][i - j] * C(i - 1, j - 1) % mod * fac[j - 1] % mod * inv2) % mod;
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
if (i >= 2) {
g[0][i][j] = g[0][i - 2][j] * (i - 1) % mod;
}
if (j) {
g[0][i][j] = (g[0][i][j] + g[0][i][j - 1] * j) % mod;
}
}
}
for (int i = 1; i <= n; ++i) {
for (int k = 0; k <= n; ++k) {
for (int j = 0; j <= n; ++j) {
if (j) {
g[i][j][k] = g[i - 1][j - 1][k] * j % mod;
}
if (k) {
g[i][j][k] = (g[i][j][k] + g[i - 1][j + 1][k - 1] * k) % mod;
}
}
}
}
f[a[1] + 1][a[1]] = 1;
for (int i = a[1] + 2; i <= n; ++i) {
for (int j = 1; j < i; ++j) {
int c2 = 0, c3 = 0;
for (int k = 1; j + k < i; ++k) {
c2 += (a[i - j - k + 1] == 2);
c3 += (a[i - j - k + 1] == 3);
f[i][j] = (f[i][j] + f[i - j][k] * g[j][c2][c3]) % mod;
}
}
}
int c2 = 0, c3 = 0;
ll ans = 0;
for (int i = 1; i < n; ++i) {
c2 += (a[n - i + 1] == 2);
c3 += (a[n - i + 1] == 3);
ans = (ans + f[n][i] * g[0][c2][c3]) % mod;
}
printf("%lld\n", ans);
}
int main() {
int T = 1;
// scanf("%d", &T);
while (T--) {
solve();
}
return 0;
}