Advertisement
iStrzalka

Path

Jan 19th, 2020
1,910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.66 KB | None | 0 0
  1.  
  2. let path (g : int array array) =
  3.     let n = Array.length g in
  4.     let ans_arr = Array.make n 1
  5.     and answer = ref 0 in
  6.         for i = 0 to (n - 1) do
  7.             let cur = g.(i) in
  8.             let cur_size = Array.length cur in
  9.             answer := max !answer (ans_arr.(i));  
  10.             for j = 0 to (cur_size - 1) do
  11.                 if cur.(j) > (i + 1) then
  12.                     ans_arr.(cur.(j) - 1) <- max (ans_arr.(cur.(j) - 1) + 1) (ans_arr.(i) + 1)
  13.             done;
  14.         done;
  15.     !answer;
  16.  
  17. (*path [| [|3;5;6|]; [|4|]; [|6|]; [|5|]; [|6|]; [|1|] |] = 4;;*)
  18.  
  19. type node = {value: int; mutable neighbours: int list}
  20.  
  21. type graph = node array
  22.  
  23. let g_make n =
  24.     Array.init n (fun i -> {value = i; neighbours = []})
  25.  
  26. let neighbours g i =
  27.     g.(i).neighbours
  28.  
  29. let size g =
  30.     Array.length g
  31.  
  32. let insert_edge g i j =
  33.     g.(i).neighbours <- j :: g.(i).neighbours;
  34.     g.(j).neighbours <- i :: g.(j).neighbours
  35.  
  36. let path2 g =
  37.     let n = size g in
  38.     let ans_arr = Array.make n 1
  39.     and answer = ref 0 in
  40.         for i = 0 to (n - 1) do
  41.             let cur = Array.of_list (neighbours g i) in
  42.             let cur_size = Array.length cur in
  43.             answer := max !answer (ans_arr.(i));  
  44.             for j = 0 to (cur_size - 1) do
  45.                 if cur.(j) > (i + 1) then
  46.                     ans_arr.(cur.(j) - 1) <- max (ans_arr.(cur.(j) - 1) + 1) (ans_arr.(i) + 1)
  47.             done;
  48.         done;
  49.     !answer;;
  50.  
  51.  
  52. let test = g_make 6;;
  53. insert_edge test 0 2;
  54. insert_edge test 0 4;
  55. insert_edge test 0 5;
  56. insert_edge test 1 3;
  57. insert_edge test 2 5;
  58. insert_edge test 3 4;
  59. insert_edge test 4 5;
  60. path2 test;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement