1.概念
一般地,设全集为,满足不同条件的子集为,则。
n个条件中至少满足一个的子集数量:
n个条件都不满足的子集数量:
2.应用
1.硬币购物
暴力做法是多重背包,但是这样每次循环都需要重新遍历,直接时间超限。
我们考虑用容斥原理,设dp[i]表示花费i块钱的可能方案数,用完全背包预处理。然后我们考虑怎么将四个限制都限制出来。
我们可以在所有状态中减去不满足状态的条件。如何减呢?第一种硬币超限时,一定选了至少个币,剩下的随便选,我们可以在总答案里减去,表示已经预先选了个币的情况数。其他不满足条件的方案用容斥原理算出即可。最终复杂度:
Code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#define int long long
using namespace std;
const int N=1e5+10;
int c[5],d[5],n,s,dp[N];
signed main(){
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
for(int i=1;i<=4;i++){
cin>>c[i];
}
dp[0]=1;
for(int i=1;i<=4;i++){
for(int j=c[i];j<N;j++){
dp[j]+=dp[j-c[i]];
}
}
cin>>n;
while(n--){
for(int i=1;i<=4;i++){
cin>>d[i];
}
cin>>s;
int ans=dp[s];
if(s-c[1]*(d[1]+1)>=0){
ans-=dp[s-c[1]*(d[1]+1)];
}
if(s-c[2]*(d[2]+1)>=0){
ans-=dp[s-c[2]*(d[2]+1)];
}
if(s-c[3]*(d[3]+1)>=0){
ans-=dp[s-c[3]*(d[3]+1)];
}
if(s-c[4]*(d[4]+1)>=0){
ans-=dp[s-c[4]*(d[4]+1)];
}
if(s-c[1]*(d[1]+1)-c[2]*(d[2]+1)>=0){
ans+=dp[s-c[1]*(d[1]+1)-c[2]*(d[2]+1)];
}
if(s-c[1]*(d[1]+1)-c[3]*(d[3]+1)>=0){
ans+=dp[s-c[1]*(d[1]+1)-c[3]*(d[3]+1)];
}
if(s-c[1]*(d[1]+1)-c[4]*(d[4]+1)>=0){
ans+=dp[s-c[1]*(d[1]+1)-c[4]*(d[4]+1)];
}
if(s-c[2]*(d[2]+1)-c[3]*(d[3]+1)>=0){
ans+=dp[s-c[2]*(d[2]+1)-c[3]*(d[3]+1)];
}
if(s-c[2]*(d[2]+1)-c[4]*(d[4]+1)>=0){
ans+=dp[s-c[2]*(d[2]+1)-c[4]*(d[4]+1)];
}
if(s-c[3]*(d[3]+1)-c[4]*(d[4]+1)>=0){
ans+=dp[s-c[3]*(d[3]+1)-c[4]*(d[4]+1)];
}
if(s-c[1]*(d[1]+1)-c[2]*(d[2]+1)-c[3]*(d[3]+1)>=0){
ans-=dp[s-c[1]*(d[1]+1)-c[2]*(d[2]+1)-c[3]*(d[3]+1)];
}
if(s-c[1]*(d[1]+1)-c[2]*(d[2]+1)-c[4]*(d[4]+1)>=0){
ans-=dp[s-c[1]*(d[1]+1)-c[2]*(d[2]+1)-c[4]*(d[4]+1)];
}
if(s-c[1]*(d[1]+1)-c[3]*(d[3]+1)-c[4]*(d[4]+1)>=0){
ans-=dp[s-c[1]*(d[1]+1)-c[3]*(d[3]+1)-c[4]*(d[4]+1)];
}
if(s-c[2]*(d[2]+1)-c[3]*(d[3]+1)-c[4]*(d[4]+1)>=0){
ans-=dp[s-c[2]*(d[2]+1)-c[3]*(d[3]+1)-c[4]*(d[4]+1)];
}
if(s-c[1]*(d[1]+1)-c[2]*(d[2]+1)-c[3]*(d[3]+1)-c[4]*(d[4]+1)>=0){
ans+=dp[s-c[1]*(d[1]+1)-c[2]*(d[2]+1)-c[3]*(d[3]+1)-c[4]*(d[4]+1)];
}
cout<<ans<<endl;
}
return 0;
}(或者使用二进制枚举)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
int n,s;
int c[10],d[10];
long long dp[100010],ans;
int main(){
cin>>c[1]>>c[2]>>c[3]>>c[4]>>n;
dp[0]=1;
for(int i=1;i<=4;i++){
for(int j=c[i];j<100010;j++){
dp[j]+=dp[j-c[i]];
}
}
while(n--){
cin>>d[1]>>d[2]>>d[3]>>d[4]>>s;
ans=dp[s];
for(int i=1;i<=15;i++){
long long cnt=0,sum=0;
for(int j=1;j<=4;j++){
if(i&(1<<(j-1))){
cnt++;
sum+=c[j]*(d[j]+1);
}
}
if(sum<=s){
if(cnt&1){
ans-=dp[s-sum];
}
else{
ans+=dp[s-sum];
}
}
}
cout<<ans<<endl;
}
return 0;
}