let topo_sort n adj =
  let in_deg = Array.make n 0 in
  for i = 0 to n - 1 do
    List.iter (fun j -> in_deg.(j) <- in_deg.(j) + 1) adj.(i)
  done;
  let q = Queue.create () in
  for i = 0 to n - 1 do
    if in_deg.(i) = 0 then Queue.push i q
  done;
  let count = ref 0 in
  while not (Queue.is_empty q) do
    let u = Queue.pop q in
    count := !count + 1;
    List.iter (fun v ->
      in_deg.(v) <- in_deg.(v) - 1;
      if in_deg.(v) = 0 then Queue.push v q
    ) adj.(u)
  done;
  !count

;;

let n = 6 in
let adj = [|
  [1; 2];
  [3];
  [3; 4];
  [5];
  [5];
  []
|] in
topo_sort n adj
