Advertisement
asiffff

KnapSack01

Dec 3rd, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package javaapplication37;
  7.  
  8. /**
  9. *
  10. * @author Asif
  11. */
  12. public class JavaApplication37 {
  13.  
  14. /**
  15. * @param args the command line arguments
  16. */
  17.  
  18. static int max(int a,int b) {
  19. if(a>b) {
  20. return a;
  21. } else {
  22. return b;
  23. }
  24. }
  25. static void kanp(int w[],int p[],int k) {
  26. int kk[][] = new int[w.length][k+1];
  27. Item ar[][] = new Item[w.length][k+1];
  28. for(int i=1;i<p.length;i++) {
  29. for(int j=1;j<=k;j++) {
  30. if(w[i]<=j) {
  31. //System.out.println("jj");
  32. int x = p[i]+ kk[i-1][j-w[i]];
  33. int y = kk[i-1][j];
  34. int max = max(x,y);
  35. kk[i][j]= max;
  36. if(max ==x) {
  37. ar[i][j] = new Item(i-1, j-w[i], "leftup");
  38. }else {
  39. ar[i][j] = new Item(i-1, j, "left");
  40. }
  41. } else {
  42. kk[i][j] = kk[i-1][j];
  43. ar[i][j] = new Item(i-1, j, "left");
  44. }
  45. }
  46. // System.out.println("");
  47. }
  48. for(int i=0;i<p.length;i++) {
  49. for(int j=0;j<=k;j++) {
  50. System.out.print(kk[i][j]+" ");
  51. }
  52. System.out.println("");
  53. }
  54.  
  55. int i = w.length-1;
  56. int j = k;
  57. Item x = ar[i][j];
  58. while(x != null) {
  59. if(x.getX().equals("leftup")) {
  60. System.out.println(i);
  61. i = x.getI();
  62. j = x.getJ();
  63. x = ar[i][j];
  64. }else {
  65. i = x.getI();
  66. j = x.getJ();
  67. x = ar[i][j];
  68.  
  69. }
  70. }
  71.  
  72. }
  73. public static void main(String[] args) {
  74. int w[] = {0,2,1,3,2};
  75. int p[] = {0,12,10,20,15};
  76. int k = 5;
  77. kanp(w, p, k);
  78.  
  79. // System.out.println(w.length);
  80.  
  81. }
  82.  
  83. }
  84.  
  85. class Item {
  86. int i,j;
  87. String x;
  88.  
  89. public Item(int i, int j, String x) {
  90. this.i = i;
  91. this.j = j;
  92. this.x = x;
  93. }
  94.  
  95. public int getI() {
  96. return i;
  97. }
  98.  
  99. public int getJ() {
  100. return j;
  101. }
  102.  
  103. public String getX() {
  104. return x;
  105. }
  106.  
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement