[背包dp+容斥定理] luogu 1450 硬币购物

题目

在这里插入图片描述
题目链接:https://www.luogu.com.cn/problem/P1450

思路

如果只询问次数很少 可以完全背包
不过这个询问次数很多要超时
那么就预处理 1 — 1 e 5 1—1e5 11e5的背包的值
每次带了d[i]枚硬币 那么d[i]+1之后的硬币就不行
s − c [ i ] ∗ ( d [ i ] + 1 ) s-c[i]*(d[i]+1) sc[i](d[i]+1)就是第i个硬币能取的最大钱钱
d p [ s − c [ i ] ∗ ( d [ i ] + 1 ) ] dp[s-c[i]*(d[i]+1)] dp[sc[i](d[i]+1)]就是第i个硬币的可能性
不过这道题 还要考虑一下容斥的东西
在这里插入图片描述
用二进制枚举一下每种情况。

代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<ctime>
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<iomanip>
#include<list>
#include<bitset>
#include<sstream>
#include<fstream>
#include<complex>
#include<algorithm>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#define int long long
using namespace std;
const int INF = 0x3f3f3f3f;
int c[10],d[10];
int dp[100010];
signed main(){
	ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	int n;
	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<=100000;j++){
			dp[j]+=dp[j-c[i]];
		}
	}
	while(n--){
		for(int i=1;i<=4;i++){
			cin>>d[i];
		}
		int s;
		cin>>s;
		int ans=dp[s];
		for(int i=1;i<=15;i++){
			int k=0,num=0;
			for(int j=0;j<4;j++){
				if(i&(1<<j)){
					num++;
					k+=c[j+1]*(d[j+1]+1);
				}
			}
				int f=1;
				if(num%2) f=-1;
				if(s>=k) ans+=f*dp[s-k];
		}
		cout<<ans<<endl;
	}
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值