AcWing算法基础课笔记——卡特兰数与容斥原理

卡特兰数

C 2 n n − C 2 n n − 1 = C 2 n n n + 1 C_{2n}^{n} - C_{2n}^{n - 1} = \frac{C_{2n}^n}{n + 1} C2nnC2nn1=n+1C2nn

题目

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

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

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

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

数据范围
1≤n≤105

输入样例:
3
输出样例:
5

代码

#include<iostream>
#include<algorithm>

using namespace std;

typedef long long LL;

const int mod = 1e9 + 7;

int qmi(int a, int k, int p) {
	int res = 1;
	while(k) {
		if(k & 1) res = (LL) res * a % p;
		a = (LL) a * a % p;
		k >>= 1;
	}
	return res;
}

int main() {
	int n;
	cin >> n;
	
	int a = 2 * n, b = n;
	int res = 1;
	
	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;
	
	cout << res << endl;
	return 0;
}

容斥原理

题目

给定一个整数 𝑛 和 𝑚 个不同的质数𝑝1,𝑝2,…,𝑝_𝑚。

请你求出 1∼𝑛 中能被 𝑝1,𝑝2,…,𝑝_𝑚 中的 至少一个数整除的整数 有多少个。

输入格式
第一行包含整数 𝑛 和 𝑚。

第二行包含 𝑚 个质数。

输出格式
输出一个整数,表示满足条件的整数的个数。

数据范围
1≤𝑚≤16,1≤𝑛,𝑝_𝑖≤10^9

输入样例:

10 2
2 3

输出样例:

7

代码

#include<iostream>
#include<algorithm>

using namespace std;

typedef long long LL;

const int N = 20;

int n, m;
int p[N];

int main() {
	cin >> n >> m;
	for(int i  = 0; i < m; i ++) cin >> p[i];
	
	int res = 0;
	for(int i = 1; i < 1 << m; i ++ ) {
		int t = 1, cnt = 0; //t表示质数的乘积, cnt表示i中1的个数,即集合的个数
		//列举每个集合,看是否被选中
		//如果被选中,乘到t中,cnt++,并判断是否大于n,大于n则舍弃 
		for(int j = 0; j < m; j ++ ) {
			if(i >> j & 1) {
				cnt ++;
				if((LL)t * p[j] > n) {
					t = -1;
					break;
				}
				t *= p[j];
			} 
		} 
		
		if(t != -1) {
			if(cnt % 2) res += n / t;
			else res -= n / t;
		}
	}
	
	cout << res << endl;
	return 0;
}
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值