Skip to content

Instantly share code, notes, and snippets.

@MaskRay
Created February 8, 2013 04:37
Show Gist options
  • Save MaskRay/4736618 to your computer and use it in GitHub Desktop.
Save MaskRay/4736618 to your computer and use it in GitHub Desktop.
给个数组,打乱了,比如:索引 0 1 2 3 4;值 3 2 1 4 0 。数组的值是下次跳的索引位置,这样的话数组有环,比如 0 -> 3 -> 4 -> 0 1 -> 2 -> 1, 求最长环的长度。
let huangBingchao a =
let n = Array.length a in
let rec go2 j i l =
if a.(i) < 0 then
(j, l)
else
let ii = a.(i) in
a.(i) <- j;
go2 (lnot i) ii (l+1) in
let rec go i mx =
if i < 0 then
mx
else
let (ix, l) = if a.(i) < 0 then (a.(i), 0) else go2 (-1) i 0 in
a.(i) <- lnot ix;
go (i-1) (max mx l) in
go (n-1) 0
let read_int () = Scanf.scanf " %d" (fun x -> x)
let n = read_int()
let a = Array.init n (fun _ -> read_int());;
Printf.printf "%d\n" (huangBingchao a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment