(* http://yukicoder.me/problems/11 *) let bitcount n = let rec loop bits num = if bits = 0 then num else loop (bits land (bits-1)) (num+1) in loop n 0 let solve n = let visited = Array.init (n+1) (fun _ -> false) in let q = Queue.create () in Queue.add (1,1) q; let ans = ref 0 in while !ans = 0 do if Queue.is_empty q then ans := -1 else let i, cnt = Queue.take q in if i = n then ans := cnt else ( visited.(i) <- true; let num = bitcount i in if i+num = n then ans := cnt+1 else ( if i+num < n && not visited.(i+num) then Queue.add (i+num, cnt+1) q; if i-num >= 1 && not visited.(i-num) then Queue.add (i-num, cnt+1) q; ) ) done; !ans let () = Scanf.scanf "%d\n" solve |> Printf.printf "%d\n"