题目链接 : 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+;
const int MOD = 1e9+; LL C[MAXN]; LL QuickPow(LL x, LL n)
{
LL ans = ;
while(n) {
if(n & ) ans = (ans * x) % MOD;
x = (x * x) % MOD;
n /= ;
}
return ans;
} void Pre()
{
C[] = ;
for(int i = ; i <= MAXN; i++) {
C[i] = C[i-] * ( * i - ) % MOD * QuickPow(i + , MOD-) % MOD;
}
} int main()
{
Pre(); int t;
int n; scanf("%d", &t);
for(int cas = ; cas <= t; cas++) {
scanf("%d", &n);
printf("Case #%d:\n%I64d\n", cas, C[n]);
} return ;
}
04-19 16:43
查看更多