Advertisement
Guest User

Untitled

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