容斥原理(模板)

题目链接

容斥模板

题目描述,N, M , 然后输入M个数,求1 到N-1内 能被M中的数整除的个数

思路:M个数中进行组合,如果为奇数个则+,为偶数个则 -。用Dfs 找组合数。

#include<iostream>
#include<cstring>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long LL;
const int Maxn = 20;
int Number[Maxn + 5];
int N, M, Tot;
LL Ans = 0;
LL Gcd(LL A, LL B){
	return !B ? A : Gcd(B, A % B);
}
void Dfs(int Cur, int Cnt, int Limit, LL LCM){
	if (Cnt == Limit) {
		if (Limit & 1) {
			Ans += (N - 1) / LCM;
		}
		else {
			Ans -= (N - 1) / LCM;
		}
		return;
	}
	if (Cur >= Tot) {
		return ;
	}
	LL NowLCM = LCM == -1 ? Number[Cur] : LCM;
	Dfs(Cur + 1, Cnt + 1, Limit, Number[Cur] / Gcd(NowLCM, Number[Cur]) * NowLCM);
	Dfs(Cur + 1, Cnt, Limit, LCM);
}
int main(){
	while (~scanf("%d%d", &N, &M)) {
		Tot = 1;
		int X;
		for (int i = 1; i <= M; ++i) {
			scanf("%d", &X);
			if (X) {
				Number[Tot++] = X;
			}
		} 
		Ans = 0;
		for (int i = 1; i < Tot; i++) {
			Dfs(1, 0, i, -1);
		} 
		printf("%lld\n", Ans);
	}
}

应该是有更快的方法

思路:上述方法是找出一组(比如找出3个)的后(把3个的不同组合全找出来再进行+-)但是我们找(4······N-1)时发现3个不同的组合是 (4·····N-1)的子集,那就可以在找的过程中进行+-。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值