hdu 1796 How many integers can you find 容斥原理模板
题意:给你一个数N,和有一个M个数的集合a1,a2,...,aM。0<N<2^31,0<M<=10,集合中每个元素∈[0, 20]。求[2,N-1]区间中有多少个数能被集合中的某一个元素整除。
分析:首先考虑特殊情况,N<2 , 答案为0; 如果集合中某个数为0,可以直接剔除。
当M==1,答案就是N / a1。
当M==2,答案就是N / a1 + N / a2 - N / lcm(a1, a2);
当M==3,答案就是N / a1 + N / a2 + N / a3 - N / lcm(a1, a2) - N / lcm(a1, a3) - N / lcm(a2, a3) + N / lcm(a1, a2, a3)。
......
依此类推, 然后就是奇加偶减的容斥了。相比一般的DFS的容斥,挑战竞赛的位运算的写法牛逼多了咯。233333....
#include <cmath>
#include <queue>
#include <vector>
#include <cstdio>
#include <string>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w",stdout)
#define fst first
#define snd second
typedef __int64 LL;
//typedef long long LL;
typedef unsigned int uint;
typedef pair<int, int> PII;
const int MAXN = 30;
int T, N, M;
int A[MAXN];
template <typename T>
T gcd(const T& a, const T& b) {
return b == 0 ? a : gcd(b, a % b);
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
while(~scanf("%d %d", &N, &M)) {
for(int i = 0; i < M; i++) {
scanf("%d", &A[i]);
if(!A[i]) {
i --;
M --;
}
}
if(N <= 2) {
printf("0\n");
continue;
}
N--;
LL res = 0;
for(int i = 1; i < (1 << M); i++) {
// 用i的二进制形式中的0, 1 表示集合中对应的元素是否选取。 用num统计 i 中1的个数。
int num = 0;
for(int j = i; j; j >>= 1) num += j & 1;
LL lcm = 1LL;
for(int j = 0; j < M; j++) {
if(!A[j]) continue;
if((i >> j) & 1) {
lcm = (LL)lcm / gcd(lcm, (LL)A[j]) * A[j];
if(lcm > N) break;
}
}
// num 奇加偶减
if(num & 1) res += N / lcm;
else res -= N / lcm;
}
printf("%I64d\n", res);
}
return 0;
}