码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-31 12:08:41      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

题目链接: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)

标签:

原文地址:http://www.cnblogs.com/tallisHe/p/4691432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!