【洛谷P1450】硬币购物

题目大意:给定 4 种面值的硬币和相应的个数,求购买 S 元商品的方案数是多少。

题解:
考虑没有硬币个数的限制的话,购买 S 元商品的方案数是多少,这个问题可以采用完全背包进行预处理。
再考虑容斥,即:可以采用总方案数 - sum(一种硬币不合法的方案数) + sum(两种) - sum(三种)...

代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
typedef long long LL;

LL dp[maxn];
int c[5],tot,s,d[5];

void prework(){
	dp[0]=1;
	for(int i=1;i<=4;i++)
		for(int j=c[i];j<=1e5;j++)
			dp[j]+=dp[j-c[i]];
}
int main(){
	for(int i=1;i<=4;i++)scanf("%d",&c[i]);
	scanf("%d",&tot);
	prework();
	while(tot--){
		for(int i=1;i<=4;i++)scanf("%d",&d[i]);
		scanf("%d",&s);
		LL ans=dp[s];
		for(int i=1;i<1<<4;i++){
			int cnt=1; LL sum=0;
			for(int j=1;j<=4;j++){
				if(i>>(j-1)&1){
					cnt=-cnt,sum+=(LL)(d[j]+1)*c[j];
				}
			}
			if(sum>s)continue;
			ans+=cnt*dp[s-sum];
		}
		printf("%lld\n",ans);
	}
	return 0;
} 
posted @ 2019-06-08 13:04  shellpicker  阅读(148)  评论(0编辑  收藏  举报