1042: [HAOI2008]硬币购物
Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 2824 Solved: 1735
[Submit][Status][Discuss]
Description
硬币购物一共有4种硬币。面值分别为c1,c2,c3,c4。某人去商店买东西,去了tot次。每次带di枚ci硬币,买s
i的价值的东西。请问每次有多少种付款方法。
Input
第一行 c1,c2,c3,c4,tot 下面tot行 d1,d2,d3,d4,s,其中di,s<=100000,tot<=1000
Output
每次的方法数
Sample Input
1 2 5 10 2
3 2 3 1 10
1000 2 2 2 900
Sample Output
4
27
题解
用容斥原理,方案数=1,2,3,4号硬币非法的方案数-1,2,3号硬币非法的方案数-1,2,4号硬币非法的方案数…+1,2号硬币非法的方案数+1,3号硬币非法的方案数+…-1号硬币非法的方案数-2号硬币非法的方案数-…。
(1,2,3号硬币非法的方案中4是否非法不管)
先用背包跑出0-S的方案数,然后0-(1<<4)枚举所有非法情况,对于二进制上为1的硬币,减去他(d[i]+1)*c[i]的价值,强制使它非法,然后剩余的价值随便,直接加上f[s-(d[k]+1)*c[k]]。
代码
.
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#define LL long long
using namespace std;
const int S=100005;
int tot,s;
int c[10],d[10];
LL ans;
LL f[S];
int main(){
scanf("%d%d%d%d%d",&c[1],&c[2],&c[3],&c[4],&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]];
}
}
int temp,cnt;
while(tot--){
ans=0;
scanf("%d%d%d%d%d",&d[1],&d[2],&d[3],&d[4],&s);
for(int i=0;i<(1<<4);i++){
cnt=0,temp=s;
for(int j=1;j<=4;j++){
if(i&(1<<(j-1))){
temp-=(d[j]+1)*c[j];
cnt++;
}
}
if(temp>=0){
if(cnt&1)ans-=f[temp];
else ans+=f[temp];
}
}
printf("%lld\n",ans);
}
return 0;
}