Advertisement
Guest User

Untitled

a guest
Oct 27th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Knapsack {
  4.  
  5. private int n,W; //number of items and maximo capacity
  6. private int w[],v[]; //pesos and values of items
  7. private int V[][]; //table to store results of sub-problems
  8.  
  9. /**
  10. * Takes necessary inputs and initializes for solving
  11. */
  12. private void initialize(){
  13. Scanner sc = new Scanner(System.in);
  14. System.out.print("Enter number of items : ");
  15. n = sc.nextInt(); //number of items
  16. System.out.print("Enter W of knapsack : ");
  17. W = sc.nextInt(); //capacity of knapsack
  18. w = new int[n];
  19. v = new int[n];
  20. System.out.println("Enter ws and vs of items : ");
  21. for(int i = 0; i < n; i++){
  22. w[i] = sc.nextInt(); //peso of item
  23. v[i] = sc.nextInt(); //beneficio of item
  24. }
  25. V = new int[n+1][W+1]; //initializing the table to hold results
  26. for(int i = 0; i <= W; i++) V[0][i] = 0;
  27. }
  28.  
  29. /**
  30. * Computes the result
  31. */
  32. public void knapsack(){
  33. //table for backtracking to get the items chosen
  34. int x[][] = new int[n+1][W+1];
  35. //filling tables
  36. for(int i = 1; i <= n; i++)
  37. for(int j = 0; j <= W; j++)
  38. if((w[i-1] <= j) && (v[i-1]+V[i-1][j-w[i-1]] > V[i-1][j])){
  39. V[i][j] = v[i-1] + V[i-1][j-w[i-1]];
  40. x[i][j] = 1;
  41. }
  42. else{
  43. V[i][j] = V[i-1][j];
  44. x[i][j] = 0;
  45. }
  46. //backtracking
  47. System.out.printf("Items escogidos\n%5s%7s%7s\n", "Item","peso","beneficio");
  48. int K = W;
  49. for(int i = n; i >= 1; i--)
  50. if(x[i][K] == 1){
  51. System.out.printf("%5d%7d%7d\n",i,w[i-1],v[i-1]);
  52. K -= w[i-1];
  53. }
  54. System.out.println("maximo beneficio : "+V[n][W]);
  55. }
  56.  
  57. public static void main(String[] args) {
  58. Knapsack obj = new Knapsack();
  59. obj.initialize();
  60. obj.knapsack();
  61. }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement