Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. package plecakowy;
  2.  
  3. /*
  4. Rozwiazanie decyzyjnego problemu plecakowego
  5. Metoda dzieli i zwycierzaj
  6. */
  7.  
  8.  
  9. public class PlecakDZ
  10. {
  11.  
  12. final static int N = 6; // liczba przedmiotów
  13. final static int MAX_V = 10; // objetość plecaka
  14.  
  15. final static int[] V = {2,6,3,3,1,2}; // objetości przedmiotów
  16. final static int[] W = {4,6,5,10,2,7}; // wartości przedmiotów
  17.  
  18. static int P(int i, int v)
  19. {
  20. int w1; // wartość, gdy nie bierzemy i-tego przedmiotu
  21. int w2; // wartość, gdy bierzemy i-ty przedmiot
  22. if (i == 0 && v < V[0])
  23. {
  24. return 0;
  25. }
  26. if (i == 0 && v >= V[0])
  27. {
  28. return W[0];
  29. }
  30. w1 = P(i - 1, v);
  31. if (i > 0 && v < V[i])
  32. {
  33. return w1;
  34. }
  35. w2 = W[i] + P(i - 1, v - V[i]);
  36. if (w2 > w1) // gdy i > 0 && v >= V[i]
  37. {
  38. return w2;
  39. }
  40. else
  41. {
  42. return w1;
  43. }
  44. }
  45.  
  46. public static void main(String[] args)
  47. {
  48. System.out.println("Wartosc przedmiotow: " + P(N - 1, MAX_V));
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement