背包动态规划输入

Posted

技术标签:

【中文标题】背包动态规划输入【英文标题】:Knapsack Dynamic Programming Inputs 【发布时间】:2014-09-06 22:48:12 【问题描述】:

我想知道对于背包问题是否有任何具体的问题和答案,我可以输入和修改此代码以确保我正确地完成了它?我正在尝试进入动态编程并从这个问题开始,但无法知道它是否真的在没有输入的情况下工作 - 我在一些电源点上发现了一些案例,虽然我的代码输出正确的信息,但它们很漂亮基本和简单的案例,所以我想确保这适用于更多的输入。

这是我的代码:

import java.util.ArrayList;

public class Knapsack 

    private int numThings = 0;

    public static void main(String[] args) 

        (new Knapsack()).run();
    

    public void run() 

        ArrayList<Thing> thingList = new ArrayList<Thing>();
        thingList.add(new Thing(60, 2));
        thingList.add(new Thing(75, 3));
        thingList.add(new Thing(90, 4));


        int maxWeight = 5;


        int[] vals = new int[maxWeight + 1];
        vals[2] = 60;

        Thing nullThing = new Thing(0,0);
        Thing max;
        int maxSet = 0;

        for (int i = 1; i < vals.length; i++) // lets go through weights leading up to our maximal weight

            System.out.println(i);
            max = nullThing;
            for (Thing x : thingList) 

                if ((i-x.getWeight() >= 0) && (x.getValue() + vals[i-x.getWeight()] > max.getValue() + vals[i-max.getWeight()])) 

                    max = x;
                    maxSet = 1;//here, we compare possibilities of adding items by subtracting weights from  our current index and seeing which ones produce the highest values
                
            

            if (maxSet == 1) 

                vals[i] = max.getValue() + vals[i-max.getWeight()];
                System.out.println(max.info() );//if we find something that sets a highest value, we cache that info into the array for future use
            
        

        System.out.println(vals[maxWeight]);


    


    private class Thing 

        private int value, weight;

        public Thing(int v, int w) 

            value = v;
            weight = w;

        

        public int getValue() 

            return value;
        

        public int getWeight() 

            return weight;
        

        public String info() 

            return "I have a weight of "+weight+" and a value of "+ value;
        
    

【问题讨论】:

【参考方案1】:

谷歌搜索“背包问题数据集”会产生大量答案。 Here is first.

【讨论】:

以上是关于背包动态规划输入的主要内容,如果未能解决你的问题,请参考以下文章

动态规划算法实现部分——0/1背包问题

0,1背包问题(动态规划)

动态规划--01背包问题

动态规划(01背包问题的拓展)

动态规划(01背包问题的拓展)

动态规划完全背包问题