Codeforces Round #404 (Div. 2)(D)
题意:在原字符串中取出子字符串,问RSBS(
- 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 ")".
题解:对于每个'(',我们预处理出其左边'('的个数 l[i] ,和右边')'的个数 r[i] ;包含这个'('的RSBS个数为;
由范德蒙恒等式:;
当min(l,r) = l 时, k = l-1代入;
当min(l,r) = r时, k = r-1代入;
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
const int N = 200010;
const LL mod = 1e9+7;
const double esp = 1e-6;
char s[N];
int r[N],l[N];
LL mul[N];
LL exgcd(LL a,LL b,LL &x,LL &y)
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
LL d = exgcd(b,a%b,x,y);
LL t = x;
x = y;
y = t - a/b*y;
return d;
}
void init()
{
LL ans = 1;
mul[0] = 1;
for(int i = 1; i < N; i++)
{
ans = (ans*i)%mod;
mul[i] = ans;
}
}
LL C(int a,int b)
{
LL x,y,d;
exgcd((mul[b-a]*mul[a])%mod,mod,x,y);
x = (x%mod+mod)%mod;
return (mul[b]*x)%mod;
}
int main()
{
scanf("%s",s);
int len = strlen(s);
int rnum = 0, lnum = 0;
for(int i = 0; i < len; i++)
{
if(s[i] == '(')
{
l[i] = lnum;
lnum++;
}
}
for(int i = len-1; i >= 0; i--)
{
if(s[i] == '(')
r[i] = rnum;
else
rnum++;
}
init();
LL sum = 0;
for(int i = 0; i < len; i++)
{
if(s[i] == '(')
{
int x = min(l[i]+1,r[i]-1);
int y = l[i]+r[i];
sum = (sum+C(x,y))%mod;
}
}
cout << sum << endl;
return 0;
}