题目链接:点击打开链接
题意:给你一个长度为m的只含()的括号串s, 要求在s两端在加两个串p和q, 使得总长度为n,并且平衡, 平衡是指任意前缀串的(都不少于), 并且整个串的(和)一样多。
思路:我们不难想到这样一个DP, d[i][j]表示长度为i的串,(比)多j个(或者)比(多j个, 是等价的)的方案数。 那么转移很简单:
if(j > 0) d[i][j] += d[i-1][j-1] ; d[i][j] += d[i-1][j+1]。
然后为了满足那两个条件, 我们计算出s串的最小平衡度minx,以及s整个串的平衡度cur,枚举第一个串的长度和平衡度, 那么我们就可以算出第二个串的长度和平衡度, 这样就可以累加答案了。
细节参见代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
using namespace std;
typedef long long ll;
typedef long double ld;
const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;
const int mod = 1000000000 + 7;
const int INF = int(1e9);
const ll INF64 = ll(1e18);
const int maxn = 2000 + 10;
int T,n,m;
ll d[maxn][maxn];
void add(ll &a, ll b) {
a += b;
if(a >= mod) a -= mod;
}
char s[(int)(1e5 + 10)];
int main() {
scanf("%d%d",&n,&m);
scanf("%s",s+1);
memset(d, 0, sizeof(d));
d[0][0] = 1;
for(int i=1;i<=n-m;i++) {
for(int j=0;j<=i;j++) {
if(j > 0) {
add(d[i][j], d[i-1][j-1]);
}
add(d[i][j], d[i-1][j+1]);
}
}
int minx = INF;
int cur = 0;
for(int i=1;i<=m;i++) {
if(s[i] == '(') ++cur;
else --cur;
minx = min(minx, cur);
}
ll ans = 0;
for(int i=0;i<=n-m;i++) {
for(int j=0;j<=i;j++) {
if(j + minx >= 0 && j + cur <= n-m-i) {
add(ans, d[i][j] * d[n-m-i][j+cur] % mod);
}
}
}
printf("%I64d\n",ans);
return 0;
}