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

let in_deg = Array.make n 0
let paths = Array.make n 0

let count_paths () =
  for u = 0 to n - 1 do
    List.iter (fun v -> in_deg.(v) <- in_deg.(v) + 1) adj.(u)
  done;
  let order = ref [] in
  let q = Queue.create () in
  for v = 0 to n - 1 do
    if in_deg.(v) = 0 then Queue.push v q
  done;
  while not (Queue.is_empty q) do
    let u = Queue.pop q in
    order := u :: !order;
    List.iter (fun v ->
      in_deg.(v) <- in_deg.(v) - 1;
      if in_deg.(v) = 0 then Queue.push v q
    ) adj.(u)
  done;
  paths.(0) <- 1;
  let topo = List.rev !order in
  List.iter (fun u ->
    List.iter (fun v ->
      paths.(v) <- paths.(v) + paths.(u)
    ) adj.(u)
  ) topo;
  paths.(n - 1)

;;

count_paths ()
