POJ3260——背包DP(多重)——The Fewest Coins

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 has N (1 ≤ N ≤ 100) different coins, with values V1V2, ..., VN (1 ≤ Vi≤ 120). Farmer John is carrying C1 coins of value V1C2 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 V1V2, ..., VN coins ( V1, ... VN
Line 3: N space-separated integers, respectively C1C2, ..., 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.
大意:让你找钱,最少流通的货币,买东西时货币有限制,找钱的时候货币没限制,多重背包问题用二进制01背包轻松解决,用函数来写清楚多了~
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX = 50010;
const int inf = 0x3f3f3f3f;
int dp[50010];
int w[110],num[110];
int n,m;
void oneback(int w,int v){
    for(int i =  MAX ; i >= w; i--)
        dp[i] = min(dp[i],dp[i-w]+v);
}
void comback(int w,int v){
    for(int i = MAX+w ; i>= 0; i--)
        dp[i] = min(dp[i],dp[i-w]+v);
}
int multiplepack()
{
    int k ;
    for(int i = 1; i <= MAX; i++)
        dp[i] =inf;
    dp[0] = 0;
    for(int i = 1; i <= 2*n;i ++){
        if( i <= n){
             k = 1;
            while(k < num[i]){
                oneback(k*w[i],k);
                num[i] -= k;
                k*= 2;
            }
            oneback(num[i]*w[i],num[i]);
        }
        else 
            comback(-w[i-n],1);
    }
    if(dp[m] == inf)
        return -1;
    else return dp[m];
}
int main()
{
    while(~scanf("%d%d",&n,&m)){
        memset(dp,0,sizeof(dp));
        for(int i = 1; i <= n ; i++)
            scanf("%d",&w[i]);
        for(int i = 1; i <= n ; i++)
            scanf("%d",&num[i]);
        printf("%d
",multiplepack());
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/zero-begin/p/4470711.html