Problem Description
We give the following inductive definition of a “regular brackets” sequence:
● the empty sequence is a regular brackets sequence,
● if s is a regular brackets sequence, then (s) are regular brackets sequences, and
● if a and b are regular brackets sequences, then ab is a regular brackets sequence.
● no other sequence is a regular brackets sequence
For instance, all of the following character sequences are regular brackets sequences:
(), (()), ()(), ()(())
while the following character sequences are not:
(, ), )(, ((), ((()
Now we want to construct a regular brackets sequence of length n, how many regular brackets sequences we can get when the front several brackets are given already.
Input
Multi test cases (about 2000), every case occupies two lines.
The first line contains an integer n.
Then second line contains a string str which indicates the front several brackets.
Please process to the end of file.
[Technical Specification]
1≤n≤1000000
str contains only '(' and ')' and length of str is larger than 0 and no more than n.
Output
For each case,output answer % 1000000007 in a single line.
Sample Input
4
()
4
(
6
()
Sample Output
1
2
2
Hint
For the first case the only regular sequence is ()().
For the second case regular sequences are (()) and ()().
For the third case regular sequences are ()()() and ()(()).
Source
BestCoder Round #32
Recommend
hujie
1 /************************************************************************* 2 > File Name: hdu5184.cpp 3 > Author: Henry Chen 4 > Mail: 390989083@qq.com 5 > Created Time: 日 9/21 22:52:52 2020 6 ************************************************************************/ 7 8 #include<bits/stdc++.h> 9 using namespace std; 10 const int mod = 1000000007; 11 const int N = 1000004; 12 long long fac[N],ny[N]; 13 char c[N]; 14 long long inv(long long a,long long m) 15 { 16 long long p = 1,q = 0,b = m,c,d; 17 while(b > 0) 18 { 19 c = a / b; 20 d = a; 21 a = b; 22 b = d % b; 23 d = p; 24 p = q; 25 q = d - c * q; 26 } 27 return p < 0 ? p+m:p; 28 } 29 long long C(int n,int x) 30 { 31 if(x < 0||n < 0||n < x) 32 { 33 return 0; 34 } 35 return fac[n] * ny[x] % mod * ny[n-x] % mod; 36 } 37 int main() 38 { 39 int n; 40 fac[0] = 1; 41 ny[0] = inv(1,mod); 42 for(int i = 1;i < N;i++) 43 { 44 fac[i] = fac[i-1]*i%mod; 45 ny[i] = inv(fac[i],mod); 46 } 47 while(~scanf("%d%s",&n,&c)) 48 { 49 if(n & 1) 50 { 51 printf("%d ",0); 52 continue; 53 } 54 int a1 = 0; 55 int a2 = 0; 56 int b = 0; 57 for(int i = 0;i < strlen(c);i++) 58 { 59 if(c[i] == '(') 60 { 61 a1++; 62 } 63 else 64 { 65 a2++; 66 } 67 if(a2 > a1) 68 { 69 printf("%d ",0); 70 b = 1; 71 break; 72 } 73 } 74 if(b) 75 { 76 continue; 77 } 78 if(a2 > a1) 79 { 80 printf("%d ",0); 81 continue; 82 } 83 long long ans = (C(n-a1-a2,n/2-a1)+mod-C(n-a1-a2,n/2-a1-1))%mod; 84 printf("%lld ",ans); 85 } 86 return 0; 87 }