题解 Bracket Insertion
Find_Yourself · · 题解
Bracket Insertion
神仙 DP 题,不愧是 tourist。
容易发现,括号序列一共有
假如 ( 为 ) 为
现在考虑维护这些前缀和。
如果我们在当前序列某一位后插入一个 (),且那一位的前缀和为
同理可知,插入 )( 相当于把
定义
那么显然有两种转移:
其中,
由于每个部分的操作都是独立的,所以还要乘上组合数。
状态
我们考虑优化掉一个
定义
那么转移方程最终可化简为:
最后输出
复杂度
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef double db;
const int N = 500 + 5, mod = 998244353;
ll n, p, c[N][N], f[N][N], g[N][N];
ll ksm(ll x, ll y) {
ll res = 1;
while (y) {
if (y & 1) res = res * x % mod;
x = x * x % mod;
y >>= 1;
}
return res;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> p; p = p * ksm(10000, mod - 2) % mod;
for (int i = 0; i <= n; ++i) c[i][0] = 1;
for (int i = 1; i <= n; ++i) for (int j = 1; j <= i; ++j) c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % mod;
for (int i = 0; i <= n; ++i) f[0][i] = g[0][i] = 1;
for (int i = 1; i <= n; ++i) {
for (int x = 0; x <= n; ++x) {
for (int j = 0; j < i; ++j) {
f[i][x] = (f[i][x] + (p * f[j][x + 1] + (1 - p + mod) * (x ? f[j][x - 1] : 0)) % mod * c[i - 1][j] % mod * g[i - j - 1][x] % mod) % mod;
}
for (int j = 0; j <= i; ++j) {
g[i][x] = (g[i][x] + c[i][j] * f[j][x] % mod * f[i - j][x] % mod) % mod;
}
}
}
ll ans = f[n][0];
for (int i = 1; i <= 2 * n; i += 2) ans = ans * ksm(i, mod - 2) % mod;
cout << ans << endl;
return 0;
}