Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. package knapsack;
  2.  
  3. import java.util.*;
  4.  
  5.  
  6.  
  7. class Node {
  8. int level; // nodes level in the tree
  9. int weight; // nodes weight
  10. int profit; // nodes profit
  11.  
  12. public Node() { // set all default values to 0
  13. level = 0;
  14. weight = 0;
  15. profit = 0;
  16. }
  17. public Node(int level, int weight, int profit) { // method to call Node class
  18. this.level = level;
  19. this.weight = weight;
  20. this.profit = profit;
  21. }
  22.  
  23. }
  24.  
  25. public class knapsack {
  26. public static int[] w = {2, 5, 10, 5}; // array of weights
  27. public static int[] p = {40, 30, 50, 10}; // array of profits
  28. public static int W = 16; // sums of weights cannot exceed W
  29. public static int n = 4; // number of items
  30.  
  31. public static int knapsack2(int n, int[] p, int[] w, int W) {
  32. Queue<Node> Q = new LinkedList<>(); //
  33. Node v = new Node(); // declare two node objects v and u
  34. Node u = new Node();
  35. int maxProfit = 0;
  36. Q.add(v); // enqueue Node v so that loop will run
  37. v.level = -1;
  38. while(!Q.isEmpty()) {
  39. v = Q.remove(); // dequeue node v
  40. u = new Node();
  41. if (v.level == -1)
  42. u.level = 0;
  43. else
  44. u.level = v.level + 1;
  45. u.weight = v.weight + w[u.level];
  46. u.profit = v.profit + p[u.level];
  47. if(u.weight <= W && u.profit > maxProfit) // next item
  48. maxProfit = u.profit;
  49. if(bound(u, n, p, w, W) > maxProfit)
  50. Q.add(u);
  51. u = new Node();
  52. u.level = v.level + 1;
  53. u.weight = v.weight; // Set u to the child of v that does not include the next item
  54. u.profit = v.profit;
  55. if(bound(u, n, p, w, W) > maxProfit)
  56. Q.add(u);
  57. }
  58. return maxProfit;
  59. }
  60.  
  61. public static double bound(Node u, int n, int[] p, int[] w, int W) {
  62. if (u.weight >= W)
  63. return 0;
  64. int j = u.level + 1, totweight = u.weight;
  65. double result = u.profit;
  66. while(j <= n && (totweight + w[j]) <= W) {
  67. totweight += w[j]; // grab as many items as possible
  68. result += p[j];
  69. j++;
  70. }
  71. int k = j;
  72. if (k <= n) // grab function of kth item
  73. result += (W - totweight) * ((double)p[k]/w[k]);
  74. return result;
  75. }
  76.  
  77. public static void main(String[] args) {
  78.  
  79. System.out.println("Max Profit: " + knapsack2(n-1, p, w, W));
  80.  
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement