//蓝桥杯:括号序列 #include<iostream> #include<cstring> #include<algorithm> using namespace std; typedef long long ll; const int MOD = 1e9 + 7, N = 5005; ll dp[N][N] = { 0 }; string str; int n; int calc() { memset(dp, 0, sizeof(dp)); //超级重点:少了就运行错误。dp所有初始化为零, dp[0][0] = 1; //在地第零位左括号比有括号多0个刚好成立,其他的不合法为0 for (int i = 1; i <= n; i++) { if (str[i - 1] == '(') { for (int j = 1; j <= n; j++) //j=0的情况不存在,方案依旧为零 { dp[i][j] = dp[i - 1][j - 1]; } } else { dp[i][0] = (dp[i - 1][1] + dp[i - 1][0]) % MOD; //当j=0时,再减一会越界,直接赋值 for (int j = 1; j <= n; j++) { dp[i][j] = (dp[i - 1][j + 1] + dp[i][j - 1]) % MOD; } } } for (int i = 0; i <= n; i++) { if (dp[n][i]) //如果不为空,则找到最小的合法序列方案数 return dp[n][i]; } return -1; } int main(void) { ios::sync_with_stdio(false); cin >> str; n = str.length(); //计算有多少个字符 ll rans1 = calc(); reverse(str.begin(), str.end()); //前后翻转 for (int i = 0; i < n; i++) { if (str[i] == '(') str[i] = ')'; else str[i] = '('; } ll rans2 = calc(); cout << (rans1 * rans2) % MOD << endl; return 0; }
蓝桥杯,历年真题,括号序列
最新推荐文章于 2024-03-08 23:42:28 发布