【洛谷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;
} 

转载于:https://www.cnblogs.com/wzj-xhjbk/p/10990473.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值