zoukankan      html  css  js  c++  java
  • 【洛谷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
    ",ans);
    	}
    	return 0;
    } 
    
  • 相关阅读:
    ACM 人见人爱A^B
    ACM Max Factor
    ACM Primes
    ACM Least Common Multiple
    ACM 最小公倍数
    ACM Bone Collector
    ACM 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活
    ACM Piggy Bank
    ACM 饭卡
    ACM Where is the Marble?
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10990473.html
Copyright © 2011-2022 走看看