容斥原理及其简单例题
容斥原理是一种计数方法,能够避免技术时重复和遗漏,其基本思想是:先不考虑重叠的情况,把包含于某内容中的所有对象的数目先计算出来,然后再把计数时重复计算的数目排斥出去,使得计算的结果既无遗漏又无重复。
举个例子:有A,B,C三个集合,我们要求三个集合的并集的元素个数(已知集合交集的元素个数),可以表示为:
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 50005
#define ll long long
#define un unsigned
using namespace std;
ll prime[N];
ll n, m;
ll ans = 0;
ll num_prime;
inline void dfs(ll x, ll mm, ll p){//容斥
if(x == num_prime + 1){
ans += mm * p;
return ;
}
dfs(x+1, mm, p);
dfs(x+1, mm/prime[x], -p);
}
int main(){
scanf("%lld %lld", &n, &m);
for(int i = 1; i <= n; i++){//枚举i
num_prime = 0;
ll num = (ll)i;
for(int j = 2; j <= sqrt(num); j++){//将i分解质因数
if(!(num % j)) {
prime[++num_prime] = j;
while(!(num % j)) num /= j;
}
}
if(num > 1) prime[++num_prime] = num;
ans = 0;
dfs(1, m, 1);
printf("%lld\n", ans);
}
return 0;
}
例3:P2567 [SCOI2010]幸运数字
先预处理出1到区间右端点的所有幸运数字,再利用容斥求近似幸运数字。
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define ll long long
#define N 4005
ll luck[N], luck_num;
ll luc[N], cnt;
ll a, b, ans = 0, now;
inline ll gcd_(ll x, ll y){
if(y == 0) return x;
return gcd_(y, x % y);
}
inline void fi(ll r,ll numb){
if(numb > r) return ;
if(numb) luck[++luck_num] = numb;
fi(r, numb * 10 + 6);
fi(r, numb * 10 + 8);
}
inline void dfs(ll x, ll p){
if(x == cnt + 1){
if(!p) return ;
if(p & 1) ans += b / now - (a - 1) / now;
//类似前缀和思想
else ans -= b / now - (a - 1) / now;
return ;
}
dfs(x + 1, p);
ll befor = now;
now = now / gcd_(now, luc[x]);
if((double)now * luc[x] <= b){
now *= luc[x];
dfs(x + 1, p + 1);
}
now = befor;
}
int main(){
scanf("%lld %lld", &a, &b);
fi(b, 0);
sort(luck + 1,luck + 1 + luck_num);
for(int i = 1; i <= luck_num; i++){
luc[++cnt] = luck[i];
for(int j = 1; j < cnt; j++)
if(!(luck[i] % luc[j])){
cnt--; break;
}
}
reverse(luc + 1, luc + 1 + cnt);
now = 1;
dfs(1, 0);
printf("%lld", ans);
return 0;
}