参考自:https://www.cnblogs.com/acm1ruoji/p/12022540.html
题意
给出一个字符串,字符串只包含三种字符:‘(’,‘)’,‘?’。其中‘?’可变为‘(’,‘)’两种字符,问对于‘?’的所有变化情况形成的所有字符串的深度和。
深度定义:字符串中括号的最大嵌套数,如“(())”的深度为2,“()()”的深度为1,“(()())”深度为2
题解
设dp[i][j]为从[i, j]内的‘?’的所有变化情况的深度和
接下来分类讨论递推即可
对于当前区间[i, j],若s[i] != ‘(’,相当于不考虑当前为位置的贡献,从而dp[i][j] += dp[i + 1][j]
同理,若s[j] != ‘)’,dp[i][j] += dp[i][j - 1]
若以上两种情况同时出现,相当于多加一段dp[i + 1][j - 1],需减去
若s[i] != ‘)’ 且 s[j] != ‘(’,则i, j位置必然会产生贡献,从而dp[i][j] += dp[i + 1][j - 1] + 2k,至于为什么是加入2k,考虑dp的意义,是当前区间内部‘?’所有情况的总和,故对于区间内部所有字符串深度都应该+1,至于字符串的个数自然是区间[i + 1, j - 1]内‘?’的个数了
#include <bits/stdc++.h>
#include <unordered_set>
#include <unordered_map>
#define _for(i, a, b) for(int i = a; i < b; ++i)
#define _rep(i, a, b) for(int i = a; i <= b; ++i)
#define closeIO ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define debug cout << "******************" << endl
#define FREE freopen("in.txt", "r", stdin)
#define FREO freopen("out.txt", "w", stdout)
#define ls l, m, rt << 1
#define rs m + 1, r, rt << 1 | 1
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> pii;
typedef long double LD;
const int MAXN = 2e3 + 10;
const int MOD = 998244353;
const double eps = 1e-6;
LL QuickPow(LL a, LL n) {
LL ans = 1;
while (n) {
if (n&1) ans = ans*a%MOD;
a = a*a%MOD;
n >>= 1;
}
return ans;
}
char s[MAXN];
LL dp[MAXN][MAXN], sum[MAXN];
int main() {
scanf("%s", s + 1);
int n = strlen(s + 1);
memset(sum, 0, sizeof(sum));
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + (s[i] == '?');
for (int len = 2; len <= n; ++len) {
for (int l = 1, r = l + len - 1; r <= n; ++l, ++r) {
if (s[l] != '(') dp[l][r] = (dp[l][r] + dp[l + 1][r])%MOD;
if (s[r] != ')') dp[l][r] = (dp[l][r] + dp[l][r - 1])%MOD;
if (s[l] != '(' && s[r] != ')') dp[l][r] = (dp[l][r] - dp[l + 1][r - 1] + MOD)%MOD;
if (s[l] != ')' && s[r] != '(') dp[l][r] = (dp[l][r] + dp[l + 1][r - 1] + QuickPow(2, sum[r - 1] - sum[l]))%MOD;
}
}
printf("%lld\n", dp[1][n]);
return 0;
}