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
| package com.bag;
public class Main { static int totalweight= 150; static int N= 5; static int values[] = {60, 20, 10, 60, 100}; static int weights[] = {20, 30, 50, 60, 80}; public static void main(String[] args) { System.out.println(bagProblem(N-1,totalweight)); bag01(); } public static int bagProblem(int i, int j) { int r = 0; if(i==-1){ return 0; } if (j>=weights[i]){ int r1 = bagProblem(i-1,j-weights[i]) + values[i]; int r2 = bagProblem(i-1,j); r = Math.max(r1,r2); } return r; } public static void bag01(){ int f[] = new int[totalweight+1]; for (int f1:f){ f1 = 0; } for (int i=0;i<N;i++){ int w = weights[i]; int v = values[i]; for (int j= totalweight;j>=w;j--){ f[j] = Math.max(f[j],f[j-w]+v); } } System.out.println(f[totalweight]); } }
|