let make_uf n = Array.init n (fun i -> i)

let rec find p x =
  if p.(x) = x then x
  else begin
    let r = find p p.(x) in
    p.(x) <- r;
    r
  end

let union p x y =
  let rx = find p x in
  let ry = find p y in
  if rx <> ry then p.(rx) <- ry

let count_components p n =
  let c = ref 0 in
  for i = 0 to n - 1 do
    if find p i = i then c := !c + 1
  done;
  !c

;;

let n = 10 in
let p = make_uf n in
union p 0 1;
union p 2 3;
union p 4 5;
union p 6 7;
union p 0 2;
union p 4 6;
count_components p n
