【组合数学】 HDOJ 5184 Brackets

附上BC的官方题解:

当n为奇数的时候答案是0。
先判断字符串的前面是否符合括号匹配,即对于任何前缀左括号个数>=右括号个数。
设左括号个数为a右括号个数为b, m=n/2,问题可以转化为在平面中从座标(a,b)沿网格走到(m,m) 且不跨过x=y这一条直线的方法数。数据太大,普通DP和搜索都不行的。
问题可以进一步转化为从(a-n,b-n)到(0,0)且不跨过x=y的方法数。再对称一下,转化到(0,0)到(n-b,n-a)不跨过x=y的方法数。

对于从(0,0)点走到(p,q)点不跨过x=y的方法数是
 
 
pq+1p+1Cqp+q
证明如下: 我们可以通过总的数目来减掉非法的数目即可。 把(0,0)和(p,q)都往下移一格,非法数目即为(0,-1)到(p,q-1)且路径中至少有一点和x=y相交的方法数。记(d,d)为从(0,-1)到(p,q-1)路径中最先和x=y相交的点。则由于对称性(-1,0)到(d,d)的方法数和(0,-1)到(d,d)的方法数是相同的。所以(0,-1)到(p,q-1)且与x=y相交的方法数和(-1,0)到(p,q-1)的方法数是相同的。 所以答案是
Cqp+qCq1p+q=pq+1p+1Cqp+q
然后对100W以内的数字进行一个阶乘处理,就可以O(1)得出答案了。

#include <iostream>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 1000005
#define maxm 100005
#define eps 1e-7
#define mod 1000000007
#define INF 0x3f3f3f3f
#define PI (acos(-1.0))
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R
#define pii pair<int, int>
#pragma comment(linker, "/STACK:16777216")
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;
LL qpow(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base;base=base*base;b/=2;}return res;}
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
//head

LL f[maxn];
LL g[maxn];
char s[maxn];
int n;

void init()
{
    f[0] = 1;
    for(int i = 1; i <= 1000000; i++) f[i] = f[i-1] * i % mod;
    g[1000000] = powmod(f[1000000], mod - 2);
    for(int i = 999999; i >= 0; i--) g[i] = g[i+1] * (i+1) % mod;
}

inline LL calc(int a, int b)
{
    return f[a+b] * (b + 1 - a) % mod * g[a] % mod * g[b+1] % mod;
}

void work()
{
    if(n % 2) {
        printf("0\n");
        return;
    }
    int a = 0, b = 0, ok = 1;
    for(int i = 0; s[i]; i++) {
        if(s[i] == '(') a++;
        else b++;
        if(b > a) ok = 0;
    }
    if(!ok) {
        printf("0\n");
        return;
    }
    n /= 2;
    a = n - a;
    b = n - b;
    if(a < 0 || b < 0) {
        printf("0\n");
        return;
    }
    printf("%I64d\n", calc(a, b));
}

int main()
{
    init();
    while(scanf("%d%s", &n, s)!=EOF) work();

    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值