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
| package com.demo;
public class DynamicPlanning { public static void main(String[] args) { int[] w={1,4,3}; int[] val={1500,3000,2000}; int m=5; int n=val.length; int [][] v = new int[n+1][m+1];
int [][] path = new int[n+1][m+1]; for (int i = 1;i<v.length;i++){ for (int j = 1; j <v[0].length; j++) { if (w[i-1]>j){ v[i][j] = v[i-1][j]; }else {
if (v[i-1][j]<val[i-1]+v[i-1][j-w[i-1]]){ v[i][j] = val[i-1]+v[i-1][j-w[i-1]]; path[i][j] = 1; }else { v[i][j]=v[i-1][j];
} } } }
for (int i=0;i<v.length;i++){ for (int j=0;j<v[i].length;j++){ System.out.print(v[i][j]+" "); } System.out.println();
}
int i = path.length-1; int j = path[0].length-1; while (i>0&& j >0){ if (path[i][j] == 1){ System.out.printf("第%d个物品放入背包",i); j -= w[i-1]; } i--; }
} }
|