其他分享
首页 > 其他分享> > 卡特兰数例题

卡特兰数例题

作者:互联网

例题

1.满足条件的01序列

给定 n 个 0 和 n 个 1,它们将按照某种顺序排成长度为 2n 的序列,求它们能排列成的所有序列中,能够满足任意前缀序列中 0 的个数都不少于 1 的个数的序列有多少个。

输出的答案对 109+7 取模。

输入格式
共一行,包含整数 n。

输出格式
共一行,包含一个整数,表示答案。

数据范围
1≤n≤105
输入样例:
3
输出样例:
5
答案 = C 2 n n n + 1 \frac{C_{2n}^n}{n+1} n+1C2nn​​
因为1e9+7是质数,所以可以直接用费马小定理求逆元

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e5+10,mod = 1e9+7;;
int qmi(int a,int b,int p)
{
	int res=1;
	while(b)
	{
		if(b&1) res=(LL)res*a%p;
		a=(LL)a*a%p;
		b>>=1;
	}
	return res;
}
int main()
{
	int n;
	scanf("%d",&n);
	int res=1;
	int a=2*n,b=n;
	for(int i=a;i>a-b;i--)
	res=(LL)res*i%mod;
	for(int i=1;i<=b;i++)
	res=(LL)res*qmi(i,mod-2,mod)%mod;
	res=(LL)res*qmi(n+1,mod-2,mod)%mod;
	printf("%d",res);
	return 0;
} 

标签:int,res,LL,1e9,序列,例题,卡特兰
来源: https://blog.csdn.net/qq_45928501/article/details/119281906