POJ3260:The Fewest Coins(混合背包)

来源:互联网 发布:c语言进程的创建 编辑:程序博客网 时间:2024/05/01 07:56

Description

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 hasN (1 ≤N ≤ 100) different coins, with values V1,V2, ...,VN (1 ≤ Vi ≤ 120). Farmer John is carryingC1 coins of valueV1, C2 coins of valueV2, ...., andCN 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 andT.
Line 2: N space-separated integers, respectively V1, V2, ...,VN coins (V1, ...VN)
Line 3: N space-separated integers, respectively C1, C2, ...,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 705 25 505 2 1

Sample Output

3
 
题意:给出钱币的方案数和总价值,然后给出每种钱币的价值与数量,而老板也是每种钱币都拥有,但是没有数量限制,购买东西的时候,价值超过给定价值的话,老板会找钱,要求最小的交流钱币的数量
 
思路:这题想了很久没有想出思路,虽然知道是背包,但是不知道该如何让运用,看了别人的代码,感觉人家的思路真心碉堡了,讲解在代码中
 
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int v[105],c[105],MAX,n,sum;int dp[33333],inf = 100000000;void ZeroOnePack(int cost,int cnt){    int i;    for(i = sum+MAX; i>=cost; i--)        dp[i] = min(dp[i],dp[i-cost]+cnt);//找出最小数量的方案}void CompletePack(int cost,int cnt){    int i;    for(i = sum+MAX+cost; i>=0; i--)        dp[i] = min(dp[i],dp[i-cost]+cnt);}int MultiplePack(){    int i,j,k;    for(i = 1; i<=sum+MAX; i++)        dp[i] = inf;    dp[0] = 0;//dp数组用来记录钱币数量    for(i = 1; i<=2*n; i++)    {        if(i<=n)//这是顾客购买时所给的钱的数量        {            k = 1;            while(k<c[i])            {                ZeroOnePack(k*v[i],k);                c[i]-=k;                k*=2;            }            ZeroOnePack(c[i]*v[i],c[i]);        }        else            CompletePack(-v[i-n],1);//只所以是负数,是因为这是老板找钱的数目    }    if(dp[sum]==inf)        return -1;    else        return dp[sum];}int main(){    int i;    while(~scanf("%d%d",&n,&sum))    {        MAX = 0;        for(i=1; i<=n; i++)        {            scanf("%d",&v[i]);            MAX = max(MAX,v[i]);        }        MAX*=MAX;//保证背包足够大        for(i=1; i<=n; i++)            scanf("%d",&c[i]);        printf("%d\n",MultiplePack());    }    return 0;}

原创粉丝点击