01背包问题(DFS解法)
生活随笔
收集整理的這篇文章主要介紹了
01背包问题(DFS解法)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
有5個物體,每個物品只有一個,其重量分別是為2,2,6,5,4,價值分別為6,3,5,4,6,背包的載重量為10,求裝入背包的物體及總質量。
計算結果:15
package com.lanQiaoFor6;import java.util.ArrayList; import java.util.TreeSet;public class JAVA_6 {static TreeSet<Person> treeSet;static ArrayList<Person> arrayList;static Person[] persons;static Person[] realPersons;static int asnprice = 0;static int realAsnprice = 0;static int weightSum = 10;static int count = 0;static int size = 0;public static void main(String[] args) {persons = new Person[5];treeSet = new TreeSet<>();treeSet.add(new Person(2, 6));treeSet.add(new Person(2, 3));treeSet.add(new Person(6, 5));treeSet.add(new Person(5, 4));treeSet.add(new Person(4, 6));arrayList = new ArrayList<>();arrayList.addAll(treeSet);for (int i = 0; i < 5; i++) {Person person = arrayList.get(i);if (person.weight > weightSum) {continue;}person.flag = true;count += person.weight;asnprice += person.value;persons[size++] = person;if (i == 4) {if (person.value > realAsnprice) {realAsnprice = (int) person.value;}continue;}dfs(arrayList.get(i + 1), count);person.flag = false;count -= person.weight;asnprice -= person.value;persons[size--] = null;}System.out.println(realAsnprice);}public static void dfs(Person person, int count) {// TODO Auto-generated method stub// 出口if (weightSum < count + person.weight) {if (asnprice > realAsnprice) {realAsnprice = asnprice;realPersons = persons.clone();for(int i=0;i<size;i++) {System.out.print (persons[i].value+" ");}System.out.println();}}// 遍歷for (int i = 0; i < 4; i++) {if (weightSum > count + person.weight && person.flag != true) {person.flag = true;count += person.weight;asnprice += person.value;persons[size++] = person;int index = arrayList.indexOf(person);if (index != arrayList.size()) {dfs(arrayList.get(index + 1), count);person.flag = false;count -= person.weight;asnprice -= person.value;persons[size--] = null;}}}} }class Person implements Comparable<Person> {public double value;public double weight;public boolean flag = false;public Person(double weight, double value) {// TODO Auto-generated constructor stubthis.value = value;this.weight = weight;}public int compareTo(Person o) {// TODO Auto-generated method stubif ((this.value / this.weight) > (o.value / o.weight)) {return -1;} else {return 1;}}}總結
以上是生活随笔為你收集整理的01背包问题(DFS解法)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 本地yum仓库以及网络版yum的私有仓库
- 下一篇: Form表单中method=post/g