栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java模板系列之背包dp-HDU1114

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
                u[i] = new item();
            }
            for(int i=0;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
                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]+".");
        }
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/888563.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号