CodeForces 785 D.Anton and School - 2 (Combinatorial Mathematics)

Description

Defining a bracketed sequence s of length n is an RSBS if and only if it satisfies the following four conditions:

1. Non-empty length (n_0)

2. Length is even

3. The first n2 parentheses are left parentheses

4. The last n2 parentheses are right parentheses

Now we give a parenthesized sequence and ask how many of them are subsequences of RSBS.

Input

Enter a sequence of parentheses no longer than 200,000 in length

Output

Output of the bracket sequence is the number of subsequences of RSBS, the result modulus 109 + 7

Sample Input

)(()()

Sample Output

6

Solution

Let the fourth left parenthesis be the last parenthesis in the subsequence. If RSBS is to form, then I left parenthesis should be selected from the left parenthesis. i+1 right parenthesis should be selected from the left parenthesis. Assuming that there is a left parenthesis before the left pareparenthesis, and r right parepareparenthesis behind, then the number of options is i=0min(l,r_1) Ci L Ci l+Ci l+1r=r= i=1min(l,r Ci l) Ci L Ci L Ci L Cr Cr Cr Cr Cr I r i r i r 22;1l+r

So as long as the number of left brackets in the first one and the number of right brackets from the first one to the last one are counted, the answer i s i=1|s|Cr[i] 1l[i]+r[i] 1[s[i]='.

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=200005;
#define mod 1000000007
int fact[maxn],inv[maxn];
void init(int n=2e5)
{
    fact[0]=1;
    for(int i=1;i<=n;i++)fact[i]=(ll)i*fact[i-1]%mod;
    inv[1]=1;
    for(int i=2;i<=n;i++)inv[i]=mod-(ll)(mod/i)*inv[mod%i]%mod;
    inv[0]=1;
    for(int i=1;i<=n;i++)inv[i]=(ll)inv[i-1]*inv[i]%mod; 
}
int C(int n,int m)
{
    if(m<0||m>n)return 0;
    return (ll)fact[n]*inv[m]%mod*inv[n-m]%mod;
}
void add(int &x,int y)
{
    x=x+y>=mod?x+y-mod:x+y;
}
int l[maxn],r[maxn];
char s[maxn]; 
int main()
{
    init();
    scanf("%s",s+1);
    int n=strlen(s+1);
    l[0]=r[n+1]=0;
    for(int i=1;i<=n;i++)l[i]=l[i-1]+(s[i]=='(');
    for(int i=n;i>=1;i--)r[i]=r[i+1]+(s[i]==')');
    int ans=0;
    for(int i=1;i<=n;i++)
        if(s[i]=='(')add(ans,C(l[i]-1+r[i],r[i]-1));
    printf("%d\n",ans);
    return 0;
}

Posted by Artiom on Wed, 13 Feb 2019 15:18:18 -0800