D. Anton and School - 2
题目连接:
http://codeforces.com/contest/785/problem/D
Description
As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket sequences (RSBS). A bracket sequence s of length n is an RSBS if the following conditions are met:
It is not empty (that is n ≠ 0).
The length of the sequence is even.
First charactes of the sequence are equal to "(".
Last charactes of the sequence are equal to ")".
For example, the sequence "((()))" is an RSBS but the sequences "((())" and "(()())" are not RSBS.
Elena Ivanovna, Anton's teacher, gave him the following task as a homework. Given a bracket sequence s. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence of s is a string that can be obtained from s by deleting some of its elements. Two subsequences are considered distinct if distinct sets of positions are deleted.
Because the answer can be very big and Anton's teacher doesn't like big numbers, she asks Anton to find the answer modulo 109 + 7.
Anton thought of this task for a very long time, but he still doesn't know how to solve it. Help Anton to solve this task and write a program that finds the answer for it!
Input
The only line of the input contains a string s — the bracket sequence given in Anton's homework. The string consists only of characters "(" and ")" (without quotes). It's guaranteed that the string is not empty and its length doesn't exceed 200 000.
Output
Output one number — the answer for the task modulo 109 + 7.
Sample Input
)(()()
Sample Output
6
Hint
题意
问你有多少种删除方案,使得最后剩下的括号序列为RSBS括号序列。
RSBS的定义是:
长度是偶数,左边n/2是(,右边n/2是)。
题解:
考虑到一个(时候,假设这个括号的右边有y个右括号,左边有x个左括号。
那么方案数是:
for(int i=0;i<=min(x,y-1);i++){
ans+=C(x,i)*C(y-1,i);
}
整理一下,根据范德蒙恒等式,这个位置的贡献就是
C(x+y-1,y)
代码
#include<bits/stdc++.h>
using namespace std;
const int mod = 1e9+7;
const int maxn = 4e5+7;
long long fac[maxn];
long long qpow(long long a,long long b)
{
long long ans=1;a%=mod;
for(long long i=b;i;i>>=1,a=a*a%mod)
if(i&1)ans=ans*a%mod;
return ans;
}
long long C(long long n,long long m)
{
if(m>n||m<0)return 0;
long long s1=fac[n],s2=fac[n-m]*fac[m]%mod;
return s1*qpow(s2,mod-2)%mod;
}
int main(){
fac[0]=1;
for(int i=1;i<maxn;i++){
fac[i]=fac[i-1]*i%mod;
}
string s;
long long ans = 0;
cin>>s;
int l=0,r=0;
for(int i=0;i<s.size();i++){
if(s[i]==')')r++;
}
for(int i=0;i<s.size();i++){
if(s[i]==')')r--;
else{
ans=(ans+C(l+r,l+1))%mod;
l++;
}
}
cout<<ans<<endl;
}