Advertisement
Guest User

Untitled

a guest
Jan 8th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 2.00 KB | None | 0 0
  1. open PMap;;
  2. open List;;
  3.  
  4. exception Cykliczne
  5.  
  6. (* tworzy graf z danych wejściowych, z założeniem że dany wierzcholek
  7. może występować wiele razy w liscie (np [(1,[2]); (1,[3]);...] *)
  8.  
  9. let make_graph lt =
  10.     match lt with
  11.     | [] -> (PMap.empty, PMap.empty)
  12.     (*zwracamy pusty graf*)
  13.     | lt ->
  14.       let graph = PMap.empty and colors = PMap.empty in
  15.       let helper (graph, colors) (el, rel) =
  16.         if PMap.mem el graph then (*przypadek, że wierzcholek już występuje *)
  17.           let old = PMap.find el graph in
  18.           let graph = PMap.remove el graph in
  19.           let graph = PMap.add el (old @ rel) graph in
  20.           (graph, colors)
  21.         else
  22.           let graph = PMap.add el rel graph
  23.           and colors = PMap.add el 0 colors in
  24.           (graph, colors)
  25.       in List.fold_left helper (graph, colors) lt
  26.  
  27.  
  28. (*sortowanie topologiczne wykorzystujące DFS *)
  29.  
  30. let top_sort (graph,colors) =
  31.   let rec dfs el (graph, colors) res =
  32.     if not (PMap.mem el colors) then
  33.       let colors = PMap.add el 2 colors in
  34.       ((graph, colors), el::res)
  35.       (* wierzcholek nie jest w grafie colors wiec nie wychodza z niego zadne
  36.       krawedzie i ustawiamy jako odwiedzony*)
  37.     else
  38.       let col = PMap.find el colors in
  39.       if col = 1 then raise Cykliczne (*wierzcołek z którego wyszliśmy *)
  40.       else if col = 2 then ((graph, colors), res) (* wierzchołek w którym byliśmy *)
  41.       else  (*wierzcholek nieodwiedzony*)
  42.         let colors = PMap.add el 1 colors in
  43.         let helper ((graph,colors), res) el =
  44.         dfs el (graph,colors) res in
  45.         let ((graph,colors), res) = List.fold_left helper ((graph,colors), res) (PMap.find el graph) in
  46.         let colors = PMap.add el 2 colors in
  47.         ((graph,colors), el::res)
  48.   in
  49.   let ((graph,colors), res) = PMap.foldi (fun el _ ((graph,colors), res) -> dfs el (graph,colors) res) graph ((graph, colors), [])  in
  50.   res
  51.  
  52. let topol lt =
  53.   let (graph,colors) = make_graph lt in
  54.   top_sort (graph, colors)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement