【數論】Codeforces Round #404 (Div. 2)(D)Anton and School - 2

CN_swords發表於2017-03-18

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;
} 




相關文章