Java模板系列之背包dp-HDU1114

https://vjudge.net/problem/HDU-1114
找了个完全背包的题,用了滚动数组,空间复杂度为n(背包大小),时间复杂度为n*m(物品数量)

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

import java.util.*;

public class Main {

    static class item{
        int val;
        int weight;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n;
        n = input.nextInt();
        while((n--)!=0){
            int a,b;
            a = input.nextInt();
            b = input.nextInt();
            a = b - a;
            int m;
            m = input.nextInt();
            item u[] = new item[m];
            for(int i=0;i<m;i++){
                u[i] = new item();
            }
            for(int i=0;i<m;i++){
                u[i].val = input.nextInt();
                u[i].weight = input.nextInt();
            }
            int dp[] = new int[a+1];
            Arrays.fill(dp,-1);
            dp[0] = 0;
            for(int i=0;i<m;i++){
                for(int j=u[i].weight;j<=a;j++){
                    if(dp[j-u[i].weight] != -1){
                        if(dp[j] == -1) dp[j] = dp[j-u[i].weight]+u[i].val;
                        else dp[j] = Math.min(dp[j-u[i].weight]+u[i].val,dp[j]);
                    }
                }
            }
            if(dp[a] == -1) System.out.println("This is impossible.");
            else System.out.println("The minimum amount of money in the piggy-bank is " + dp[a]+".");
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值