题目描述
Link has a bracket sequence aaa of length nnn, which is a subsequence of a valid bracket sequence bbb of length mmm.
Link doesn't remember bbb, so he wonders the number of possible sequences bbb.
A bracket sequence is valid if it satisfies any of the following conditions:
- Its length is 000.
- It can be represented as (A)(A)(A), where AAA is a valid bracket sequences.
- It can be represented as ABABAB, where AAA and BBB are both valid bracket sequence.
A sequence aaa is a subsequence of a sequence bbb if aaa can be obtained from bbb by deletion of several (possibly, zero or all) elements.
输入描述:
Each test contains multiple test cases. The first line contains the number of test cases TTT (1≤T≤1001 \le T \le 1001≤T≤100). Description of the test cases follows. The first line contains two integers n,mn,mn,m (1≤n≤m≤2001 \leq n \leq m \leq 2001≤n≤m≤200). The second line contains a bracket sequence sss of length nnn. It is guaranteed that the sum of mmm over all test cases does not exceed 10310^3103.
输出描述:
For each test cases, output the number of possible sequences bbb modulo 109+710^9+7109+7.
Note that the answer maybe 000 due to Link's poor memory.
输入
3 2 2 () 2 4 )( 2 4 ()
输出
1 1 2
题意: 给你一个长度为n的括号序列a,a不一定是合法括号序列,该括号序列是长度为m的括号序列b的子序列,而b是合法括号序列,求有多少种不同的括号序列b。
分析: 设dp[i][j][k]表示含义为考虑b串前i个字符,以及a串前j个字符,a串前j个字符出现在b串前i个字符中且b串左括号比右括号多k个的b串个数,最终答案为dp[m][n][0]。这样对于每一位b串字符可以枚举放左括号还是右括号,所以状态转移方程也就出来了。对于dp[i][j][k]首先看b串第i位要放的是否和a串第j位相同,如果相同那么这两个字符可以让a串匹配的字符数加1,所以此时dp[i][j][k] += dp[i-1][j-1][k-1或k+1],第三维具体是什么取决于b串放的是左括号还是右括号;如果不同那么dp[i][j][k] += dp[i-1][j][k-1或k+1]。另外对于i等于1的初始状态,根据状态含义可以知道dp[1][0][1] = 1,若a串第一个字符是左括号,那么还需要dp[1][1][1] = 1,这样就初始化完成了,i从2~n递推即可。
具体代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
#define int long long
using namespace std;
char s[205];
//dp[i][j][k]表示对于b串前i个字符与a串前j个字符匹配上且左括号比右括号多k个的串数
int dp[205][205][205];
const int mod = 1e9+7;
signed main()
{
int T;
cin >> T;
while(T--){
int n, m;
scanf("%lld%lld", &n, &m);
for(int i = 0; i <= m; i++)
for(int j = 0; j <= n; j++)
for(int k = 0; k <= m; k++)
dp[i][j][k] = 0;
scanf("%s", s+1);
if(s[1] == '(') dp[1][1][1] = 1;
dp[1][0][1] = 1;
for(int i = 2; i <= m; i++)
for(int j = 0; j <= n; j++)
for(int k = 0; k <= m; k++){
if(j){
//放(
if(s[j] == '(' && k >= 1)
dp[i][j][k] = (dp[i][j][k]+dp[i-1][j-1][k-1])%mod;
else if(s[j] == ')' && k >= 1)
dp[i][j][k] = (dp[i][j][k]+dp[i-1][j][k-1])%mod;
//放)
if(s[j] == ')' && k <= m-1)
dp[i][j][k] = (dp[i][j][k]+dp[i-1][j-1][k+1])%mod;
else if(s[j] == '(' && k <= m-1)
dp[i][j][k] = (dp[i][j][k]+dp[i-1][j][k+1])%mod;
}
else{
//放(
if(k >= 1)
dp[i][0][k] = (dp[i][0][k]+dp[i-1][0][k-1])%mod;
//放)
if(k <= m-1)
dp[i][0][k] = (dp[i][0][k]+dp[i-1][0][k+1])%mod;
}
}
// for(int i = 0; i <= m; i++, puts(""))
// for(int j = 0; j <= n; j++, puts(""))
// for(int k = 0; k <= m; k++)
// cout << dp[i][j][k] << " ";
printf("%lld\n", dp[m][n][0]);
}
return 0;
}