HDU5673 卡特兰数的应用

  附上题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5673, 这个题的大意是在坐标原点有一个机器人, 这个机器人每次可以选择向左走向右走休息一秒, 但是不能走向负半轴, 现在机器人进过一系列运动之后返回了坐标原点, 问你有多少种情况可以使机器人到达坐标原点。 

分析:由于机器人开始在坐标原点 最后也在坐标原点, 因此我们可以知道机器人向左走的步数和向右走的步数想同, 且最大是n/2, 因此我们枚举机器人向右走的步数i, 从n中走法中选出2*i个不歇息的点的方案数就是C(n, 2*i), 然后我们就要知道机器人2*i步走的合法的方案数, 仔细思考下我们发现这个方案数和括号合法的个数非常相似, 而括号匹配的个数正好是Cata(i), 因此最终答案就是sigma(C(n, 2*i)*cata(i))  0<=i<=n/2, 代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>

using namespace std;
typedef long long LL;
LL M = 1000000007;
const int maxn = 1000000 + 100;
LL nfic[maxn*2], rev_nfic[maxn*2];
LL cata[maxn];

LL qk_mod(LL a, LL b){
    LL res = 1;
    while(b > 0){
        if(b&1)
            res = (res*a)%M;
        a = (a*a)%M;
        b >>= 1;
    }
    return res;
}

LL Com(LL n, LL m){
    LL res = nfic[n];
    res = res*rev_nfic[m]%M;
    res = res*rev_nfic[n-m]%M;
    return res;
}

int main() {
    int T;
    scanf("%d", &T);
    nfic[0] = 1;
    rev_nfic[0] = 1;
    for(int i=1; i<=2*1000000+3; i++){
        nfic[i] = (i*nfic[i-1])%M;
        rev_nfic[i] = qk_mod(nfic[i], M-2);
    }
    for(int i=0; i<=1000000; i++){
        cata[i] = Com(2*i, i)*qk_mod(i+1, M-2)%M;
    }
    while(T--) {
        int n;
        scanf("%d", &n);
        LL res = 0;
        for(int i=0; i<=n/2; i++){
            res = (res + Com(n, 2*i)*cata[i])%M;
        }
        cout<<res<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/xingxing1024/p/5432676.html