shakaran

Untitled

Nov 30th, 2012
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. //Problema clásico de selección de actividades ponderadas
  2.  
  3. /* Ejemplo datos de entrada
  4. Actividad:   0 1 2 3 4 5
  5. -------------------------
  6. T inicio     0 1 4 2 6 7
  7. T fin        3 5 6 7 8 9
  8. Beneficios   2 4 4 7 2 2
  9.  
  10. i    : 0  1  2  3  4  5
  11. ------------------------
  12. p(i) :-1 -1  0 -1  2  3
  13.  
  14. */
  15. // p[] es un array del mismo tamaño que beneficios pero que indica
  16. // la actividad compatible mas cercana con tiempo de fin menor.
  17. private static int sel(int i)
  18. {
  19.         if (i==-1)
  20.                 return 0;
  21.         else
  22.                 return Math.max( sel(i-1) , beneficios[i]+sel(p[i]) );
  23. }
  24.  
  25. // Primera aproximación incorrecta en iterativo.
  26. private static int sel(int i)
  27. {
  28.     int a, b = 0, resa, resb = 0;
  29.  
  30.     if (i == -1)
  31.     {
  32.         return 0;
  33.     }
  34.     else
  35.     {
  36.         // sel(i-1)
  37.         for (int a = i - 1; a >= 0; a--)
  38.         {
  39.             resa = Math.max(resa, beneficios[i] + p[a]);
  40.         }
  41.  
  42.         // sel(p[i])
  43.         for (int b = i; b >= 0; b--)
  44.         {
  45.             resb = Math.max(resb, beneficios[i] + p[b]);
  46.         }
  47.        
  48.         return Math.max(resa , beneficios[i] + resb)
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment