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.
题解:
容易想到暴力做法:设字符串的长度为
len
,设
s1[i]
为
1−i
的左括号数量,
s2[i]
为
i−len
的右括号数量,那么对于第
i
位左括号,设
我们考虑如何把式子化成上面的形式。
这样就行了。您可能觉得奇怪,不是有个 min(a,b) 吗?而且这里的 j 是从
代码:
#include<bits/stdc++.h>
using namespace std;
#define pa pair<int,int>
#define LL long long
const LL mod=1000000007LL;
const int Maxn=200010;
char str[Maxn];
int s1[Maxn],s2[Maxn],ans=0;
LL fac[Maxn],fin[Maxn],inv[Maxn];
LL C(int n,int m)
{
if(n<m)return 0;
return fac[n]*fin[n-m]%mod*fin[m]%mod;
}
void pre()
{
inv[1]=1;fac[0]=fac[1]=1;fin[0]=fin[1]=1;
for(int i=2;i<=200000;i++)
{
fac[i]=fac[i-1]*(LL)(i)%mod;
inv[i]=(mod-mod/i)*inv[mod%i]%mod;
fin[i]=fin[i-1]*inv[i]%mod;
}
}
int main()
{
pre();
scanf("%s",str+1);
int len=strlen(str+1);s1[0]=s2[len+1]=0;
for(int i=1;i<=len;i++)s1[i]=s1[i-1]+(str[i]=='(');
for(int i=len;i;i--)s2[i]=s2[i+1]+(str[i]==')');
LL ans=0;
for(int i=1;i<len;i++)
if(str[i]=='(')
{
int a=s1[i],b=s2[i+1];
ans=(ans+C(a+b-1,a))%mod;
}printf("%I64d",ans);
}