Brackets
Problem DescriptionWe 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 sequenceFor 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.
InputMulti 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.OutputFor each case,output answer % 1000000007 in a single line.Sample Input4()4(6()
【题意】
括号匹配(<=10^6),给出已将匹配好的前若干个的括号,让你把剩下的匹配完,问方案数%10^9+7,多组数据<=1000
【分析】
跟上一题类似。先判断他给的括号是否匹配。然后假设左括号比右括号多了l个,就是要求任意前缀和>=l的方案数。也用1与-1互换的方法推
上一个厉害的证明:
我的理解在上一篇博写了~
代码如下:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
using namespace std;
#define Maxn 1000010
#define Mod 1000000007
#define LL long long char s[Maxn];
int p[Maxn]; void init()
{
p[]=;
for(int i=;i<=Maxn-;i++)
{
LL x=(LL)p[i-],y=(LL)i,z;
z=(x*y)%Mod;
p[i]=(int)z;
}
} LL qpow(int x,int b)
{
if(x==) return ;
LL xx=x,ans=;
while(b)
{
if(b&) ans=(ans*xx)%Mod;
xx=(xx*xx)%Mod;
b>>=;
}
return ans;
} int get_c(int n,int m)
{
LL ans=p[m];
ans=(ans*qpow(p[n],Mod-))%Mod;
ans=(ans*qpow(p[m-n],Mod-))%Mod;
return (int)ans;
} int main()
{
init();
int n;
while(scanf("%d",&n)!=EOF)
{
int m,sl=;
scanf("%s",s+);
int l=strlen(s+),now=;
bool ok=;
for(int i=;i<=l;i++)
{
if(s[i]=='(') now++,sl++;
else now--;
if(now<) ok=;
}
if(n%!=||l>n||!ok||sl*>n||(l-sl)*>n) {printf("0\n");continue;}
m=n/-sl;
if(sl==n/||l==n) {printf("1\n");continue;}
printf("%d\n",(get_c(m,*m+now)+Mod-get_c(m-,*m+now))%Mod);
}
return ;
}
[HDU 5184]
2016-09-20 19:53:38