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:
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!
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 one number — the answer for the task modulo 109 + 7.
)(()()
6
()()()
7
)))
0
题解:
对于每一个当前为"("的位置i,设a为区间[1,i]中左括号的个数,b为区间(i,len]中右括号的个数,
那么在保证当前位置的左括号留下,当前位置右面的左括号全部删除的前提下,合法的删法数
最后的答案ans就是
其中组合数用阶乘打个表就好了
可是这样写是n^2复杂度,所以还需要用范德蒙恒等式优化下,
范德蒙德恒等式如下:
①C(n,0)*C(m,0)+C(n,1)*C(m,1)+…+C(n,m)*C(m,m) == C(n+m,m)
②C(n,0)*C(m,k)+C(n,1)*C(m,k-1)+…+C(n,k)*C(m,0) == C(n+m,k)
③C(n,0)*C(n,1)+C(n,1)*C(n,2)+…+C(n,n-1)*C(n,n) == C(2*n,n-1)
由②得,显而易见了:K[x] = C(b+a-1, a);
#include
#include
#define LL long long
#define mod 1000000007
char str[200005];
LL q[200005], jc[300005] = {1};
LL Pow(LL a, LL b)
{
LL sum;
sum = 1;
while(b)
{
if(b%2==1) sum = (sum*a)%mod, b--;
else a = (a*a)%mod, b /= 2;
}
return sum;
}
LL C(LL n, LL m)
{
LL ans;
if(n=1;i--)
{
q[i] = q[i+1];
if(str[i]==')')
q[i] += 1;
}
a = b = ans = 0;
for(i=1;i<=n;i++)
{
if(str[i]=='(')
{
a += 1;
b = a+q[i+1]-1;
ans = (ans+C(b, a))%mod;
}
}
printf("%I64d\n", ans);
return 0;
}