【codevs1869】硬币购物,背包+神奇的容斥原理

来源:互联网 发布:c语言加密算法 编辑:程序博客网 时间:2024/05/09 20:19

硬币购物 2008年
时间限制: 1 s
空间限制: 256000 KB
题目等级 : 大师 Master
题解
题目描述 Description
一共有4种硬币。面值分别为c1,c2,c3,c4。某人去商店买东西,去了tot次。 每次带di枚ci硬币,买si的价值的东西。请问每次有多少种付款方法。

输入描述 Input Description
第一行 c1,c2,c3,c4,tot 下面tot行 d1,d2,d3,d4,s

输出描述 Output Description
每次的方法数

样例输入 Sample Input
1 2 5 10 2
3 2 3 1 10
1000 2 2 2 900

样例输出 Sample Output
4
27

数据范围及提示 Data Size & Hint

di,s<=100000
tot<=1000


UPD 2017.1.3
典型的背包问题,但由于数量太大,复杂度为O(sdi),所以不能直接dp
不过物品种类比较少,只有四种,所以我们可以把问题写成这个样子
求下面关于xi的方程的解的个数
c1x1+c2x2+c3x3+c4x4=s
其中xidi
这几乎和容斥中的经典问题——“求未知数有上界限制的方程解个数”一模一样
所以我们可以套容斥试试
先求出xi没有限制下方程的非负整数解
这就相当于是一个完全背包
枚举{xi}的子集,把上界限制转化成下界限制xidi+1,然后再做完全背包
利用容斥加减一下就出来了
代码:

#include<cstdio>#define LL long long using namespace std;int tot,c[5],d[5],s;LL f[100005],ans;void dfs(int x,int y,int sum){    if (sum<0) return;    if (x>4)    {        if (y&1) ans-=f[sum];        else ans+=f[sum];        return;    }    dfs(x+1,y,sum);    dfs(x+1,y+1,sum-c[x]*(d[x]+1));}main(){    for (int i=1;i<=4;++i) scanf("%d",c+i);    scanf("%d",&tot);    f[0]=1;    for (int i=1;i<=4;++i)        for (int j=c[i];j<=100000;++j)            f[j]+=f[j-c[i]];    while (tot--)    {        ans=0;        for (int i=1;i<=4;++i) scanf("%d",d+i);        scanf("%d",&s);        dfs(1,0,s);        printf("%lld\n",ans);    }} 
0 0
原创粉丝点击