hdoj 1114 Piggy-Bank(完全背包+dp)

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

思路分析:该问题要求为多重背包问题,使用多重背包的解法即可;假设dp[v]表示容量为v的背包中能够装下的最少的价值,因为一件物品可以装无限数次,所以可以得到递推公式: dp[v] = Min(dp[v], dp[v- c[i]] + w[i]);

 

代码如下:

import java.util.*;

public class Main {
    static final int MAX_N = 10000 + 100;
    static final int MAX_INT = 100000000;
    static int[] w = new int[MAX_N];
    static int[] c = new int[MAX_N];
    static int[] dp = new int[MAX_N];
    
    public static int Min(int a, int b) {
        return a < b ? a : b;
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int case_times = in.nextInt();
        
        while (case_times-- != 0) {
            int v_pig, v_total, V, N;
            
            v_pig = in.nextInt();
            v_total = in.nextInt();
            N = in.nextInt();
            V = v_total - v_pig;
            Arrays.fill(dp, MAX_INT);
            dp[0] = 0;
            for (int i = 1; i <= N; ++ i){
                w[i] = in.nextInt();
                c[i] = in.nextInt();
            }
            for (int i = 1; i <= N; ++ i)
                for (int v = c[i]; v <= V; ++ v)
                    dp[v] = Min(dp[v], dp[v - c[i]] + w[i]);
            if (dp[V] == MAX_INT)
                System.out.println("This is impossible.");
            else
                System.out.println("The minimum amount of money in the piggy-bank is " + dp[V] + ".");
        }
    }
}

你可能感兴趣的:(hdoj 1114 Piggy-Bank(完全背包+dp))