The Fewest Coins(多重背包+完全背包)
Farmer John has gone to town to buy some farm supplies. Being a very efficient man, he always pays for his goods in such a way that the smallest number of coins changes hands, i.e., the number of coins he uses to pay plus the number of coins he receives in change is minimized. Help him to determine what this minimum number is.
FJ wants to buy T (1 ≤ T ≤ 10,000) cents of supplies. The currency system has N (1 ≤ N ≤ 100) different coins, with values V1, V2, ..., VN (1 ≤ Vi ≤ 120). Farmer John is carrying C1 coins of value V1, C2 coins of value V2, ...., and CN coins of value VN (0 ≤ Ci ≤ 10,000). The shopkeeper has an unlimited supply of all the coins, and always makes change in the most efficient manner (although Farmer John must be sure to pay in a way that makes it possible to make the correct change).
Input
Line 1: Two space-separated integers: N and T.
Line 2: N space-separated integers, respectively V 1, V 2, ..., VN coins ( V 1, ... VN)
Line 3: N space-separated integers, respectively C 1, C 2, ..., CN
Output
Line 1: A line containing a single integer, the minimum number of coins involved in a payment and change-making. If it is impossible for Farmer John to pay and receive exact change, output -1.
Sample Input
3 70
5 25 50
5 2 1
Sample Output
3
Hint
Farmer John pays 75 cents using a 50 cents and a 25 cents coin, and receives a 5 cents coin in change, for a total of 3 coins used in the transaction.
题意:农民去买东西,他有n种硬币并且每种硬币都有一定数量,然后商家有这n种硬币不限数量。最后求农民买东西最少要花多少个硬币(他所支付的和商家找零给他的),也就是说农民可以刚好支付t,也可以是通过支付x找零y达到t,两者的关系是t=x-y,也就是说找零的钱数y=x-t,那么可以对农民的硬币运用多重背包求解出dp[],然后对商家进行完全背包dp2[],两者关系是总硬币数ans=(dp[i]+dp2[i-t])min,代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define INF 0x3f3f3f
int p[300000]={0},q[300000]={0};
int dp[25020],dp2[25020];
int n,t,top=0,v[105],c[105];
int main(){
memset(dp,INF,sizeof(dp));
memset(dp2,INF,sizeof(dp2));
dp[0]=0;
dp2[0]=0;
scanf("%d%d",&n,&t);
for(int i=0;i<n;i++)
scanf("%d",&v[i]);
for(int i=0;i<n;i++)
scanf("%d",&c[i]);
for(int i=0;i<n;i++){
for(int j=1;j<=c[i];j<<=1){
p[top]=j*v[i]; //记录钱数
q[top]=j; //记录硬币数
c[i]-=j;
top++;
}
if(c[i]>0){
p[top]=c[i]*v[i];
q[top]=c[i];
top++;
}
} //二进制优化,把多重背包转化成01背包
for(int i=0;i<top;i++){
for(int j=t+10000;j>=p[i];j--){
dp[j]=min(dp[j],dp[j-p[i]]+q[i]);
}
}
for(int i=0;i<n;i++){
for(int j=v[i];j<=t+10000;j++){
dp2[j]=min(dp2[j],dp2[j-v[i]]+1);
}
} //完全背包(商家找零的硬币数)
int ans=INF;
for(int i=t;i<=t+10000;i++)
ans=min(ans,dp[i]+dp2[i-t]); //求出最小硬币数
if(ans==INF)
printf("-1\n");
else{
printf("%d\n",ans);
}
return 0;
}