1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public class _01KnapsackProblem { public int[] weight; public int[] value; public int[] take;
int curWeight = 0; int curValue = 0;
int bestValue = 0; int[] bestChoice; int count;
int maxWeight = 0;
public void init(int[] weight, int[] value, int maxWeight) { if (weight == null || weight.length == 0 || value == null || value.length == 0 || weight.length != value.length || maxWeight <= 0) { System.out.println("输入数据有错!"); return; } this.value = value; this.weight = weight; this.maxWeight = maxWeight; count = value.length; take = new int[count]; bestChoice = new int[count]; }
public int[] maxValue(int x) { if (x > count - 1) { if (curValue > bestValue) { bestValue = curValue; for (int i = 0; i < take.length; i++) { bestChoice[i] = take[i]; } } } else { for (int i = 0; i < 2; i++) { take[x] = i; if (i == 0) { maxValue(x + 1); } else { if (curWeight + weight[x] <= maxWeight) { curWeight += weight[x]; curValue += value[x]; maxValue(x + 1); curWeight -= weight[x]; curValue -= value[x]; } } } } return bestChoice; } public static void main(String[] args) { _01KnapsackProblem bt=new _01KnapsackProblem(); bt.init(new int[]{11,7,9,12,3,10},new int[]{10,5,7,9,2,12},25); int[] result = bt.maxValue(0); System.out.print("输出:\n"+"选择的物品是:"); for (int i = 0; i <=bt.bestChoice.length-1 ; i++) { if (bt.bestChoice[i] == 1) { System.out.print(i+1+","); } } System.out.println("\n此时价值最大,即"+bt.bestValue); } }
|