sweet1cris

Untitled

Jan 11th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1. public class KnapSackMaxValueUnbound {
  2.     public static void main(String[] args) {
  3.         KnapSackMaxValueUnbound ku = new KnapSackMaxValueUnbound();
  4.         int[] w = { 6, 3, 4, 2 };
  5.         int[] v = { 30, 14, 16, 9 };
  6.         int capacity = 10;
  7.         ku.unboundKnapsack(w, v, capacity);
  8.     }
  9.  
  10.     public List<Integer> unboundKnapsack(int[] w, int[] v, int capacity) {
  11.         List<Integer> result = new ArrayList<>();
  12.         if (capacity < 0 || w == null || v == null || w.length != v.length) {
  13.             return result;
  14.         }
  15.         int[] k = new int[capacity + 1];
  16.         int[] s = new int[capacity + 1];
  17.         int[] prev = new int[capacity + 1];
  18.         k[0] = 0;
  19.         for (int i = 0; i < w.length; i++) {
  20.             s[i] = -1;
  21.             prev[i] = -1;
  22.         }
  23.  
  24.         for (int b = 1; b < k.length; b++) {
  25.             for (int i = 0; i < w.length; i++) {
  26.                 if (w[i] <= b && k[b] < v[i] + k[b - w[i]]) {
  27.                     k[b] = v[i] + k[b - w[i]];
  28.                     s[b] = i;
  29.                     prev[b] = b - w[i];
  30.                 }
  31.             }
  32.         }
  33.         System.out.println(Arrays.toString(k));
  34.         System.out.println(Arrays.toString(s));
  35.         System.out.println(Arrays.toString(prev));
  36.         // s[b] + 1
  37.         int n = k.length - 1;
  38.         while (s[n] != -1) {
  39.             result.add(s[n] + 1);
  40.             n = prev[n];
  41.         }
  42.         Collections.reverse(result);
  43.         System.out.println(result);
  44.         return result;
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment