Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. open Graph.Pack.Digraph
  2.  
  3. (* function checks if element exists already in stack *)
  4. let exists stack element =
  5.   try
  6.     Stack.iter (fun x-> if x = element then raise Exit;) stack;
  7.     false;
  8.   with
  9.       Exit -> true
  10.     | _ -> false
  11.  
  12. type composante =
  13.     None
  14.   | Some of int
  15. ;;
  16.  
  17. let string_of_composante x = match x with
  18.     None -> "none"
  19.   | Some(l) -> string_of_int l
  20. ;;
  21.  
  22.  
  23. (* tarjan function *)
  24. let tarjan g =
  25.   let nb_of_vertex = nb_vertex g in
  26.   let cfc = Array.create nb_of_vertex None in
  27.   let nv = Array.create nb_of_vertex true in
  28.   let ind = Array.create nb_of_vertex 0 in
  29.   let ind_rec = Array.create nb_of_vertex 0 in
  30.   let icfc = ref 1 in
  31.   let i = ref 1 in
  32.   let p = Stack.create () in
  33.  
  34.   let rec descente s_ =
  35.     let s = V.label s_ in
  36.     Stack.push s p ;    (* we store numbers only in stack *)
  37.     nv.(s) <- false ;   (* NV[s] <- faux *)
  38.     ind.(s) <- !i ;     (* ind[s] <- i *)
  39.     ind_rec.(s) <- !i ; (* ind_rac[s] <- i *)
  40.     i := !i + 1 ;       (* i <- i +1 *)
  41.    
  42.   (* for all succeseurs *)
  43.     iter_succ
  44.       (fun x_ ->
  45.       let x=(V.label x_) in
  46.       if nv.(x) then
  47.     begin
  48.  
  49.       descente x_;
  50.       ind_rec.(s) <- (min ind_rec.(s) ind_rec.(x));
  51.     end
  52.       else
  53.    
  54.       if (exists p x) then
  55.     ind_rec.(s) <- (min ind_rec.(s) ind.(x) );
  56. )
  57.  
  58.  
  59.       (* the graph - 2nd argument *)
  60.       g
  61.  
  62.       (* the vertex - 3rd argument *)
  63.       s_;
  64.    
  65.     if ind_rec.(s) = ind.(s) then
  66.       let z = ref (Stack.pop p) in
  67.       cfc.(!z) <- Some(!icfc);
  68.       while !z != s do
  69.     z := Stack.pop p;
  70.     cfc.(!z) <- Some(!icfc);
  71.       done;
  72.       icfc := !icfc+1
  73.       ;
  74.   in
  75.    
  76.   (* for all vertex if nv[x] then (descente x g) *)
  77.   iter_vertex
  78.     (fun x_ ->
  79.       ( let x=(V.label x_) in
  80.     if nv.(x) then
  81.       descente x_;
  82.       )
  83.     )
  84.     g;
  85.  
  86.   (* return cfc *)
  87.   cfc
  88. ;;
  89.  
  90. let g = Rand.graph ~v:8 ~e:12 ();;
  91. let k = tarjan g;;
  92.  
  93. let i = ref 0 in
  94. while !i < 8 do
  95.   print_endline ( (string_of_int !i)^ " " ^(string_of_composante k.(!i)));
  96.   i:= !i+1;
  97. done;
  98. display_with_gv g;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement