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.
翻译一下就是有多少种
()、(())、((())))。。。
例如,去掉1 5的,得到(());如上
这样我们可以知道,假设每次读取当前"(“有ai个,” )"有bi个。
这样我们得到了当前这次读入,左边有多少(,右边有多少)
然后每一个(,ai-1里取,因为要去掉重复,所以必须使用当前位置的
,右边从bi取。
套用
范德蒙恒等式
过程见题解,可以根据自己的推导过程微调,得出不一样的计算公式。
#include<bits/stdc++.h>
using namespace std;
#define _for(i,a,b) for( int i=(a);i<=(b);i++)
typedef long long ll;
const ll N = 2e5 + 7;
const ll mod = 1e9 + 7;
char x[N];
ll l[N], r[N];
ll fac[N], inv[N];
ll quick(ll m, ll n) {
ll ans = 1;
while(n) {
if(n & 1)
ans = ans * m % mod;
m = m * m % mod;
n >>= 1;
}
return ans;
}
ll C(ll n, ll m) {
return (fac[n] % mod) * (inv[m] % mod) * (inv[n - m] % mod) % mod;
}
int main() {
memset(l, 0, sizeof l);
memset(r, 0, sizeof r);
ll ans = 0;
fac[0] = inv[0] = 1;
_for(i, 1, N - 3) {
fac[i] = (fac[i - 1] * i) % mod;
inv[i] = quick(fac[i], mod - 2);
}
scanf("%s", x + 1);
int len = 0;
for(int i = 1; x[i] != '\0'; i++) {
if(x[i] == '(') {
l[i] = l[i - 1] + 1;
} else
l[i] = l[i - 1];
len++;
}
for(int i = len; i >= 1; i--) {
if(x[i] == ')') {
r[i] = r[i + 1] + 1;
} else
r[i] = r[i + 1];
}
_for(i, 1, len) {
if(x[i] == '(') {
ans = (ans + C(l[i] + r[i] - 1, l[i]) % mod) % mod;
}
}
printf("%lld\n", ans);
return 0;
}