问题描述:
设U = {u1,u2,u3,......ui}(一共有amount数量的物品)是一组准备放入背包中的物品.设背包的容量为size.
定义每个物品都具有两个属性weight和value.
我们要解决的问题就是计算在所选取的物品总重量不超过背包容量size的前提下使所选的物品总价值最大.
一句话,让你的有限背包,装上最终总价值最高的物品。
- import java.util.Arrays;
-
-
-
-
-
-
- public class T {
-
-
-
-
-
-
- public static void knapsack(int[] value, int[] weight, int capicity, int[][] m) {
-
- int n = value.length - 1;
-
- int jMax = Math.min(weight[n] - 1, capicity);
-
- for (int j = 0; j <= jMax; j++)
- m[n][j] = 0;
- showArray(m);
-
-
- for (int j = weight[n]; j <= capicity; j++)
- m[n][j] = value[n];
- showArray(m);
-
- for (int i = n - 1; i >= 1; i--) {
- jMax = Math.min(weight[i] - 1, capicity);
- System.out.println(jMax);
- for (int k = 0; k <= jMax; k++)
- m[i][k] = m[i + 1][k];
- showArray(m);
- for (int h = weight[i]; h <= capicity; h++) {
- System.out.println(m[i+1][h]+" / "+ m[i + 1][h - weight[i]]+" + " +value[i]+"("+h+","+weight[i]+","+value[i]+")");
- m[i][h] = Math.max(m[i + 1][h], m[i + 1][h - weight[i]] + value[i]);
- }
- showArray(m);
- }
- m[0][capicity] = m[1][capicity];
- if (capicity >= weight[0])
- m[0][capicity] = Math.max(m[0][capicity], m[1][capicity - weight[0]] + value[0]);
- System.out.println("bestw =" + m[0][capicity]);
- }
-
- public static void showArray(int[][] m) {
- for (int[] a : m) {
- System.out.println(Arrays.toString(a));
- }
- System.out.println("-------------------------------------------");
- }
-
- public static void traceback(int[][] m, int[] w, int c, int[] x) {
- int n = w.length - 1;
- for (int i = 0; i < n; i++)
- if (m[i][c] == m[i + 1][c])
- x[i] = 0;
- else {
- x[i] = 1;
- c -= w[i];
- }
- x[n] = (m[n][c] > 0) ? 1 : 0;
- }
-
- public static void main(String[] args) {
-
- int[] ww = { 8,5,4,3 };
- int[] vv = { 10,7,5,4 };
- int[][] mm = new int[4][13];
- knapsack(vv, ww, 12, mm);
- int[] xx = new int[ww.length];
- traceback(mm, ww, 12, xx);
- for (int i = 0; i < xx.length; i++)
- System.out.println(xx[i]);
- }
- }
阅读(561) | 评论(1) | 转发(0) |