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

 

转载于:https://www.cnblogs.com/Quinte/p/4969874.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值