HDU 4828 - Grids (Catalan数)

 

题目链接http://acm.hdu.edu.cn/showproblem.php?pid=4828

 

Catalan数的公式为 C[n+1] = C[n] * (4 * n + 2) / (n + 2)

题目要求对M = 1e9+7 取模

利用乘法逆元将原式中除以(n+2)取模变为对(n+2)逆元的乘法取模

C[n+1] = C[n] * (4 * n + 2) * Pow(n+2, MOD-2) % MOD

其中Pow用快速幂解决

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>

using namespace std;

typedef long long LL;

const int MAXN = 1e6+10;
const int MOD = 1e9+7;

LL C[MAXN];

LL QuickPow(LL x, LL n)
{
    LL ans = 1;
    while(n) {
        if(n & 1) ans = (ans * x) % MOD;
        x = (x * x) % MOD;
        n /= 2;
    }
    return ans;
}

void Pre()
{
    C[1] =  1;
    for(int i = 2; i <= MAXN; i++) {
        C[i] = C[i-1] * (4 * i - 2) % MOD * QuickPow(i + 1, MOD-2) % MOD;
    }
}

int main()
{
    Pre();

    int t;
    int n;

    scanf("%d", &t);
    for(int cas = 1; cas <= t; cas++) {
        scanf("%d", &n);
        printf("Case #%d:\n%I64d\n", cas, C[n]);
    }


    return 0;
}
View Code

 

posted @ 2015-11-16 19:56  Quinte  阅读(137)  评论(0编辑  收藏  举报