JALLAT_kurska.ml 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. type 'a poids = Poids of 'a | Infini;;
  2. let g = [|
  3. [|Infini; Poids(9); Infini; Poids(5); Infini; Infini; Infini|];
  4. [|Poids(7); Infini; Poids(8); Poids(9); Poids(7); Infini; Infini|];
  5. [|Infini; Poids(8); Infini; Infini; Poids(5); Infini; Infini|];
  6. [|Poids(5); Poids(9); Infini; Infini; Poids(15); Poids(6); Infini|];
  7. [|Infini; Poids(7); Poids(5); Poids(15); Infini; Poids(8); Poids(9)|];
  8. [|Infini; Infini; Infini; Poids(6); Poids(8); Infini; Poids(11)|];
  9. [|Infini; Infini; Infini; Infini; Poids(9); Poids(11); Infini|];
  10. |];;
  11. let rec insere i x l =
  12. match l with
  13. | [] -> [i]
  14. | t::q -> if x > t then i :: l else t :: (insere i x q)
  15. ;;
  16. let liste_triee_arrete w =
  17. let l = ref [] and n = Array.length w.(0) in
  18. for i = 0 to n - 2 do
  19. for j = i + 1 to (n - 1) do
  20. if w.(i).(j) <> Infini then
  21. match w.(i).(j) with
  22. | Poids(p) -> l := insere (i, j) p !l
  23. | Infini -> ()
  24. else ()
  25. done;
  26. done;
  27. !l
  28. ;;
  29. let n = Array.length g.(0);;
  30. let composantes = Array.make n 0;;
  31. let aretes = liste_triee_arrete g;;
  32. let aux i j t =
  33. let ci = composantes.(i) and cj = composantes.(j) in
  34. match ci = cj with
  35. | true -> ()
  36. | false ->
  37. t := (i, j) :: !t;
  38. for k = 0 to n - 1 do
  39. if composantes.(k) = cj then composantes.(k) <- ci;
  40. done
  41. ;;
  42. let rec kaux1 w aretes t =
  43. match aretes with
  44. | [] -> t
  45. | a::aq -> let (i, j) = a in aux i j t; kaux1 w aq t
  46. ;;
  47. let kruskal1 w =
  48. let aretes = liste_triee_arrete w in
  49. let t = ref [] in
  50. kaux1 w aretes t;
  51. !t
  52. ;;
  53. (* Seconde partie *)
  54. (*une fonction chemin w u v, qui renvoie true s'il existe un chemin entre u et v*)
  55. let chemin w u v =
  56. let n = Array.length w in
  57. let rec aux i =
  58. match i = n with
  59. | true -> false
  60. | false ->
  61. match w.(u).(i) with
  62. | Infini -> aux (i+1)
  63. | Poids(p) ->
  64. match w.(i).(v) with
  65. | Infini -> aux (i+1)
  66. | Poids(q) -> true
  67. in aux 0
  68. ;;
  69. let kruskal2 w =
  70. let n = Array.length w in
  71. let rec aux i =
  72. match i = n with
  73. | true -> []
  74. | false ->
  75. match w.(i) with
  76. | [] -> aux (i+1)
  77. | t::q ->
  78. match chemin w t i with
  79. | true -> (t, i) :: (aux (i+1))
  80. | false -> aux (i+1)
  81. in aux 0
  82. ;;