C. Famil Door and Brackets
time limit per test
memory limit per test
input
output
n
valid
- the total number of opening brackets is equal to the total number of closing brackets;
- for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets.
s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.
pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109.
Input
n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively.
s of length m consisting of characters '(' and ')' only.
Output
p and q such that p + s + q is a valid sequence of round brackets modulo 109.
Examples
input
4 1 (
output
4
input
4 4 (())
output
1
input
4 3 (((
output
0
dp[i][j]表示长度为i括号序列中, 左括号比右括号多j的序列数量.dp[i][j] = dp[i-1][j+1] + dp[i-1][j-1]
#include <bits/stdc++.h>
#define maxn 2005
#define MOD 1000000007
using namespace std;
typedef long long ll;
ll dp[maxn][maxn];
char str[100005];
int n, m;
void Init(){
dp[0][0] = 1;
int d = n - m;
for(int i = 1; i <= d; i++)
for(int j = 0; j <= i; j++){
if(j == 0)dp[i][j] = dp[i-1][j+1];
else dp[i][j] = dp[i-1][j+1] + dp[i-1][j-1] % MOD;
}
}
int main(){
// freopen("in.txt", "r", stdin);
scanf("%d%d%s", &n, &m, str);
Init();
int sum = 0, mins = 1e9;
for(int i = 0; str[i]; i++){
if(str[i] == '(')
sum++;
else
sum--;
mins = min(sum, mins);
}
int d = n - m;
ll ans = 0;
for(int i = 0; i <= d; i++)
for(int j = 0; j <= i; j++){
if(j + mins < 0 || sum + j > d)
continue;
ans += dp[i][j] % MOD * (dp[d-i][sum+j] % MOD);
ans %= MOD;
}
printf("%I64d\n", ans);
return 0;
}