容斥原理
算法简述
在集合S中至少具有,,…中的一个元素的个数是:
主要运用场合与思路:
简单的讲:容斥原理的最重要的应用就是去重。如果完成一件事情有n类方式,…,每一类进行方式有中方法(1 <= i <=n),但是这些方法在合并时存在重叠现象,这时可以选择尝试容斥原理。在比赛中单独使用容斥原理的情况并不多见,常见的问题有错排问题等。
模板
可以用二进制的思想来枚举所有可能的情况,若某位上置1则表示要选取该元素,最后统计1的数目的奇偶性来判断是加上还是减去所求的值。可参考以下结构:
for(int i = 0; i < (1<<fn); i++) {
int cnt = 0;
int num = 0;
for(int j = 0; j < fn; j++) {
if((1<<j)&i) {
num = num * fac[j];
cnt++;
}
}
LL d = R/num;
if(cnt&1) ans -= 1LL*num*d*(d+1)/2;
else ans += 1LL*num*d*(d+1)/2;
}
例题
HDU 1695 GCD
题意 :
求有多少对(x,y)(1<=x<=b,1<=y<=d)满足。
题解
gcd(x,y)=k,说明x,y都能被k整除,那么
于是问题就转化为两个区间内寻找有多少对数互质。假设b<=d,我们可以在中枚举数i,对于每一个i,我们只需找到在中与i互质的个数,最后依次相加就可得到结果。 当i<=b/k时可以用欧拉函数求与i互质的个数,当b/k < i <= d/k时,区间中与i互质的个数 = b/k - (区间中与i不互质的个数)。区间中与i不互质的数则就是i中素因子的倍数,将它们相加则就是答案,但是由于会有重叠部分,比如6既是2的倍数又是3的倍数,此时就可以用容斥原理来求解。
AC代码
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define CLR(a,b) memset(a,(b),sizeof(a))
const int N = 1e5+10;
LL phi[N];
int num[N][20];
int arr[N];
void eular()
{
CLR(phi,0);
phi[1] = 1;
for(LL i = 2; i < N; i++) {
if(!phi[i]) {
for(LL j = i; j < N; j+=i) {
if(!phi[j]) phi[j] = j;
phi[j] = phi[j]*(i-1)/i; // 溢出
num[j][arr[j]++] = i; //求得的质因数
}
}
phi[i] += phi[i-1];
}
}
int iex(int x, int y) //二进制容斥
{
int ans = 0;
for(int i = 1; i < (1<<arr[x]); i++) {
int cnt = 0;
int nu = 1;
for(int j = 0;j < arr[x]; j++) {
if((1<<j) & i) {
nu *= num[x][j];
cnt++;
}
}
if(cnt & 1) ans += y/nu;
else ans -= y/nu;
}
return ans;
}
int main()
{
int zz = 0;
int a, b, c, d, k;
eular();
int T;
scanf("%d",&T);
while(T--) {
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
printf("Case %d: ",++zz);
if(k == 0) {
printf("0\n"); continue;
}
if(b > d) swap(b,d);
b /= k; d /= k;
LL ans = phi[b];
for(int i = b+1; i <= d; i++) ans += b-iex(i,b);
printf("%lld\n",ans);
}
return 0;
}
鸽巢原理 :
如果有n+1个鸽子要进n个鸽巢,则至少存在一个鸽巢种包含两个或更多的鸽子。
看上去是一句“废话”,不过这句”废话“在用来证明一个排列或则某种现象的存在性上相当有魅力
关于鸽巢原理更抽象的表述:
• If X has more elements than Y, then f is not one-to-one.
• If X and Y have the same number of elements and f is onto, then f is one-to-one.
• If X and Y have the same number of elements and f is one-to-one, then f is onto.
鸽巢原理的加强形式
定理: 令q1, q2, q3, …., qn为正整数。如果将 q1, q2, q3, …., qn - n + 1 个物体放到n个盒子中,则存在一个i,使得第i个盒子至少含有qi个物品 ;
证明: 假设将q1, q2, q3, …., qn - n + 1个物品分别放到n个盒子里。如果每一个i (i = {1, 2, ..n}),第i个盒子中放少于qi 个物品,则所有盒子所放物品的总数不超过
(q1 - 1) + (q2 - 1) + … + (qn - 1) = q1 + q2 + … + qn - n
显然,比所要放的总数少一个。因此可以确定,对某个i (i = {1, 2, .. n}),第i个盒子至少包含qi个物品。
例题
HDU 1205
很裸的题…
AC代码
#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 1e6+10;
int arr[N];
int main()
{
int T;
scanf("%d",&T);
while(T--) {
int n;
int ans = 0;
LL sum = 0;
scanf("%d",&n);
for(int i = 0;i < n; i++) {
scanf("%d",&arr[i]);
ans = max(ans,arr[i]);
sum += arr[i];
}
sort(arr,arr+n);
if(sum >= ans*2-1) puts("Yes");
else puts("No");
}
return 0;
}