CodeForces - 1015F Bracket Substring
Description
给出一个括号序列 \(s(|s|\le 200)\) ,求长度为 \(2n(n\le 100)\) 且包含 \(s\) 作为字串的合法的括号序列个数。
Solution
我已经菜到做 div.3 了
\(dp[i][j][k]\) 表示现在正在填第 \(i\) 个字符,已经匹配的 \(s\) 长度为 \(j\) ,有 \(k\) 个未匹配的左括号。
转移显然,见代码。用 \(fail[]\) 加速即可。
#include<bits/stdc++.h>
using namespace std;
template <class T> void read(T &x) {
x = 0; bool flag = 0; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == 45) flag = 1;
for (; isdigit(ch); ch = getchar()) x = x * 10 + ch - 48; if (flag) x = -x;
}
#define N 205
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define P 1000000007
char s[N];
int fail[N], dp[N][N][N];
inline void calc(int& x, const int& y) { (x += y) >= P ? (x -= P) : 0; }
int main() {
int n, m; read(n); n <<= 1;
scanf("%s", s); m = strlen(s);
rep(i, 1, m - 1) {
int j = fail[i]; for (; j && s[i] != s[j]; j = fail[j]);
fail[i + 1] = s[i] == s[j] ? j + 1 : 0;
}
dp[1][s[0] == '('][1] = 1;
rep(i, 2, n) rep(j, 0, min(m, i)) rep(k, 0, i) {
if (j < m) {
if (s[j] == '(') calc(dp[i][j + 1][k + 1], dp[i - 1][j][k]);
else {
int nxt = j; for (; nxt && s[nxt] != '('; nxt = fail[nxt]);
nxt += (s[nxt] == '(');
calc(dp[i][nxt][k + 1], dp[i - 1][j][k]);
}
if (s[j] == ')') calc(dp[i][j + 1][k], dp[i - 1][j][k + 1]);
else {
int nxt = j; for (; nxt && s[nxt] != ')'; nxt = fail[nxt]);
nxt += (s[nxt] == ')');
calc(dp[i][nxt][k], dp[i - 1][j][k + 1]);
}
}
else {
calc(dp[i][j][k + 1], dp[i - 1][j][k]);
calc(dp[i][j][k], dp[i - 1][j][k + 1]);
}
}
cout << dp[n][m][0];
return 0;
}