hdoj 2546 饭卡(0-1背包)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2546

思路分析:该问题为0-1背包问题的变形题;问题求余额最少,设开始的余额为V,则求得用V-5可以买到的菜的最大价值,最后留下的5元则用来买菜价最高的菜,可以证明这种购买方式是能够产生最优解的;另外,因为题目要求所有的菜只能买一次,所以在求V-5能买最多价值的菜时不能买菜价最高的菜,因为菜价最高的菜一定是用剩下的5元钱来购买的;

代码如下:

import java.util.*;

public class Main {
    static final int MAX_N = 1000 + 10;
    static int[] c = new int[MAX_N];
    static int[] dp = new int[MAX_N];
    
    static int Max(int a, int b) {
        return a > b ? a : b;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N, V;
        
        while ((N = in.nextInt()) != 0) {
            int max_value = 0;
            
            Arrays.fill(dp, 0);
            for (int i = 0; i < N; ++ i) {
                c[i] = in.nextInt();
                if (c[i] > max_value)
                    max_value = c[i];
            }
            Arrays.sort(c, 0, N);
            V = in.nextInt();
            for (int i = 0; i < N - 1; ++ i) {
                for (int v = V - 5; v >= c[i]; -- v) {
                        dp[v] = Max(dp[v], dp[v - c[i]] + c[i]);
                }
            }
            if (V < 5)
                System.out.println(V);
            else
                System.out.println(V - dp[V-5] - c[N - 1]);
        }
    }
}
原文地址:https://www.cnblogs.com/tallisHe/p/4687558.html