Advertisement
juaniisuar

Kruskal ML

Sep 21st, 2015
2,277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (* utilidades *)
  2.  
  3. fun create [] = []
  4.         | create (x::y) = (x,x)::(create y);
  5.  
  6. fun pertenece a [] = false
  7.         | pertenece a (b::c) = if a = b then true else pertenece a c;
  8.      
  9. exception nopepuntoexe;
  10.  
  11. (* implementacion del union find *)
  12.  
  13. fun findAux x [] z = raise nopepuntoexe
  14.         | findAux x ((a,b)::c) z = if x = a andalso a = b then b else if x = a then findAux b z z else findAux x c z;
  15.        
  16. fun find x a = findAux x a a;
  17.  
  18. fun unionAux x y [] rest k = raise nopepuntoexe
  19.         | unionAux x y ((a,b)::c) rest k = if k = a then rest@((a,x)::c) else unionAux x y c (rest@[(a,b)]) k;
  20.  
  21. fun union x y a = unionAux x y a [] (find y a);
  22.  
  23. (* funciones para ordenar *)
  24.  
  25. fun menores (a,b,x) [] = []
  26.         | menores (a,b,x) ((c,d,y)::ys) = if y <= x then (c,d,y)::menores (a,b,x) ys else menores (a,b,x) ys;
  27.  
  28. fun mayores (a,b,x) [] = []
  29.         | mayores (a,b,x) ((c,d,y)::ys) = if y > x then (c,d,y)::mayores (a,b,x) ys else mayores (a,b,x) ys;
  30.  
  31. fun qs [] = []
  32.         | qs ((a,b,x)::xs) = qs (menores (a,b,x) xs) @ [(a,b,x)] @ qs (mayores (a,b,x) xs);
  33.  
  34. (* funciones para generar la lista de nodos *)
  35.  
  36. fun eliminar [] k  = []
  37.         | eliminar (a::b) k = if k = a then eliminar b k else a::(eliminar b k);
  38.  
  39. fun listaNodosAux [] = []
  40.         | listaNodosAux (a::b) = a::(listaNodosAux (eliminar b a));
  41.  
  42. fun clash [] = []
  43.         | clash ((a,b,c)::d) = [a,b]@(clash d);
  44.  
  45. fun listaNodos g = listaNodosAux (clash g);
  46.  
  47. (* kruskal *)
  48.  
  49. fun kruskalAux [] UFlist MSP = MSP
  50.         | kruskalAux ((a,b,c)::d) UFlist MSP = if (find a UFlist) <> (find b UFlist) (* no hay ciclo *)
  51.                                                 then kruskalAux d (union a b UFlist) ((a,b,c)::MSP) (* se agrega la arista al MSP *)
  52.                                                 else kruskalAux d UFlist MSP; (* se ignora *)
  53.  
  54. fun kruskal g = kruskalAux (qs g) (create (listaNodos g)) []; (* le pasas la lista ordenada, la lista para el union-find y una lista vacía para guardar el msp *)
  55.  
  56. (* tests *)
  57.  
  58. kruskal [(1,2,3), (1,3,4), (2,3,99), (3,4,5), (1,4,50), (4,5,1)];
  59. kruskal [(1,2,1), (1,3,1), (2,4,2), (2,1,0), (2,3,2), (2,4,0), (3,2,1), (4,3,1), (4,1,0)];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement