Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
53
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. (* tarjan function *)
  13.  
  14. let tarjan g =
  15.   let nb_of_vertex = nb_vertex g in
  16.   let cfc = Array.create nb_of_vertex 0 in
  17.   let nv = Array.create nb_of_vertex true in
  18.   let ind = Array.create nb_of_vertex 0 in
  19.   let ind_rec = Array.create nb_of_vertex 0 in
  20.   let icfc = ref 1 in
  21.   let i = ref 1 in
  22.   let p = Stack.create () in
  23.  
  24.   let rec descente s_ =
  25.     let s = V.label s_ in
  26.     Stack.push s p ; (* we store numbers only in stack *)
  27.     nv.(s) <- false ;
  28.     ind.(s) <- !i ;
  29.     ind_rec.(s) <- !i ;
  30.     i := !i + 1 ;
  31.    
  32.   (* for all succeseurs *)
  33.     iter_succ (fun x_ ->
  34.       (
  35.     let x=(V.label x_) in
  36.     if nv.(x) then
  37.       (
  38.         descente x_;
  39.         ind_rec.(s) <- (min ind_rec.(s) ind_rec.(x));
  40.       )
  41.     else
  42.       if (exists p x) then
  43.         ind_rec.(s) <- (min ind_rec.(s) ind.(x) );
  44.       )) g s_;
  45.    
  46.     if ind_rec.(s) = ind.(s) then
  47.       let z = ref (Stack.pop p) in
  48.       while !z != s do
  49.     cfc.(!z) <- !icfc;
  50.     z := Stack.pop p;
  51.       done;
  52.       icfc := !icfc+1
  53.   in
  54.  
  55.  
  56.   (* for all vertex if nv[x] then (descente x g) *)
  57.   iter_vertex
  58.     (fun x_ ->
  59.       ( let x=(V.label x_) in
  60.     if nv.(x) then (descente x_ g);
  61.       )
  62.     )
  63.     g;
  64.  
  65.   (* return cfc *)
  66.   cfc
  67. ;;
  68.  
  69. let g = Rand.graph ~v:10 ~e:20 ();;
  70. let _ = tarjan g;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement