容斥原理笔记
例题
求
我们要将多算的给减掉。显然当
这即是容斥原理。
简单来说就是“奇加偶减”。(其实这么说也不好)
练习
题面
- 给出一个长度为
n 的序列a ,问在区间[L,R] 中有多少个数,至少能被a 中的一个数整除。
注意,
对于一种非法转移,我们已经了解了,但是如果两种都非法呢?被多减去了。
从状态转移开始讨论。
但是
代码
#include<bits/stdc++.h>
using namespace std;
int c[5],d[5],dp[100005],n;
int main() {
for(int i=1;i<=4;i++) cin>>c[i];
cin>>n;
dp[0]=1;
for(int i=1;i<=4;i++) {
for(int j=c[i];j<=100000;j++) {
dp[j]+=dp[j-c[i]];
}
}
while(n--) {
int s;
for(int j=1;j<=4;j++) {
cin>>d[j];
}cin>>s;
int ans=0;
for(int i=0;i<1<<4;i++) {//全 0 的情况会使 ans = dp_s。所以答案就是总共的方案数减去非法方案数。
int p=0,cnt=0;
for(int j=0;j<4;j++) {
if((i>>j) & 1) cnt++, p+=c[j+1]*(d[j+1]+1);
}
if(s-p>=0){
if(cnt & 1) ans-=dp[s-p];
else ans+=dp[s-p];
}
}
cout<<ans<<"\n";
}
return 0;
}
题面
- 武林中流传了
m 种武功,现在有n 个习武之人去学习一些武功,经过深思熟虑,每个人都选择了5 个不同的武功,名字叫a_1\dots a_5 。 并学习成功,现在由于武林盟主失踪,群龙无首,这n 个人发生了叛乱,任意两个人x 和y ,如果存在一种相同的武功他们俩都会,那么他们俩就是朋友,反之他们就是敌人,问n 个人中有多少对敌人。
现在有大小为
那如果有大小为
同时会两种武功的人肯定也是同时会一种武功的人,他们是有包含关系的。所以套文章开头公式即可,剩下的省略。对于统计是否同时会
本文实现的是比较简单暴力的写法,常数特别大。枚举后用 vector 存到 map 里面遍历。
#pragma GCC optimize(3,"Ofast","inline")
#include<bits/stdc++.h>
#define rint register unsigned int
using namespace std;
map<vector<int>,pair<int,int> >mp;
signed main() {
ios::sync_with_stdio(0); cin.tie(0), cout.tie(0);
int n; cin>>n;
for(rint i=1;i<=n;i++) {
vector<int>a(5,0);
for(rint j=0;j<5;j++) cin>>a[j];
sort(a.begin(),a.end());
vector<int>t(5,0);
for(rint j=1;j<1<<5;j++) {
rint cnt=0;
for(rint k=0;k<5;k++) {
if((j>>k) & 1) t[k]=a[k],cnt++;
else t[k]=0;
}
sort(t.begin(),t.end());
mp[t].first++,mp[t].second = cnt;
}
}
int ans = 0;
for(auto it:mp) {
auto j = it; int k = j.second.first;
if(j.second.second & 1) ans+= (k-1)*k;
else ans-= (k-1)*k;
}
cout<<((n-1)*n-ans)/2;
return 0;
}