D. Anton and School - 2
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 sequences of lengthn 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 sequences. Find the number of its distinct subsequences such that they are RSBS. Note that a subsequence ofs 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 modulo109 + 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!
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 exceed200 000.
Output one number — the answer for the task modulo 109 + 7.
)(()()
6
()()()
7
)))
0
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
typedef long long LL;
const int P=1000000007;
LL f[1000001],v[1000001];
LL rp(LL now, int k)
{
LL will=1;
for (; k; k>>= 1, now *= now, now %= P)
{
if (k & 1) will *= now, will %= P;
}
return will;
}
LL C(int n, int m)
{
if(n < m) return 0;
return f[n] * rp(f[m], P - 2) % P * rp(f[n - m], P - 2) % P;
}
void init()
{
f[0] = 1; v[0] = 1;
for (int i = 1; i <= 1000000; i++) //1e6以内的组合数
{
f[i] = f[i - 1] * i % P;
}
}
char a[200005];
LL sum[200005][2];
int main()
{
init();
scanf("%s",a);
LL l=strlen(a);
if(a[0]=='(')sum[0][0]++;
else sum[0][1]++;
for(int i=1;i<l;i++)
{
sum[i][0]=sum[i-1][0];
sum[i][1]=sum[i-1][1];
if(a[i]=='(')sum[i][0]++;
else sum[i][1]++;
}
LL ans=0;
for(int i=0;i<l;i++)
{
if(a[i]=='(')
{
LL n=sum[l-1][1]-sum[i][1];
LL m=sum[i][0]-1;
LL mi1=min(m,n);
LL mi2=min(m+1,n);
ans=(ans+C(n+m+1,mi2)-C(n+m,mi1)+P)%P;
}
}
printf("%lld\n",ans%P);
}