After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?

The first line contains integer n (1 ≤ n ≤ 105) — the number of groups of schoolchildren. The second line contains a sequence of integers s1, s2, ..., sn (1 ≤ si ≤ 4). The integers are separated by a space, si is the number of children in the i-th group.

Print the single number — the minimum number of taxis necessary to drive all children to Polycarpus.

NoteIn the first test we can sort the children into four cars like this:  the third group (consisting of four children),  the fourth group (consisting of three children),  the fifth group (consisting of three children),  the first and the second group (consisting of one and two children, correspondingly). There are other ways to sort the groups into four cars.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make 5 0;;
for i=1 to n do
   let k=read_int() in tab.(k)<-tab.(k)+1
done;;
if (tab.(2) mod 2)=0 then (tab.(1)<-max 0 (tab.(1)-tab.(3));tab.(2)<-tab.(2)/2)
else (tab.(1)<-max 0 (tab.(1)-tab.(3)-2);tab.(2)<-tab.(2)/2+1);;
if (tab.(1) mod 4)=0 then tab.(1)<-tab.(1)/4 else tab.(1)<-tab.(1)/4+1;;
print_int(tab.(1)+tab.(2)+tab.(3)+tab.(4));;

(* Codeforces 158 B Taxi *)

(* you can use either gr or rdln but not both *)
let gr () = Scanf.scanf " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let grc () = Scanf.scanf " %c" (fun i -> i);;
let rdln() = input_line stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let debug = false;;

let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;

let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;

let taxi1 n1 =
    let n14 = n1/4 in
    let nn1 = n1 - n14*4 in
    let t1 = if nn1 > 0 then (n14 + 1)
            else n14 in
    (* let _ = Printf.printf "n1 t1 = %d %d\n" n1 t1 in *)
    t1;;

let taxi2 n1 n2 =
    let n22 = n2/2 in
    let nn2 = n2 - 2 * n22 in
    let nn1 = if nn2 == 0 then n1
        else if n1 > 2 then n1 - 2
        else 0 in
    let t2 = n22 + nn2 + taxi1 nn1 in
    (* let _ = Printf.printf "n1,n2 = %d %d t2 = %d\n" n1 n2 t2 in *)
    t2;;

let taxi3 n1 n2 n3 =
    let nn1 = if n3 > n1 then 0 else (n1 - n3) in
    n3 + taxi2 nn1 n2;;

let taxi4 n1 n2 n3 n4 =
    n4 + taxi3 n1 n2 n3;;

let rec count4 n1 n2 n3 n4 a = match a with
    | [] -> (n1, n2, n3, n4)
    | h :: t ->
    match h with
      | 1 -> count4 (n1 + 1) n2 n3 n4 t
      | 2 -> count4 n1 (n2 + 1) n3 n4 t
      | 3 -> count4 n1 n2 (n3 + 1) n4 t
      | 4 -> count4 n1 n2 n3 (n4 + 1) t
      | _ ->
      let _ = print_string "bad h in count4\n" in
      (-9999,0,0,0);;

let main() =
	let n = gr () in
	let s = readlist n [] in
	let n1,n2,n3,n4 = count4 0 0 0 0 s in
    (* let _ = Printf.printf "n1-4 = %d %d %d %d\n" n1 n2 n3 n4 in *)
	let taxi = taxi4 n1 n2 n3 n4 in
	begin
		print_int taxi;
		print_string "\n"
	end;;

main();;

let read_int () = Scanf.scanf "%d " (fun x -> x);;
let read_int3 () = Scanf.scanf " %d %d %d " (fun x y z -> (x,y,z) );;

let numx = Array.make 4 0;;
let n = read_int ();;
  for i = 1 to n do
    Scanf.scanf "%d " (fun x -> numx.(x-1)<- numx.(x-1)+1)
  done

let num_cars = ref ( numx.(3) + numx.(1)/2 );;
let () = numx.(1) <- numx.(1) mod 2;;
let () = if (numx.(0) <= numx.(2)  ) then
           begin
             numx.(2) <- numx.(2) - numx.(0);
             num_cars := !num_cars + numx.(0);
             numx.(0) <- 0
           end
         else
           begin
             num_cars := !num_cars + numx.(2);
             numx.(0) <- numx.(0) - numx.(2);
           end
;;

let () = if (numx.(0) == 0) then
           num_cars := !num_cars + numx.(2) + numx.(1)
         else
           begin
             if(numx.(1) == 1) then
               begin
                 num_cars := !num_cars + 1;
                 numx.(0) <- numx.(0) -2
               end;
             if (numx.(0) > 0) then
               num_cars := !num_cars + ( numx.(0) + 3) /4
           end
;;
let ()= print_int !num_cars; print_endline "";;

let read_int () = Scanf.scanf "%d " (fun x -> x);;
let read_int3 () = Scanf.scanf " %d %d %d " (fun x y z -> (x,y,z) );;

let n = read_int ();;
let a = Array.init n (fun i -> read_int () );;
let numx = Array.make 4 0;;
let vote i = numx.(i-1) <- numx.(i-1) + 1;;
let () = Array.iter (fun x -> vote x) a;;

let num_cars = ref ( numx.(3) + numx.(1)/2 );;

let () = numx.(1) <- numx.(1) mod 2;;

let () = if (numx.(0) <= numx.(2)  ) then
           begin
             numx.(2) <- numx.(2) - numx.(0);
             num_cars := !num_cars + numx.(0);
             numx.(0) <- 0
           end
         else
           begin
             num_cars := !num_cars + numx.(2);
             numx.(0) <- numx.(0) - numx.(2);
           end
;;

let () = if (numx.(0) == 0) then
           num_cars := !num_cars + numx.(2) + numx.(1)
         else
           begin
             if(numx.(1) == 1) then
               begin
                 num_cars := !num_cars + 1;
                 numx.(0) <- numx.(0) -2
               end;
             if (numx.(0) > 0) then
               num_cars := !num_cars + ( numx.(0) + 3) /4
           end
;;

let ()= print_int !num_cars; print_endline "";;

let read_int () = Scanf.scanf "%d " (fun x -> x);;
let read_int3 () = Scanf.scanf " %d %d %d " (fun x y z -> (x,y,z) );;

let n = read_int ();;
let a = Array.init n (fun i -> read_int () );;
let numx = Array.make 4 0;;
let vote i = numx.(i-1) <- numx.(i-1) + 1;;
let () = Array.iter (fun x -> vote x) a;;

let num_cars = ref ( numx.(3) + numx.(1)/2 );;

let () = numx.(1) <- numx.(1) mod 2;;

let () = if (numx.(0) <= numx.(2)  ) then
           begin
             numx.(2) <- numx.(2) - numx.(0);
             num_cars := !num_cars + numx.(0);
             numx.(0) <- 0
           end
         else
           begin
             num_cars := !num_cars + numx.(2);
             numx.(0) <- numx.(0) - numx.(2);
             numx.(2) <- 0
           end
;;

let () = if (numx.(0) == 0) then
           num_cars := !num_cars + numx.(2) + numx.(1)
         else
           begin
             if(numx.(1) == 1) then
               begin
                 num_cars := !num_cars + 1;
                 numx.(0) <- numx.(0) -2
               end;
             if (numx.(0) > 0) then
               begin
                 if (numx.(0) mod 4 == 0) then
                   num_cars := !num_cars + numx.(0)/4
                 else
                   num_cars := !num_cars + numx.(0)/4 + 1
               end
           end
;;

let ()= print_int !num_cars; print_endline "";;

let read_int () = Scanf.scanf " %d" (fun x -> x)

let solve n =
  let data = [|0; 0; 0; 0; 0|] in
    for i = 1 to n do
      match read_int () with
      | 1 when data.(3) > 0 -> data.(3) <- data.(3) - 1; data.(4) <- data.(4) + 1
      | 2 when data.(2) > 0 -> data.(2) <- data.(2) - 1; data.(4) <- data.(4) + 1
      | 3 when data.(1) > 0 -> data.(1) <- data.(1) - 1; data.(4) <- data.(4) + 1
      | i -> data.(i) <- data.(i) + 1
    done;

    if data.(2) > 0 && data.(1) > 0 then begin
      data.(2) <- 0;
      data.(4) <- data.(4) + 1;
      if data.(1) > 1
      then data.(1) <- data.(1)-2
      else data.(1) <- 0
    end;

    if data.(1) mod 4 = 0
    then data.(4) + data.(3) + data.(2) + data.(1) / 4
    else data.(4) + data.(3) + data.(2) + data.(1) / 4 + 1

let () =
  let n = read_int ()
  in Printf.printf "%d\n" (solve n)

let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x) ;;

let n = read_int () ;;

let s =
    let rec loop i n f =
        if i > n then f []
        else let si = read_int () in loop (i + 1) n (fun l -> f (si :: l))
    in loop 1 n (fun x -> x) ;;

let count x =
    let rec loop total = function
        | [] -> total
        | h :: t -> loop (total + if h = x then 1 else 0) t
    in loop 0 ;;

let one = count 1 s
    and two = count 2 s
    and three = count 3 s
    and four = count 4 s ;;

let group31 = min one three ;;
let group21 = min (two mod 2) (one - group31) ;;
let group2 = two / 2 + if group21 = 1 then 0 else (two mod 2) ;;
let group1 = ((max 0 (one - group31 - group21 * 2)) + 3) / 4 ;;

let taxis = four + three + group2 + group21 + group1 ;;

Printf.printf "%d\n" taxis ;;

let _ =
    let main () =
        let n = read_int () in
        let arr = Array.create 5 0 in
        let rec loop i =
            if i > 0 then (
                Scanf.scanf " %d" (fun x -> arr.(x) <- arr.(x) + 1);
                loop (i - 1)
            )
        in
        loop n;
        let c = arr.(4) + arr.(3) in
        let _ = arr.(1) <- arr.(1) - min arr.(1) arr.(3) in
        let c = c + (arr.(2) + 1) / 2 in
        let _ = arr.(1) <- arr.(1) - min arr.(1) ((arr.(2) mod 2) * 2) in
        let r = c + (arr.(1) + 3) / 4 in
        Printf.printf "%d\n" r
    in
    main ()

let input () = Scanf.scanf "%d " (fun n -> n)

let rec read list n =
    if n > 0
    then
        let var = Scanf.scanf "%d " (fun n -> n) in
        read (var :: list) (n - 1)
    else
        List.rev list

let separate list s =
    let rec filter list s current_counts =
    if s > 0
    then
        let count = List.length(List.filter (fun int -> int = s) list) in
        filter list (s - 1) (count :: current_counts)
    else
        current_counts
    in filter list s []

let no_owerflow n =
    if n < 0
    then
        0
    else
        n

let taxis list = match (separate list 4) with
|[ones; twos; threes; fours] -> fours + threes + (twos * 2 + no_owerflow(ones - threes) + 3) / 4

let solve input = taxis (read [] input)

let print result = Printf.printf "%d\n" result

let () = print (solve (input ()))

open Scanf;;

let parse n =
  let rec parseInt n acc =
    if n <= 0 then acc
    else
      match bscanf Scanning.stdin " %d" (fun x -> x) with
      | d -> parseInt (n - 1) (d :: acc)
      | exception _ -> acc
  in parseInt n [];;

let taxis numList =
  let ones, twos, threes, fourths =
    List.fold_left ( fun (ones, twos, threes, fourths) x ->
      match x with
      | 1 -> (ones + 1, twos, threes, fourths)
      | 2 -> (ones, twos + 1, threes, fourths)
      | 3 -> (ones, twos, threes + 1, fourths)
      | 4 -> (ones, twos, threes, fourths + 1)
      | _ -> (ones, twos, threes, fourths)
    ) (0, 0, 0, 0) numList
  in let needed = fourths
  in let needed = needed + twos / 2
  in let twos = twos mod 2
  in let needed = needed + threes
  in if ones > threes then
    let ones = ones - threes
    in let needed = needed + ones / 4
    in if twos = 1 then
      if ones  mod 4 > 2 then
        needed + 2
      else
        needed + 1
    else
      if ones mod 4 = 0 then
        needed
      else
        needed + 1
  else
    needed + twos / 2 + twos mod 2

let main () =
  let n = bscanf Scanning.stdin "%d\n" (fun x -> x)
  in let numList = parse n
  in taxis numList;;

Printf.printf "%d" (main ());;

open Scanf
open Printf
let n = scanf "%d\n" (fun n -> n)

let (n1,n2,n3,n4) =
  let a = Array.make 10 0 in
  for i=0 to n-1 do
    let i =  scanf "%d " (fun x -> x) in
    a.(i) <- a.(i) + 1
  done;
  (a.(1),a.(2),a.(3),a.(4))

let () = (*
  printf "%d %d %d %d\n" n1 n2 n3 n4; *)
  ()
let ans = ref n4
let n4 = 0
let incr2 x =
  ans := !ans +x;
  (*printf "incr by %d to %d\n" x !ans;*)
  ()
let info x = (*
  printf "Evaling %d \n" x;*)
  ()

let () =
  let m =  (min n1 n3) in
  incr2 m;
  let n1 = n1 - m in
  let n3 = n3-m in
  let n3 =
    info 3;
    if n3>0 then (incr2 n3; 0) else n3 in
  let n2 =
    info 2;
    incr2 (n2/2);
    n2 mod  2 in
  let (n1,n2) =
    info 2;
    if n2>0 then (incr2 1; (n1-2,0)) else (n1,n2) in
  let () =
    let last =
      if n1>0 then ( (if n1 mod 4 = 0 then 0 else 1) + (n1/4) )
      else 0
    in
    incr2 last
  in ()

let () = print_int !ans; print_newline ()

let nextInt() =
  Scanf.scanf "%d " (fun x -> x);;

let readList n f =
  let rec loop n =
    if n == 0 then
      []
    else
      f() :: loop (n-1)
  in
  List.rev(loop n);;

let incValue arr x =
  arr.(x) <- arr.(x) + 1;;

let groupByList l =
  let counts = (Array.make 5 0) in
  let _ = List.map (incValue counts) l in
  counts;;

let rec fitTaxis counts =
  let sol = ref 0 in
  sol := counts.(4);

  let taxi3pack = min counts.(1) counts.(3) in
  sol := !sol + taxi3pack;
  counts.(1) <- counts.(1) - taxi3pack;
  counts.(3) <- counts.(3) - taxi3pack;
  sol := !sol + counts.(3);
  let remainder = counts.(1) + (counts.(2) * 2) in
  if remainder mod 4 == 0 then
    remainder / 4 + !sol
  else
    remainder / 4 + 1 + !sol;;

let _ =
  let n = read_int() in
  let l = readList n nextInt in
  let counts = groupByList l in
  print_int(fitTaxis counts);
  print_newline()

let nextInt() =
  Scanf.scanf "%d " (fun x -> x);;

let readList n f =
  let rec loop n =
    if n == 0 then
      []
    else
      f() :: loop (n-1)
  in
  List.rev(loop n);;

let incValue arr x =
  arr.(x) <- arr.(x) + 1;;

let groupByList l =
  let counts = (Array.make 5 0) in
  let _ = List.map (incValue counts) l in
  counts;;

let fitTaxis counts =
  let sol = ref 0 in
  sol := counts.(4);

  let taxi3pack = min counts.(1) counts.(3) in
  sol := !sol + taxi3pack;
  counts.(1) <- counts.(1) - taxi3pack;
  counts.(3) <- counts.(3) - taxi3pack;
  sol := !sol + counts.(3);
  !sol + (counts.(1) + (counts.(2) * 2) + 3) / 4;;

let _ =
  let n = read_int() in
  let l = readList n nextInt in
  let counts = groupByList l in
  print_int(fitTaxis counts);
  print_newline()

open Scanf;;
open Printf;;
open List;;

let read_and_count n =
  let rec read n acc =
    match n with
    | 1 -> let y = (scanf "%d" (fun x->x) ) in
       acc.(y) <- acc.(y) + 1;
       acc
    | x -> let y = (scanf "%d " (fun x->x)) in
       acc.(y) <- acc.(y) + 1;
       read (x-1) acc
  in read n (Array.make 5 0)
;;

let n = scanf "%d\n" (fun x -> x) in
let counters = (read_and_count n) in
let sol = ref 0 in
sol := !sol + counters.(4);
let mini = (min counters.(3) counters.(1)) in
sol := !sol + mini;
counters.(3) <- counters.(3) - mini;
counters.(1) <- counters.(1) - mini;
sol := !sol + counters.(3);
sol := !sol + ( (counters.(2)*2 + counters.(1) + 3) / 4);
printf "%d\n" !sol;

let read_int () = Scanf.scanf "%d " (fun x -> x);;
let read_int3 () = Scanf.scanf " %d %d %d " (fun x y z -> (x,y,z) );;

let n = read_int ();;
let a = Array.init n (fun i -> read_int () );;
let numx = Array.make 4 0;;
let vote i = numx.(i-1) <- numx.(i-1) + 1;;
let () = Array.iter (fun x -> vote x) a;;

let num_cars = ref ( numx.(3) + numx.(1)/2 + numx.(0)/4 );;

let remain_2 = numx.(1) mod 2;;
let remain_1 = numx.(0) mod 4;;

let () = if (remain_1 > numx.(2)) then
             num_cars := !num_cars + numx.(2) + (remain_1 - numx.(2) )
         else if (remain_1 == numx.(2)) then
           num_cars := !num_cars + numx.(2) + remain_2
         else
           num_cars := !num_cars + remain_1 + (numx.(2) - remain_1) + remain_2
;;

let () = (print_int !num_cars; print_endline "");;

         (* This is the easy way *)
(*
         let b = Array.to_list cars
        |> List.filter (fun x -> (x>0))
        |> List.length
;;

let ()= print_int b; print_endline "";;
 *)

let read_int () = Scanf.scanf "%d " (fun x -> x);;
let read_int3 () = Scanf.scanf " %d %d %d " (fun x y z -> (x,y,z) );;

let n = read_int ();;

let a = Array.init n (fun i -> read_int () );;

let () = a |> Array.sort (fun x y -> (if (x < y ) then 1 else -1) );;

let cars = Array.make n 0;; (* Call n empty cars *)

  exception BreakLoop;;
  for i = 0 to n-1 do
    try
    for j = 0 to n-1 do
      let x = a.(i) + cars.(j) in
      if ( x <= 4 ) then
        begin
          cars.(j) <- x;
          raise BreakLoop
        end
    done
    with BreakLoop -> ()

  done;;

  let num_cars = ref 0;;
    try
    for i = 0; to n-1 do
      if(cars.(i)>0) then
        num_cars := !num_cars + 1
      else
        raise BreakLoop
    done
    with BreakLoop -> print_int !num_cars; print_endline "";;

         (* This is the easy way *)
(*
         let b = Array.to_list cars
        |> List.filter (fun x -> (x>0))
        |> List.length
;;

let ()= print_int b; print_endline "";;
 *)

let _ =
    let main () =
        let n = read_int () in
        let arr = Array.create 5 0 in
        let rec loop i =
            if i > 0 then (
                Scanf.scanf " %d" (fun x -> arr.(x) <- arr.(x) + 1);
                loop (i - 1)
            )
        in
        loop n;
        let c = arr.(4) + arr.(3) in
        let _ = arr.(1) <- arr.(1) - min arr.(1) arr.(3) in
        let c = c + (arr.(2) + 1) / 2 in
        let _ = arr.(1) <- arr.(1) - min arr.(1) ((arr.(2) mod 1) * 2) in
        let r = c + (arr.(1) + 3) / 4 in
        Printf.printf "%d\n" r
    in
    main ()

open Scanf;;

let parse n =
  let rec parseInt n acc =
    if n <= 0 then acc
    else
      match bscanf Scanning.stdin " %d" (fun x -> x) with
      | d -> parseInt (n - 1) (d :: acc)
      | exception _ -> acc
  in parseInt n [];;

let taxis numList =
  let ones, twos, threes, fourths =
    List.fold_left ( fun (ones, twos, threes, fourths) x ->
      match x with
      | 1 -> (ones + 1, twos, threes, fourths)
      | 2 -> (ones, twos + 1, threes, fourths)
      | 3 -> (ones, twos, threes + 1, fourths)
      | 4 -> (ones, twos, threes, fourths + 1)
      | _ -> (ones, twos, threes, fourths)
    ) (0, 0, 0, 0) numList
  in let needed = fourths
  in let needed = needed + twos / 2
  in let twos = twos mod 2
  in let needed = needed + threes
  in if ones > threes then
    let ones = ones - threes
    in let needed = needed + ones / 4
    in if twos = 1 then
      if ones  mod 4 > 2 then
        needed + 2
      else
        needed + 1
    else
      if (ones - threes) mod 4 = 0 then
        needed
      else
        needed + 1
  else
    needed + twos / 2 + twos mod 2

let main () =
  let n = bscanf Scanning.stdin "%d\n" (fun x -> x)
  in let numList = parse n
  in taxis numList;;

Printf.printf "%d" (main ());;

open Scanf;;

let parse () =
  let rec parseInt acc =
    match bscanf Scanning.stdin " %d" (fun x -> x) with
    | d -> parseInt (d :: acc)
    | exception _ -> acc
  in parseInt [];;

let taxis numList =
  let ones, twos, threes, fourths =
    List.fold_left ( fun (ones, twos, threes, fourths) x ->
      match x with
      | 1 -> (ones + 1, twos, threes, fourths)
      | 2 -> (ones, twos + 1, threes, fourths)
      | 3 -> (ones, twos, threes + 1, fourths)
      | 4 -> (ones, twos, threes, fourths + 1)
      | _ -> (ones, twos, threes, fourths)
    ) (0, 0, 0, 0) numList
  in let needed = fourths
  in let needed = needed + twos / 2
  in let twos = twos mod 2
  in let needed = needed + threes
  in if ones > threes then
    let needed = needed + ones / 4
    in if twos = 1 then
      if ones mod 4 > 2 then
        needed + 2
      else
        needed + 1
    else
      if ones mod 4 = 0 then
        needed
      else
        needed + 1
  else
    needed + twos / 2 + twos mod 2

let main () =
  let _ = bscanf Scanning.stdin "%d\n" (fun x -> x)
  in let numList = parse ()
  in taxis numList;;

Printf.sprintf "%d" (main ());;

open Scanf;;

let parse n =
  let rec parseInt n acc =
    if n <= 0 then acc
    else
      match bscanf Scanning.stdin " %d" (fun x -> x) with
      | d -> parseInt (n - 1) (d :: acc)
      | exception _ -> acc
  in parseInt n [];;

let taxis numList =
  let ones, twos, threes, fourths =
    List.fold_left ( fun (ones, twos, threes, fourths) x ->
      match x with
      | 1 -> (ones + 1, twos, threes, fourths)
      | 2 -> (ones, twos + 1, threes, fourths)
      | 3 -> (ones, twos, threes + 1, fourths)
      | 4 -> (ones, twos, threes, fourths + 1)
      | _ -> (ones, twos, threes, fourths)
    ) (0, 0, 0, 0) numList
  in let needed = fourths
  in let needed = needed + twos / 2
  in let twos = twos mod 2
  in let needed = needed + threes
  in if ones > threes then
    let needed = needed + ones / 4
    in if twos = 1 then
      if ones mod 4 > 2 then
        needed + 2
      else
        needed + 1
    else
      if ones - threes mod 4 = 0 then
        needed
      else
        needed + 1
  else
    needed + twos / 2 + twos mod 2

let main () =
  let n = bscanf Scanning.stdin "%d\n" (fun x -> x)
  in let numList = parse n
  in taxis numList;;

Printf.printf "%d" (main ());;

open Scanf;;

let parse n =
  let rec parseInt n acc =
    if n <= 0 then acc
    else
      match bscanf Scanning.stdin " %d" (fun x -> x) with
      | d -> parseInt (n - 1) (d :: acc)
      | exception _ -> acc
  in parseInt n [];;

let taxis numList =
  let ones, twos, threes, fourths =
    List.fold_left ( fun (ones, twos, threes, fourths) x ->
      match x with
      | 1 -> (ones + 1, twos, threes, fourths)
      | 2 -> (ones, twos + 1, threes, fourths)
      | 3 -> (ones, twos, threes + 1, fourths)
      | 4 -> (ones, twos, threes, fourths + 1)
      | _ -> (ones, twos, threes, fourths)
    ) (0, 0, 0, 0) numList
  in let needed = fourths
  in let needed = needed + twos / 2
  in let twos = twos mod 2
  in let needed = needed + threes
  in if ones > threes then
    let ones = ones - threes
    in let needed = needed + ones / 4
    in if twos = 1 then
      if ones  mod 4 > 2 then
        needed + 2
      else
        needed + 1
    else
      if (ones - threes) mod 4 = 0 then
        needed + 300
      else
        needed + 1
  else
    needed + twos / 2 + twos mod 2

let main () =
  let n = bscanf Scanning.stdin "%d\n" (fun x -> x)
  in let numList = parse n
  in taxis numList;;

Printf.printf "%d" (main ());;

open Scanf;;

let parse n =
  let rec parseInt n acc =
    if n <= 0 then acc
    else
      match bscanf Scanning.stdin " %d" (fun x -> x) with
      | d -> parseInt (n - 1) (d :: acc)
      | exception _ -> acc
  in parseInt n [];;

let taxis numList =
  let ones, twos, threes, fourths =
    List.fold_left ( fun (ones, twos, threes, fourths) x ->
      match x with
      | 1 -> (ones + 1, twos, threes, fourths)
      | 2 -> (ones, twos + 1, threes, fourths)
      | 3 -> (ones, twos, threes + 1, fourths)
      | 4 -> (ones, twos, threes, fourths + 1)
      | _ -> (ones, twos, threes, fourths)
    ) (0, 0, 0, 0) numList
  in let needed = fourths
  in let needed = needed + twos / 2
  in let twos = twos mod 2
  in let needed = needed + threes
  in if ones > threes then
    let needed = needed + ones / 4
    in if twos = 1 then
      if ones mod 4 > 2 then
        needed + 2
      else
        needed + 1
    else
      if ones mod 4 = 0 then
        needed
      else
        needed + 1
  else
    needed + twos / 2 + twos mod 2

let main () =
  let n = bscanf Scanning.stdin "%d\n" (fun x -> x)
  in let numList = parse n
  in taxis numList;;

Printf.printf "%d" (main ());;

open Scanf;;

let parse n =
  let rec parseInt n acc =
    if n <= 0 then acc
    else
      match bscanf Scanning.stdin " %d" (fun x -> x) with
      | d -> parseInt (n - 1) (d :: acc)
      | exception _ -> acc
  in parseInt n [];;

let taxis numList =
  let ones, twos, threes, fourths =
    List.fold_left ( fun (ones, twos, threes, fourths) x ->
      match x with
      | 1 -> (ones + 1, twos, threes, fourths)
      | 2 -> (ones, twos + 1, threes, fourths)
      | 3 -> (ones, twos, threes + 1, fourths)
      | 4 -> (ones, twos, threes, fourths + 1)
      | _ -> (ones, twos, threes, fourths)
    ) (0, 0, 0, 0) numList
  in let needed = fourths
  in let needed = needed + twos / 2
  in let twos = twos mod 2
  in let needed = needed + threes
  in if ones > threes then
    let needed = needed + ones / 4
    in if twos = 1 then
      if ones mod 4 > 2 then
        needed + 2
      else
        needed + 1
    else
      if (ones - threes) mod 4 = 0 then
        needed
      else
        needed + 1
  else
    needed + twos / 2 + twos mod 2

let main () =
  let n = bscanf Scanning.stdin "%d\n" (fun x -> x)
  in let numList = parse n
  in taxis numList;;

Printf.printf "%d" (main ());;


She is skilled in all kinds of magics, and is keen on inventing new one.—Perfect Memento in Strict SensePatchouli is making a magical talisman. She initially has $$$n$$$ magical tokens. Their magical power can be represented with positive integers $$$a_1, a_2, \ldots, a_n$$$. Patchouli may perform the following two operations on the tokens.  Fusion: Patchouli chooses two tokens, removes them, and creates a new token with magical power equal to the sum of the two chosen tokens.  Reduction: Patchouli chooses a token with an even value of magical power $$$x$$$, removes it and creates a new token with magical power equal to $$$\frac{x}{2}$$$. Tokens are more effective when their magical powers are odd values. Please help Patchouli to find the minimum number of operations she needs to make magical powers of all tokens odd values.

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The description of the test cases follows. For each test case, the first line contains one integer $$$n$$$ ($$$1 \leq n\leq 2\cdot 10^5$$$) — the initial number of tokens. The second line contains $$$n$$$ intergers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial magical power of the $$$n$$$ tokens. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum number of operations Patchouli needs to make all tokens have an odd value of magical power. It can be shown that under such restrictions the required sequence of operations exists.

NoteTest case 1:$$$a$$$ consists solely of odd numbers initially.Test case 2:Choose the tokens with magical power of $$$1$$$ and $$$2$$$ and perform Fusion. Now $$$a=[1,3]$$$, both are odd numbers.Test case 3:Choose the tokens with magical power of $$$2$$$ and $$$8$$$ and perform Fusion. Now $$$a=[4,10]$$$.Choose the token with magical power of $$$10$$$ and perform Reduction. Now $$$a=[4,5]$$$.Choose the tokens with magical power of $$$4$$$ and $$$5$$$ and perform Fusion. Now $$$a=[9]$$$, and $$$9$$$ is an odd number.It can be shown that you can not make all the magical powers odd numbers in less than $$$3$$$ moves, so the answer is $$$3$$$.

let read_int () = Scanf.scanf " %d" (fun x -> x);;

let rec get_ce = function
| (le, x) ->
     if (x mod 2 == 0) then get_ce ((le+1),(x/2))
     else le
;;
let rec get_ne_le = function
| (ne, le, 0) -> ne, le
| (ne, le, t) ->
     let x = read_int () in
     let ce = get_ce (0, x) in
     if (ce == 0) then get_ne_le (ne, 0, (t-1))
     else if (ce < le) then get_ne_le ((ne+1), ce, (t-1))
     else get_ne_le ((ne+1), le, (t-1))
;;
let run_case = function
| () ->
     let n = read_int () in
     let ne, le = get_ne_le (0, 30, n) in
     if (le==0) then print_int ne
     else print_int (ne+le-1)
;;

let rec iter_cases = function
| 0 -> ()
| t ->
     run_case ();
     print_newline ();
     iter_cases (t-1)
;;

let t=read_int() in iter_cases t;;


Theseus has just arrived to Crete to fight Minotaur. He found a labyrinth that has a form of a rectangular field of size n × m and consists of blocks of size 1 × 1.Each block of the labyrinth has a button that rotates all blocks 90 degrees clockwise. Each block rotates around its center and doesn't change its position in the labyrinth. Also, each block has some number of doors (possibly none). In one minute, Theseus can either push the button in order to rotate all the blocks 90 degrees clockwise or pass to the neighbouring block. Theseus can go from block A to some neighbouring block B only if block A has a door that leads to block B and block B has a door that leads to block A.Theseus found an entrance to labyrinth and is now located in block (xT, yT) — the block in the row xT and column yT. Theseus know that the Minotaur is hiding in block (xM, yM) and wants to know the minimum number of minutes required to get there.Theseus is a hero, not a programmer, so he asks you to help him.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and the number of columns in labyrinth, respectively. Each of the following n lines contains m characters, describing the blocks of the labyrinth. The possible characters are:   «+» means this block has 4 doors (one door to each neighbouring block);  «-» means this block has 2 doors — to the left and to the right neighbours;  «|» means this block has 2 doors — to the top and to the bottom neighbours;  «^» means this block has 1 door — to the top neighbour;  «>» means this block has 1 door — to the right neighbour;  «<» means this block has 1 door — to the left neighbour;  «v» means this block has 1 door — to the bottom neighbour; «L» means this block has 3 doors — to all neighbours except left one;  «R» means this block has 3 doors — to all neighbours except right one;  «U» means this block has 3 doors — to all neighbours except top one;  «D» means this block has 3 doors — to all neighbours except bottom one; «*» means this block is a wall and has no doors.  Left, right, top and bottom are defined from representing labyrinth as a table, where rows are numbered from 1 to n from top to bottom and columns are numbered from 1 to m from left to right. Next line contains two integers — coordinates of the block (xT, yT) (1 ≤ xT ≤ n, 1 ≤ yT ≤ m), where Theseus is initially located. Last line contains two integers — coordinates of the block (xM, yM) (1 ≤ xM ≤ n, 1 ≤ yM ≤ m), where Minotaur hides. It's guaranteed that both the block where Theseus starts and the block where Minotaur is hiding have at least one door. Theseus and Minotaur may be initially located at the same block.

If Theseus is not able to get to Minotaur, then print -1 in the only line of the output. Otherwise, print the minimum number of minutes required to get to the block where Minotaur is hiding.

NoteAssume that Theseus starts at the block (xT, yT) at the moment 0.

open StdLabels

type vertex =
  { x : int;
    y : int;
    rot : int;
  }

let [n; m] = read_line () |> Str.(split (regexp " ")) |> List.map ~f:int_of_string
let s = n * m

let rotate = function
  | '+' -> '+'
  | '-' -> '|'
  | '|' -> '-'
  | '^' -> '>'
  | '>' -> 'v'
  | 'v' -> '<'
  | '<' -> '^'
  | 'U' -> 'R'
  | 'R' -> 'D'
  | 'D' -> 'L'
  | 'L' -> 'U'
  | '*' -> '*'
  | _ -> failwith "Unknown block"

let maze = Bytes.make (4 * s) ' '
let () =
  for y = 0 to n-1 do
    Bytes.blit ~src:(read_line ()) ~src_pos:0 ~dst:maze ~dst_pos:(y * m) ~len:m
  done;
  for i = s to 4 * s - 1 do
    maze.[i] <- rotate maze.[i-s]
  done

let read_coords () =
  read_line ()
  |> Str.(split (regexp " "))
  |> List.map ~f:(fun s -> int_of_string s - 1)
  (* Discovered that (X,Y) are named (Y,X) in problem! *)
  |> fun [y; x] -> y * m + x

let start = read_coords ()
let goal = read_coords ()

let default d = function
  | Some x -> x
  | None -> d

module Int = struct
  type t = int
  let compare = compare
end

module Vertex =
  struct
    type t = vertex
    let compare = compare
  end

module PriorityQueue(Priority : Map.OrderedType) =
  struct
    module PriorityMap = Map.Make(Priority)

    let create = ref PriorityMap.empty

    let add prio elt pq =
      let queue =
        if PriorityMap.mem prio !pq then
          PriorityMap.find prio !pq
        else
          let q = Queue.create () in
          pq := PriorityMap.add prio q !pq;
          q in
      Queue.add elt queue

    let pop pq =
      if PriorityMap.is_empty !pq then
        None
      else
        let prio, queue = PriorityMap.min_binding !pq in
        let r = Queue.pop queue in
        if Queue.is_empty queue then
          pq := PriorityMap.remove prio !pq;
        Some r
  end

module PriorityVertex =
  struct
    type t = int * Vertex.t
    let compare = compare
  end

module VertexSet = Set.Make(Vertex)

module VertexQueue = PriorityQueue(Int)

let astar ?(heuristic = fun v -> 0) ~start ~is_goal =
  let edge_length = 1 in
  let marks = Bytes.make (4*m*n) ' ' in
  let fringe = VertexQueue.create in
  VertexQueue.add (heuristic start) (start, 0) fringe;
  let rec go () =
    match VertexQueue.pop fringe with
    | None -> None
    | Some (v, dist) ->
       if is_goal v then
         Some dist
       else if marks.[v] = '*' then
         go ()
       else
         let dist' = dist + edge_length in
         marks.[v] <- '*';
         let enqueue u =
           if marks.[u] <> '*' then
             VertexQueue.add (dist' + heuristic u) (u, dist') fringe in
         let c = maze.[v] in
         let pl, pu, pr, pd = "+-<URD", "+|^RDL", "+->DLU", "+|vLUR" in
         let sc = String.contains in
         let xy = v mod s in
         let x = xy mod m and y = xy / m in
         enqueue ((v + s) mod (4 * s));
         if x > 0 && sc pl c && sc pr maze.[v-1] then
           enqueue (v-1);
         if y > 0 && sc pu c && sc pd maze.[v-m] then
           enqueue (v-m);
         if x < m-1 && sc pr c && sc pl maze.[v+1] then
           enqueue (v+1);
         if y < n-1 && sc pd c && sc pu maze.[v+m] then
           enqueue (v+m);
         go () in
  go ()

let is_goal v = (v - goal) mod s = 0

let heuristic v =
  let xy = v mod s in
  let dx = xy mod m - goal mod m and dy = xy/m - goal/m in
  abs dx + abs dy

let () =
  astar ~heuristic ~start ~is_goal
  |> default (-1)
  |> Printf.printf "%d\n"

open StdLabels

type vertex =
  { x : int;
    y : int;
    rot : int;
  }

let [n; m] = read_line () |> Str.(split (regexp " ")) |> List.map ~f:int_of_string
let s = n * m

let rotate = function
  | '+' -> '+'
  | '-' -> '|'
  | '|' -> '-'
  | '^' -> '>'
  | '>' -> 'v'
  | 'v' -> '<'
  | '<' -> '^'
  | 'U' -> 'R'
  | 'R' -> 'D'
  | 'D' -> 'L'
  | 'L' -> 'U'
  | '*' -> '*'
  | _ -> failwith "Unknown block"

let maze = Bytes.make (4 * s) ' '
let () =
  for y = 0 to n-1 do
    Bytes.blit ~src:(read_line ()) ~src_pos:0 ~dst:maze ~dst_pos:(y * m) ~len:m
  done;
  for i = s to 4 * s - 1 do
    maze.[i] <- rotate maze.[i-s]
  done

let read_coords () =
  read_line ()
  |> Str.(split (regexp " "))
  |> List.map ~f:(fun s -> int_of_string s - 1)
  (* Discovered that (X,Y) are named (Y,X) in problem! *)
  |> fun [y; x] -> y * m + x

let start = read_coords ()
let goal = read_coords ()

let default d = function
  | Some x -> x
  | None -> d

module Int = struct
  type t = int
  let compare = compare
end

module Vertex =
  struct
    type t = vertex
    let compare = compare
  end

module PriorityQueue(Priority : Map.OrderedType) =
  struct
    module PriorityMap = Map.Make(Priority)

    let create = ref PriorityMap.empty

    let add prio elt pq =
      let queue =
        if PriorityMap.mem prio !pq then
          PriorityMap.find prio !pq
        else
          let q = Queue.create () in
          pq := PriorityMap.add prio q !pq;
          q in
      Queue.add elt queue

    let pop pq =
      if PriorityMap.is_empty !pq then
        None
      else
        let prio, queue = PriorityMap.min_binding !pq in
        let r = Queue.pop queue in
        if Queue.is_empty queue then
          pq := PriorityMap.remove prio !pq;
        Some r
  end

module Graph =
  struct
    module PriorityVertex =
      struct
        type t = int * Vertex.t
        let compare = compare
      end

    module VertexSet = Set.Make(Vertex)

    module VertexQueue = PriorityQueue(Int)

    let astar ?(heuristic = fun v -> 0) ~edges ~start ~is_goal =
      let edge_length = 1 in
      let marks = Bytes.make (4*m*n) ' ' in
      let fringe = VertexQueue.create in
      VertexQueue.add (heuristic start) (start, 0) fringe;
      let rec go () =
        match VertexQueue.pop fringe with
        | None -> None
        | Some (v, dist) ->
           if is_goal v then
             Some dist
           else if marks.[v] = '*' then
             go ()
           else
             let dist' = dist + edge_length in
             marks.[v] <- '*';
             List.iter
               ~f:(fun u ->
                   if marks.[u] <> '*' then
                     VertexQueue.add (dist' + heuristic u) (u, dist') fringe)
               (edges v);
             go () in
      go ()
  end

let edges v =
  let c = maze.[v] in
  let pl, pu, pr, pd = "+-<URD", "+|^RDL", "+->DLU", "+|vLUR" in
  let sc = String.contains in
  let xy = v mod s in
  let x = xy mod m and y = xy / m in
  let r = ref [(v + s) mod (4 * s)] in
  if x > 0 && sc pl c && sc pr maze.[v-1] then
    r := v-1 :: !r;
  if y > 0 && sc pu c && sc pd maze.[v-m] then
    r := v-m :: !r;
  if x < m-1 && sc pr c && sc pl maze.[v+1] then
    r := v+1 :: !r;
  if y < n-1 && sc pd c && sc pu maze.[v+m] then
    r := v+m :: !r;
  !r

let is_goal v = (v - goal) mod s = 0

let heuristic v =
  let xy = v mod s in
  let dx = xy mod m - goal mod m and dy = xy/m - goal/m in
  abs dx + abs dy

let () =
  Graph.astar ~heuristic ~edges ~start ~is_goal
  |> default (-1)
  |> Printf.printf "%d\n"

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))

let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)

let () =
  let (n,m) = read_pair () in
  let lab_str = Array.init n (fun _ -> read_string()) in
  let (xt,yt) = read_pair() in
  let (xt,yt) = (xt-1, yt-1) in
  let (xm,ym) = read_pair() in
  let (xm,ym) = (xm-1, ym-1) in

  let vt = Array.make_matrix n m 0 in

  let visited (i,j,r) = vt.(i).(j) land (1 lsl r) <> 0 in
  let visit (i,j,r) = vt.(i).(j) <- vt.(i).(j) lor (1 lsl r) in

  let lab = Array.make_matrix n m [||] in

  for i=0 to n-1 do
    for j=0 to m-1 do
      lab.(i).(j) <-
	match lab_str.(i).[j] with
	  | '+' -> [|1;1;1;1|]
	  | '-' -> [|1;0;1;0|]
	  | '|' -> [|0;1;0;1|]
	  | '^' -> [|0;1;0;0|]
	  | '>' -> [|1;0;0;0|]
	  | '<' -> [|0;0;1;0|]
	  | 'v' -> [|0;0;0;1|]
	  | 'L' -> [|1;1;0;1|]
	  | 'R' -> [|0;1;1;1|]
	  | 'U' -> [|1;0;1;1|]
	  | 'D' -> [|1;1;1;0|]
	  | '*' -> [|0;0;0;0|]
	  | _ -> failwith "bad input"
    done
  done;

  let out_bounds i j = i < 0 || j < 0 || i > n-1 || j > m-1 in

  let neighbors (i,j,r) =
    List.fold_left (fun ac (di,dj,s0) ->
      if lab.(i).(j).((s0+r) mod 4) = 0 then ac
      else if out_bounds (i+di) (j+dj) then ac else
	let s1 = (r + s0 + 2) mod 4 in
	if lab.(i+di).(j+dj).(s1) = 0 then ac else (i+di, j+dj, r)::ac
    ) [(i, j, (r+1) mod 4)] [(-1,0,1);(1,0,3);(0,-1,2);(0,1,0)]
  in

  let rec bfs nodes level = if nodes = [] then None else (
    let new_nodes = List.fold_left (fun ac x ->
      List.fold_left (fun ac y ->
	if visited y then ac else (visit y; y::ac)
      ) ac (neighbors x)
    ) [] nodes in
    if visited (xm,ym,0) || visited (xm,ym,1) || visited (xm,ym,2) || visited (xm,ym,3)
    then Some (level+1) else bfs new_nodes (level+1)
  ) in

  visit (xt,yt,0);

  let answer =
    if (xm,ym) = (xt,yt) then 0
    else match bfs [(xt,yt,0)] 0 with None -> -1 | Some level -> level
  in

  printf "%d\n" answer


Dima has a birthday soon! It's a big day! Saryozha's present to Dima is that Seryozha won't be in the room and won't disturb Dima and Inna as they celebrate the birthday. Inna's present to Dima is a stack, a queue and a deck.Inna wants her present to show Dima how great a programmer he is. For that, she is going to give Dima commands one by one. There are two types of commands:  Add a given number into one of containers. For the queue and the stack, you can add elements only to the end. For the deck, you can add elements to the beginning and to the end.  Extract a number from each of at most three distinct containers. Tell all extracted numbers to Inna and then empty all containers. In the queue container you can extract numbers only from the beginning. In the stack container you can extract numbers only from the end. In the deck number you can extract numbers from the beginning and from the end. You cannot extract numbers from empty containers. Every time Dima makes a command of the second type, Inna kisses Dima some (possibly zero) number of times. Dima knows Inna perfectly well, he is sure that this number equals the sum of numbers he extracts from containers during this operation.As we've said before, Dima knows Inna perfectly well and he knows which commands Inna will give to Dima and the order of the commands. Help Dima find the strategy that lets him give as more kisses as possible for his birthday!

The first line contains integer n (1 ≤ n ≤ 105) — the number of Inna's commands. Then n lines follow, describing Inna's commands. Each line consists an integer:   Integer a (1 ≤ a ≤ 105) means that Inna gives Dima a command to add number a into one of containers.  Integer 0 shows that Inna asks Dima to make at most three extractions from different containers.

Each command of the input must correspond to one line of the output — Dima's action. For the command of the first type (adding) print one word that corresponds to Dima's choice:   pushStack — add to the end of the stack;  pushQueue — add to the end of the queue;  pushFront — add to the beginning of the deck;  pushBack — add to the end of the deck.  For a command of the second type first print an integer k (0 ≤ k ≤ 3), that shows the number of extract operations, then print k words separated by space. The words can be:   popStack — extract from the end of the stack;  popQueue — extract from the beginning of the line;  popFront — extract from the beginning from the deck;  popBack — extract from the end of the deck.  The printed operations mustn't extract numbers from empty containers. Also, they must extract numbers from distinct containers. The printed sequence of actions must lead to the maximum number of kisses. If there are multiple sequences of actions leading to the maximum number of kisses, you are allowed to print any of them.

0
pushStack
1 popStack
pushStack
pushQueue
2 popStack popQueue
pushStack
pushQueue
pushFront
3 popStack popQueue popFront

let (|>) x f = f x ;;
let (@@) f x = f x ;;

let ident x = x ;;
let ident2 x y = (x, y) ;;
let ident3 x y z = (x, y, z) ;;
let ident4 x y z w = (x, y, z, w) ;;
let ident5 x y z w v = (x, y, z, w, v) ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

module S = Set.Make (struct
  type t = int * int
  let compare ((i, x) : t) ((j, y) : t) = compare (x, i) (y, j)
end);;

let () =
  let n = Scanf.scanf "%d " ident in
  let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d " ident :: acc) |> List.rev in
  let command = Array.create n `push_back in
  let rec iter next rest = function
  | comm :: comms when comm = 0 ->
    if S.cardinal rest = 0 then begin
      command.(next) <- `command0;
      iter (next + 1) rest comms
    end else if S.cardinal rest = 1 then begin
      let [i, m] = S.elements rest in
      command.(i) <- `push_stack;
      command.(next) <- `command1 (`stack);
      iter (next + 1) S.empty comms
    end else if S.cardinal rest = 2 then begin
      let [i1, m1; i2, m2] = S.elements rest in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(next) <- `command2 (`stack, `queue);
      iter (next + 1) S.empty comms
    end else begin
      let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->
        let m = S.max_elt set in
        (m :: acc, S.remove m set)) in
      let [i1, _; i2, _; i3, _] = maxs in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(i3) <- `push_front;
      command.(next) <- `command3 (`stack, `queue, `deck);
      iter (next + 1) S.empty comms
    end
  | comm :: comms ->
    iter (next + 1) (S.add (next, comm) rest) comms
  | [] -> () in
  iter 0 S.empty comm;
  Array.iter command ~f:(function
  | `push_back -> print_endline "pushBack"
  | `push_front -> print_endline "pushFront"
  | `push_stack -> print_endline "pushStack"
  | `push_queue -> print_endline "pushQueue"
  | `command0 -> print_endline "0"
  | `command1 _ -> print_endline "1 popStack"
  | `command2 _ -> print_endline "2 popStack popQueue"
  | `command3 _ -> print_endline "3 popStack popQueue popFront")
;;

let (|>) x f = f x ;;
let (@@) f x = f x ;;

let ident x = x ;;
let ident2 x y = (x, y) ;;
let ident3 x y z = (x, y, z) ;;
let ident4 x y z w = (x, y, z, w) ;;
let ident5 x y z w v = (x, y, z, w, v) ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

module S = Set.Make (struct
  type t = int * int
  let compare ((_, x) : t) ((_, y) : t) = compare x y
end);;

let () =
  let n = Scanf.scanf "%d " ident in
  let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d " ident :: acc) |> List.rev in
  let command = Array.create n `push_back in
  let rec iter next rest = function
  | comm :: comms when comm = 0 ->
    if S.cardinal rest = 0 then begin
      command.(next) <- `command0;
      iter (next + 1) rest comms
    end else if S.cardinal rest = 1 then begin
      let [i, m] = S.elements rest in command.(i) <- `push_stack;
      command.(next) <- `command1 (`stack);
      iter (next + 1) (S.remove (i, m) rest) comms
    end else if S.cardinal rest = 2 then begin
      let [i1, m1; i2, m2] = S.elements rest in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(next) <- `command2 (`stack, `queue);
      iter (next + 1) (S.remove (i1, m1) (S.remove (i2, m2) rest)) comms
    end else begin
      let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->
        let m = S.max_elt set in
        (m :: acc, S.remove m set)) in
      let [i1, _; i2, _; i3, _] = maxs in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(i3) <- `push_front;
      command.(next) <- `command3 (`stack, `queue, `deck);
      iter (next + 1) rest comms
    end
  | comm :: comms ->
    iter (next + 1) (S.add (next, comm) rest) comms
  | [] -> () in
  iter 0 S.empty comm;
  Array.iter command ~f:(function
  | `push_back -> print_endline "pushBack"
  | `push_front -> print_endline "pushFront"
  | `push_stack -> print_endline "pushStack"
  | `push_queue -> print_endline "pushQueue"
  | `command0 -> print_endline "0"
  | `command1 _ -> print_endline "1 popStack"
  | `command2 _ -> print_endline "2 popStack popQueue"
  | `command3 _ -> print_endline "3 popStack popQueue popFront")
;;

let (|>) x f = f x ;;
let (@@) f x = f x ;;

let ident x = x ;;
let ident2 x y = (x, y) ;;
let ident3 x y z = (x, y, z) ;;
let ident4 x y z w = (x, y, z, w) ;;
let ident5 x y z w v = (x, y, z, w, v) ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

module S = Set.Make (struct
  type t = int * int
  let compare ((i, x) : t) ((j, y) : t) = compare (x, i) (y, j)
end);;

let () =
  let n = Scanf.scanf "%d " ident in
  let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d " ident :: acc) |> List.rev in
  let command = Array.create n `push_back in
  let rec iter next rest = function
  | comm :: comms when comm = 0 ->
    if S.cardinal rest = 0 then begin
      command.(next) <- `command0;
      iter (next + 1) rest comms
    end else if S.cardinal rest = 1 then begin
      let [i, m] = S.elements rest in command.(i) <- `push_stack;
      command.(next) <- `command1 (`stack);
      iter (next + 1) (S.remove (i, m) rest) comms
    end else if S.cardinal rest = 2 then begin
      let [i1, m1; i2, m2] = S.elements rest in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(next) <- `command2 (`stack, `queue);
      iter (next + 1) (S.remove (i1, m1) (S.remove (i2, m2) rest)) comms
    end else begin
      let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->
        let m = S.max_elt set in
        (m :: acc, S.remove m set)) in
      let [i1, _; i2, _; i3, _] = maxs in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(i3) <- `push_front;
      command.(next) <- `command3 (`stack, `queue, `deck);
      iter (next + 1) rest comms
    end
  | comm :: comms ->
    iter (next + 1) (S.add (next, comm) rest) comms
  | [] -> () in
  iter 0 S.empty comm;
  Array.iter command ~f:(function
  | `push_back -> print_endline "pushBack"
  | `push_front -> print_endline "pushFront"
  | `push_stack -> print_endline "pushStack"
  | `push_queue -> print_endline "pushQueue"
  | `command0 -> print_endline "0"
  | `command1 _ -> print_endline "1 popStack"
  | `command2 _ -> print_endline "2 popStack popQueue"
  | `command3 _ -> print_endline "3 popStack popQueue popFront")
;;

let (|>) x f = f x ;;
let (@@) f x = f x ;;

let ident x = x ;;
let ident2 x y = (x, y) ;;
let ident3 x y z = (x, y, z) ;;
let ident4 x y z w = (x, y, z, w) ;;
let ident5 x y z w v = (x, y, z, w, v) ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

module S = Set.Make (struct
  type t = int * int
  let compare ((i, x) : t) ((j, y) : t) = compare (x, i) (y, j)
end);;

let () =
  let n = Scanf.scanf "%d " ident in
  let comm = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d " ident :: acc) |> List.rev in
  let command = Array.create n `push_back in
  let rec iter next rest = function
  | comm :: comms when comm = 0 ->
    if S.cardinal rest = 0 then begin
      command.(next) <- `command0;
      iter (next + 1) rest comms
    end else if S.cardinal rest = 1 then begin
      let [i, m] = S.elements rest in
      command.(i) <- `push_stack;
      command.(next) <- `command1 (`stack);
      iter (next + 1) S.empty comms
    end else if S.cardinal rest = 2 then begin
      let [i1, m1; i2, m2] = S.elements rest in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(next) <- `command2 (`stack, `queue);
      iter (next + 1) S.empty comms
    end else begin
      let (maxs, rest) = fold_for 0 3 ~init:([], rest) ~f:(fun (acc, set) i ->
        let m = S.max_elt set in
        (m :: acc, S.remove m set)) in
      let [i1, _; i2, _; i3, _] = maxs in
      command.(i1) <- `push_stack;
      command.(i2) <- `push_queue;
      command.(i3) <- `push_front;
      command.(next) <- `command3 (`stack, `queue, `deck);
      iter (next + 1) rest comms
    end
  | comm :: comms ->
    iter (next + 1) (S.add (next, comm) rest) comms
  | [] -> () in
  iter 0 S.empty comm;
  Array.iter command ~f:(function
  | `push_back -> print_endline "pushBack"
  | `push_front -> print_endline "pushFront"
  | `push_stack -> print_endline "pushStack"
  | `push_queue -> print_endline "pushQueue"
  | `command0 -> print_endline "0"
  | `command1 _ -> print_endline "1 popStack"
  | `command2 _ -> print_endline "2 popStack popQueue"
  | `command3 _ -> print_endline "3 popStack popQueue popFront")
;;


Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simultaneously. There are two states for each skewer: initial and turned over.This time Miroslav laid out $$$n$$$ skewers parallel to each other, and enumerated them with consecutive integers from $$$1$$$ to $$$n$$$ in order from left to right. For better cooking, he puts them quite close to each other, so when he turns skewer number $$$i$$$, it leads to turning $$$k$$$ closest skewers from each side of the skewer $$$i$$$, that is, skewers number $$$i - k$$$, $$$i - k + 1$$$, ..., $$$i - 1$$$, $$$i + 1$$$, ..., $$$i + k - 1$$$, $$$i + k$$$ (if they exist). For example, let $$$n = 6$$$ and $$$k = 1$$$. When Miroslav turns skewer number $$$3$$$, then skewers with numbers $$$2$$$, $$$3$$$, and $$$4$$$ will come up turned over. If after that he turns skewer number $$$1$$$, then skewers number $$$1$$$, $$$3$$$, and $$$4$$$ will be turned over, while skewer number $$$2$$$ will be in the initial position (because it is turned again).As we said before, the art of cooking requires perfect timing, so Miroslav wants to turn over all $$$n$$$ skewers with the minimal possible number of actions. For example, for the above example $$$n = 6$$$ and $$$k = 1$$$, two turnings are sufficient: he can turn over skewers number $$$2$$$ and $$$5$$$.Help Miroslav turn over all $$$n$$$ skewers.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 1000$$$, $$$0 \leq k \leq 1000$$$) — the number of skewers and the number of skewers from each side that are turned in one step.

The first line should contain integer $$$l$$$ — the minimum number of actions needed by Miroslav to turn over all $$$n$$$ skewers. After than print $$$l$$$ integers from $$$1$$$ to $$$n$$$ denoting the number of the skewer that is to be turned over at the corresponding step.

NoteIn the first example the first operation turns over skewers $$$1$$$, $$$2$$$ and $$$3$$$, the second operation turns over skewers $$$4$$$, $$$5$$$, $$$6$$$ and $$$7$$$.In the second example it is also correct to turn over skewers $$$2$$$ and $$$5$$$, but turning skewers $$$2$$$ and $$$4$$$, or $$$1$$$ and $$$5$$$ are incorrect solutions because the skewer $$$3$$$ is in the initial state after these operations.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done
	let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
end open MyInt64

let repm from_ to_ m_init fbod =
	let i,f,m = ref ~|from_,ref true,ref m_init in
	while !i <= ~|to_ && !f do
		match fbod (~~| !i) !m with
		| `Break -> f := false
		| `Break_m m' -> (f := false; m := m')
		| `Ok m' -> (i := !i +$ 1; m := m')
	done; !m

let () =
	let n,k = get_2_i64 0 in
	(
		if n <= k then [0L]
		else if k=0L then (
			let l = ref [] in
			for i=0 to (~|n -$ 1) do
				l := (~~|i)::!l
			done;
			!l |> List.rev
		)
		else if n <= 2L*k+1L then [n-k-1L]
		else if n <= 3L*k+1L then (
			let ll = n / 2L
			(* in printf "  lr: %Ld, %Ld\n" ll (n-ll); *)
			in
			let pl,pr = ll - k - 1L, ll + k
			in
			[pl;pr]
		)
		else (
			let q = n / (2L*k+1L) in let r = n - q * (2L*k+1L) in
			(* printf "  %Ld, %Ld\n" q r; *)
			let q,r = if r <= k then (q-1L,r+(2L*k+1L)) else (q,r)
			(* in printf "  %Ld, %Ld\n" q r; *)
			in
			let w = 2L*k+1L in
			if r = 2L*k+1L then (
				let s = ref k in
				let l = ref [k] in
				while !s <= n - w do
					s += (2L*k+1L);
					l := !s::!l;
				done; !l |> List.rev
			)
			else if r < 2L*k+1L then (
				let s,l = ref (r-k-1L), ref [r-k-1L] in
				while !s < n - w do
					s += (2L*k+1L);
					l := !s::!l;
				done; !l |> List.rev
			)
			else (
				let ll = r / 2L in
				let s,l = ref (ll-k-1L), ref [ll-k-1L] in
				while !s < n - w - (r - ll) do
					s += (2L*k+1L);
					l := !s::!l;
				done;
				l := (n-(r-ll)+k)::!l;
				!l |> List.rev
			)
		)
	)
	|> (fun v ->
		let v = List.map ((+) 1L) v in
		let l = List.length v in
		printf "%d\n%s\n" l (string_of_list ~separator:" " Int64.to_string v)
	)

	(* let p =
		(Int64.to_float n) /. (Int64.to_float @@ 2L*k+1L)
		|> ceil
		|> Int64.of_float
	in *)


Ari the monster is not an ordinary monster. She is the hidden identity of Super M, the Byteforces’ superhero. Byteforces is a country that consists of n cities, connected by n - 1 bidirectional roads. Every road connects exactly two distinct cities, and the whole road system is designed in a way that one is able to go from any city to any other city using only the given roads. There are m cities being attacked by humans. So Ari... we meant Super M have to immediately go to each of the cities being attacked to scare those bad humans. Super M can pass from one city to another only using the given roads. Moreover, passing through one road takes her exactly one kron - the time unit used in Byteforces.   However, Super M is not on Byteforces now - she is attending a training camp located in a nearby country Codeforces. Fortunately, there is a special device in Codeforces that allows her to instantly teleport from Codeforces to any city of Byteforces. The way back is too long, so for the purpose of this problem teleportation is used exactly once.You are to help Super M, by calculating the city in which she should teleport at the beginning in order to end her job in the minimum time (measured in krons). Also, provide her with this time so she can plan her way back to Codeforces.

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 123456) - the number of cities in Byteforces, and the number of cities being attacked respectively. Then follow n - 1 lines, describing the road system. Each line contains two city numbers ui and vi (1 ≤ ui, vi ≤ n) - the ends of the road i. The last line contains m distinct integers - numbers of cities being attacked. These numbers are given in no particular order.

First print the number of the city Super M should teleport to. If there are many possible optimal answers, print the one with the lowest city number. Then print the minimum possible time needed to scare all humans in cities being attacked, measured in Krons. Note that the correct answer is always unique.

NoteIn the first sample, there are two possibilities to finish the Super M's job in 3 krons. They are: and .However, you should choose the first one as it starts in the city with the lower number.

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let n = read_int () in
  let m = read_int () in

  let tree = Array.make n [] in

  let add_edge (u,v) =
    tree.(u) <- v::tree.(u);
    tree.(v) <- u::tree.(v);
  in

  for i=0 to n-2 do
    let u = read_int() -1 in
    let v = read_int() -1 in
    add_edge (u,v)
  done;

  let mark = Array.make n false in
  let marked = Array.init m (fun _ -> read_int()-1) in
  let start = marked.(0) in

  for i=0 to m-1 do
    mark.(marked.(i)) <- true
  done;

  let child = Array.make n [] in

  let rec dfs p u =
    List.iter (fun v -> if v<>p then (
      child.(u) <- v::child.(u);
      dfs u v
    )) tree.(u)
  in

  dfs (-1) start;

  let child1 = Array.make n [] in

  let rec dfs_mark u =
    let me = if mark.(u) then 1 else 0 in
    me + List.fold_left (fun ac v ->
      let c = dfs_mark v in
      if c <> 0 then child1.(u) <- v::child1.(u);
      c+ac
    ) 0 child.(u)
  in

  if dfs_mark start <> m then failwith "wrong number of marked nodes";

  let rec dfs_size u =
    1 + List.fold_left (fun ac v -> ac + dfs_size v) 0 child1.(u)
  in

  let nnodes = dfs_size start in

  let data = Array.make n ((0,0),(0,(0,0))) in
   (*   (depth, min_node_achieving it, farthest_pair_dist, (pair achieving it))
   *)

  let rec dfs_score u =
    let d = List.length child1.(u) in
    if d=0 then (
      data.(u) <- ((0,u),(0,(u,u)));
      if not mark.(u) then failwith "should have been marked"
    )
    else
      let depth = Array.make d (0,0) in
      let farthest = Array.make d (0,(0,0)) in
      List.iteri (fun i v ->
	dfs_score v;
	let (dep,f) = data.(v) in
	depth.(i) <- dep;
	farthest.(i) <- f
      ) child1.(u);
      let comp (d1,di1) (d2,di2) = compare (-d1,di1) (-d2,di2) in
      Array.sort comp depth;
      Array.sort comp farthest;
      if d=1 then
	let (d0,d0i) = depth.(0) in
	let opt1 = farthest.(0)	in
	let opt3 = if not mark.(u) then opt1 else (d0+1, (min d0i u, max d0i u)) in
	let opts = List.sort comp [opt1; opt3] in
	data.(u) <- ((d0+1,d0i), List.hd opts);
      else
	let (d0,d0i) = depth.(0) in
	let (d1,d1i) = depth.(1) in
	let opt1 = farthest.(0) in
	let opt2 = (d0 + d1 + 2, (min d0i d1i, max d0i d1i)) in
	let opt3 = if not mark.(u) then opt2 else (d0+1, (min d0i u, max d0i u)) in
	let opts = List.sort comp [opt1; opt2; opt3] in
	data.(u) <- ((d0+1,d0i), List.hd opts)
  in

  dfs_score start;

  let (_, (farthest, (v0,v1))) = data.(start) in

  (*
  printf "start = %d  nnodes = %d  farthest = %d  (v0,v1) = (%d,%d)\n" start nnodes farthest v0 v1;
  *)
  let answer = (nnodes - 1) * 2 - farthest in
  printf "%d\n" (v0+1);
  printf "%d\n" answer


Ksusha the Squirrel is standing at the beginning of a straight road, divided into n sectors. The sectors are numbered 1 to n, from left to right. Initially, Ksusha stands in sector 1. Ksusha wants to walk to the end of the road, that is, get to sector n. Unfortunately, there are some rocks on the road. We know that Ksusha hates rocks, so she doesn't want to stand in sectors that have rocks.Ksusha the squirrel keeps fit. She can jump from sector i to any of the sectors i + 1, i + 2, ..., i + k. Help Ksusha! Given the road description, say if she can reach the end of the road (note, she cannot stand on a rock)?

The first line contains two integers n and k (2 ≤ n ≤ 3·105, 1 ≤ k ≤ 3·105). The next line contains n characters — the description of the road: the i-th character equals ".", if the i-th sector contains no rocks. Otherwise, it equals "#". It is guaranteed that the first and the last characters equal ".".

Print "YES" (without the quotes) if Ksusha can reach the end of the road, otherwise print "NO" (without the quotes).

open List
open Printf
open Scanf
open String

let inf= 1070000000;;

let rec getlist n =
	if n=0 then []
	else scanf " %d" (fun x->x)::getlist (n-1);;

let min a b = if a<b then a else b;;

let rec min_ a =
	if a=[] then inf
	else min (hd a) (min_ (tl a));;

let rec ok n k s cur rock =
	if rock=k then false
	else if cur=n then true
	else if s.[cur]='#' then ok n k s (cur+1) (rock+1)
	else ok n k s (cur+1) 0;;

let solve n k s =
	if ok n k s 0 0 then printf "YES\n"
	else printf "NO\n"
in scanf "%d %d %s" solve;;


In 2013, the writers of Berland State University should prepare problems for n Olympiads. We will assume that the Olympiads are numbered with consecutive integers from 1 to n. For each Olympiad we know how many members of the jury must be involved in its preparation, as well as the time required to prepare the problems for her. Namely, the Olympiad number i should be prepared by pi people for ti days, the preparation for the Olympiad should be a continuous period of time and end exactly one day before the Olympiad. On the day of the Olympiad the juries who have prepared it, already do not work on it.For example, if the Olympiad is held on December 9th and the preparation takes 7 people and 6 days, all seven members of the jury will work on the problems of the Olympiad from December, 3rd to December, 8th (the jury members won't be working on the problems of this Olympiad on December 9th, that is, some of them can start preparing problems for some other Olympiad). And if the Olympiad is held on November 3rd and requires 5 days of training, the members of the jury will work from October 29th to November 2nd.In order not to overload the jury the following rule was introduced: one member of the jury can not work on the same day on the tasks for different Olympiads. Write a program that determines what the minimum number of people must be part of the jury so that all Olympiads could be prepared in time.

The first line contains integer n — the number of Olympiads in 2013 (1 ≤ n ≤ 100). Each of the following n lines contains four integers mi, di, pi and ti — the month and day of the Olympiad (given without leading zeroes), the needed number of the jury members and the time needed to prepare the i-th Olympiad (1 ≤ mi ≤ 12, di ≥ 1, 1 ≤ pi, ti ≤ 100), di doesn't exceed the number of days in month mi. The Olympiads are given in the arbitrary order. Several Olympiads can take place in one day. Use the modern (Gregorian) calendar in the solution. Note that all dates are given in the year 2013. This is not a leap year, so February has 28 days. Please note, the preparation of some Olympiad can start in 2012 year.

Print a single number — the minimum jury size.

let chan = Scanf.Scanning.from_file "input.txt"
let read_int () = Scanf.bscanf chan " %d" (fun x -> x)

let ochan = open_out "output.txt"
let print_string s = Printf.fprintf ochan "%s" s

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

let h = Array.make 1000 0
let offset = 500

let day_number m d =
  let dpm = [|31;28;31;30;31;30;31;31;30;31;30;31|] in
  let md = sum 0 (m-2) (fun i->dpm.(i)) in
    md + (d-1)

let () =
  let n = read_int() in
    for i=1 to n do
      let m = read_int() in
      let d = read_int() in
      let p = read_int() in
      let t = read_int() in
      let dn = day_number m d in
    for j=dn-t to dn-1 do
      h.(j+offset) <- h.(j+offset) + p
    done;
    done;
    print_string (Printf.sprintf "%d\n" (maxf 0 999 (fun i-> h.(i))))

let chan = Scanf.Scanning.from_file "input.txt"
let read_int () = Scanf.bscanf chan " %d " (fun x -> x)

let ochan = open_out "output.txt"
let print_string s = Printf.fprintf ochan "%s" s

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

let h = Array.make 1000 0
let offset = 500

let day_number m d =
  let dpm = [|31;28;31;30;31;30;31;31;30;31;30;31|] in
  let md = sum 0 (m-2) (fun i->dpm.(i)) in
    md + (d-1)

let () =
  let n = read_int() in
    for i=1 to n do
      let m = read_int() in
      let d = read_int() in
      let p = read_int() in
      let t = read_int() in
      let dn = day_number m d in
    for j=dn-t to dn-1 do
      h.(j+offset) <- h.(j+offset) + p
    done;
    done;
    print_string (Printf.sprintf "%d\n" (maxf 0 999 (fun i-> h.(i))))

let input = open_in "input.txt" ;;
let output = open_out "output.txt" ;;

let read_int () = Scanf.fscanf input " %d " (fun x -> x) ;;

let n = read_int () ;;

let olympiads =
    let rec loop i f =
        if i = n then f []
        else let m = read_int () and d = read_int () and
                 p = read_int () and t = read_int ()
        in loop (i + 1) (fun l -> f ((m, d, p, t) :: l))
    in loop 0 (fun x -> x) ;;

(* Create a cumulative array of days since January 1, 2012 for the year 2013 *)
let months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|]
let cumulative_days = Array.make 13 366 ;;
for i = 1 to 12 do
    cumulative_days.(i) <- months.(i) + cumulative_days.(i - 1)
done ;;

let start m d t = cumulative_days.(m - 1) + d - t ;;

let olympiads =
    let compare (m1, d1, p1, t1) (m2, d2, p2, t2) =
        (start m1 d1 t1) - (start m2 d2 t2)
    in List.sort compare olympiads ;;

let jury_size olympiads =
    let rec loop oly intersection size = match oly with
        | [] ->  size
        | (m1, d1, p1, t1) as hd1 :: tl1 ->
            let rec filter l s f = match l with
                | [] -> (s, f [hd1])
                | (m2, d2, p2, t2) as hd2 :: tl2 ->
                    if (start m1 d1 t1) > (start m2 d2 1) then filter tl2 s f
                    else filter tl2 (s + p2) (fun v -> f (hd2 :: v))
            in let (newsize, newinter) = filter intersection p1 (fun x -> x)
            in loop tl1 newinter (max newsize size)
    in loop olympiads [] 0 ;;

Printf.fprintf output "%d\n" (jury_size olympiads);;

let chan = Scanf.Scanning.from_channel (open_in "input.txt")
let read_int () = Scanf.bscanf chan " %d " (fun x -> x)

let ochan = open_out "output.txt"
let print_string s = Printf.fprintf ochan "%s" s

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

let h = Array.make 1000 0
let offset = 500

let day_number m d =
  let dpm = [|31;28;31;30;31;30;31;31;30;31;30;31|] in
  let md = sum 0 (m-2) (fun i->dpm.(i)) in
    md + (d-1)

let () =
  let n = read_int() in
    for i=1 to n do
      let m = read_int() in
      let d = read_int() in
      let p = read_int() in
      let t = read_int() in
      let dn = day_number m d in
	for j=dn-t to dn-1 do
	  h.(j+offset) <- h.(j+offset) + p
	done;
    done;
    print_string (Printf.sprintf "%d\n" (maxf 0 999 (fun i-> h.(i))))


You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains a single string $$$s$$$ ($$$1 \le |s| \le 100$$$, where $$$|s|$$$ is the length of the string $$$s$$$), consisting only of characters a and/or b.

For each test case, print the resulting string $$$s$$$ with $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$ you'll get making the minimum number of steps. If there are multiple answers, print any of them.

NoteIn the first test case, both $$$\operatorname{AB}(s) = 0$$$ and $$$\operatorname{BA}(s) = 0$$$ (there are no occurrences of ab (ba) in b), so can leave $$$s$$$ untouched.In the second test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 2$$$, so you can leave $$$s$$$ untouched. In the third test case, $$$\operatorname{AB}(s) = 1$$$ and $$$\operatorname{BA}(s) = 0$$$. For example, we can change $$$s_1$$$ to b and make both values zero.In the fourth test case, $$$\operatorname{AB}(s) = 2$$$ and $$$\operatorname{BA}(s) = 1$$$. For example, we can change $$$s_6$$$ to a and make both values equal to $$$1$$$.

let solve s =
  (String.make 1 s.[(String.length s - 1)]) ^ String.sub s 1 (String.length s - 1)

let () =
  let tc = Scanf.scanf " %d" (fun x -> x) in
  (let rec loop tc =
    match tc with
    | 0 -> ()
    | _ ->  Printf.printf "%s\n" (solve (Scanf.scanf " %s" (fun x ->x))); loop (tc - 1);
  in loop tc)

let change c =
  char_of_int (int_of_char 'a' + (1 - ((int_of_char c) - (int_of_char 'a'))))

let solve s =
  let rec count s i res =
    if i < String.length s then
      if (s.[i] != s.[i-1])
      then count s (i+1) (res+1)
      else count s (i+1) res
    else res
  in let res = count s 1 0 in
  if (res mod 2) == 1
       then (String.make 1 (change s.[0])) ^ (String.sub s 1 ((String.length s) - 1))
       else s

let () =
  let tc = Scanf.scanf " %d" (fun x -> x) in
  let rec loop tc =
    match tc with
    |0 -> ()
    |_ ->  Printf.printf "%s\n" (solve (Scanf.scanf " %s" (fun x ->x))); loop (tc - 1);
  in loop tc


Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:  a < b < c;  a divides b, b divides c. Naturally, Xenia wants each element of the sequence to belong to exactly one group of three. Thus, if the required partition exists, then it has  groups of three.Help Xenia, find the required partition or else say that it doesn't exist.

The first line contains integer n (3 ≤ n ≤ 99999) — the number of elements in the sequence. The next line contains n positive integers, each of them is at most 7. It is guaranteed that n is divisible by 3.

If the required partition exists, print  groups of three. Print each group as values of the elements it contains. You should print values in increasing order. Separate the groups and integers in groups by whitespaces. If there are multiple solutions, you can print any of them. If there is no solution, print -1.

open Printf
open Scanf
open String
open Array
open List
open Int64

let a = make 8 0;;

let rec read n =
	if n=0 then ()
	else (let x = scanf " %d" (fun y->y)
		in a.(x) <- a.(x)+1; read (n-1));;

let rec print s n =
	if n=0 then ()
	else (printf s; print s (n-1));;

let ok m =
	let n136 = a.(3) in
	let n124 = a.(4) in
	let n126 = m - n136 - n124 in
	if n126 < 0 then false
	else if a.(1) <> m then false
	else if a.(2) <> n124 + n126 then false
	else if a.(6) <> n126 + n136 then false
	else
		(print "1 2 4\n" n124;
		print "1 2 6\n" n126;
		print "1 3 6\n" n136;
		true);;

let solve n =
	read n;
	if not (ok (n/3)) then printf "-1"
	else ()
in scanf "%d" solve;;

let read_int _ = Scanf.scanf " %d" (fun x -> x)
let read_string _ = Scanf.scanf " %s" (fun x -> x)

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

 let implode l =
  let result = String.create (List.length l) in
  let rec imp i = function
  | [] -> result
  | c :: l -> result.[i] <- c; imp (i + 1) l in
  imp 0 l;;

let (--) i j =
  let rec aux n acc =
    if n < i then acc else aux (n-1) (n :: acc)
  in aux j []

  let () =
    let n = read_int () in
    let arr = Array.init n read_int in
    let count = Array.init 8 (fun _ -> 0) in
    let ok = Array.fold_right (fun x ok ->
      if ok = false || (x = 5 || x = 7) then false
      else begin
        count.(x) <- count.(x) + 1;
        true
      end
    ) arr true
    in
    let bad = ref (ok = false) in
    bad := !bad || (count.(1) <> n / 3);
    bad := !bad || (count.(4) + count.(6) <> n / 3);
    bad := !bad || (count.(2) + count.(3) <> n / 3);
    bad := !bad || (count.(3) > count.(6));
    bad := !bad || (count.(2) <> count.(4) + count.(6) - count.(3));
    if !bad then Printf.printf "-1\n"
    else begin
      let limit = count.(3) in
      for i = 1 to limit do
        Printf.printf "1 3 6\n";
        count.(6) <- count.(6) - 1;
      done;
      for i = 1 to count.(4) do
        Printf.printf "1 2 4\n";
      done;
      for i = 1 to count.(6) do
        Printf.printf "1 2 6\n";
      done;
    end

open String
open List
open Printf
open Scanf

let read_int _ = Scanf.scanf " %d" (fun x -> x)
let read_string _ = Scanf.scanf " %s" (fun x -> x)

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

 let implode l =
  let result = String.create (List.length l) in
  let rec imp i = function
  | [] -> result
  | c :: l -> result.[i] <- c; imp (i + 1) l in
  imp 0 l;;

let (--) i j =
  let rec aux n acc =
    if n < i then acc else aux (n-1) (n :: acc)
  in aux j []

  let () =
    let n = read_int () in
    let arr = Array.init n read_int in
    let count = Array.init 8 (fun _ -> 0) in
    let ok = Array.fold_right (fun x ok ->
      if ok = false || (x = 5 || x = 7) then false
      else begin
        count.(x) <- count.(x) + 1;
        true
      end
    ) arr true
    in
    let bad = ref (ok = false) in
    bad := !bad || (count.(1) <> n / 3);
    bad := !bad || (count.(4) + count.(6) <> n / 3);
    bad := !bad || (count.(2) + count.(3) <> n / 3);
    bad := !bad || (count.(2) <> count.(4) + count.(6) - count.(3));
    if !bad then Printf.printf "-1\n"
    else begin
      let limit = count.(3) in
      for i = 1 to limit do
        Printf.printf "1 3 6\n";
        count.(6) <- count.(6) - 1;
      done;
      for i = 1 to count.(4) do
        Printf.printf "1 2 4\n";
      done;
      for i = 1 to count.(6) do
        Printf.printf "1 2 6\n";
      done;
    end


Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.In the evening Noku is going to take a look at the night sky. He would like to find three distinct stars and form a triangle. The triangle must have positive area. In addition, all other stars must lie strictly outside of this triangle. He is having trouble finding the answer and would like your help. Your job is to find the indices of three stars that would form a triangle that satisfies all the conditions. It is guaranteed that there is no line such that all stars lie on that line. It can be proven that if the previous condition is satisfied, there exists a solution to this problem.

The first line of the input contains a single integer n (3 ≤ n ≤ 100 000). Each of the next n lines contains two integers xi and yi ( - 109 ≤ xi, yi ≤ 109). It is guaranteed that no two stars lie at the same point, and there does not exist a line such that all stars lie on that line.

Print three distinct integers on a single line — the indices of the three points that form a triangle that satisfies the conditions stated in the problem. If there are multiple possible answers, you may print any of them.

NoteIn the first sample, we can print the three indices in any order.In the second sample, we have the following picture.   Note that the triangle formed by starts 1, 4 and 3 doesn't satisfy the conditions stated in the problem, as point 5 is not strictly outside of this triangle (it lies on it's border).

let dist (a,b) (c,d) =
   let x = a -. c and y = b -. d in
      sqrt (x *. x +. y *. y)

let not_in_line (a,b) (c,d) (e,f) =
   let (w,x) = (c -. a,d -. b) and (y,z) = (e -. a,f -. b) in
       abs_float (w *. z -. x *. y) > 0.0000001

(*
let f ((a,a')::(b,b')::q) =
   let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in
   let i = ref 0 and d = ref max_float in
      List.iteri (fun j x -> let d' = dist m x n  if d' < !d && not_in_line x (a,a') (b,b') then (i := j; d := d')) q;
      3 + !i;;

Scanf.scanf "%d" (fun n ->
let l = ref [] in
   prerr_endline "coucou";
   for i=1 to n do
      Scanf.scanf " %f %f" (fun a b -> l := (a,b)::!l);
   done;
      Printf.printf "1 2 %d" (f (List.rev !l)))
*)

let f (t::q) =
   let i = ref 0 and y = ref (0. , 0.) and d = ref max_float in
      List.iteri (fun j x -> let d' = dist t x in if d' < !d then (i := j; d := d'; y := x)) q;
   let j = ref 0 and z = ref (0. , 0.) and d = ref max_float in
      List.iteri (fun k x -> let d' = dist t x in if d' < !d && not_in_line x !y t && k <> !i then (j := k; d := d'; z := x)) q;
       (!i + 2,!j + 2);;

Scanf.scanf "%d" (fun n ->
let l = ref [] in
   for i=1 to n do
      Scanf.scanf " %f %f" (fun a b -> l := (a,b)::!l);
   done;
   let (a,b) = (f (List.rev !l)) in
      Printf.printf "1 %d %d" a b)

let dist (a,b) (c,d) =
   let x = a -. c and y = b -. d in
      sqrt (x *. x +. y *. y)

let not_in_line (a,b) (c,d) (e,f) =
   let (w,x) = (c -. a,d -. b) and (y,z) = (e -. a,f -. b) in
       abs_float (w *. z -. x *. y) > 0.0000001

let f ((a,a')::(b,b')::q) =
   let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in
   let i = ref 0 and d = ref max_float in
      List.iteri (fun j x -> let d' = dist m x in if d' < !d && not_in_line x (a,a') (b,b') then (i := j; d := d')) q;
      3 + !i;;

Scanf.scanf "%d" (fun n ->
let l = ref [] in
   prerr_endline "coucou";
   for i=1 to n do
      Scanf.scanf " %f %f" (fun a b -> l := (a,b)::!l);
   done;
      Printf.printf "1 2 %d" (f (List.rev !l)))

let dist (a,b) (c,d) =
   let x = a -. c and y = b -. d in
      sqrt (x *. x +. y *. y)

let not_in_line (a,b) (c,d) (e,f) =
   let (w,x) = (c -. a,d -. b) and (y,z) = (e -. a,f -. b) in
       w *. z -. x *. y <> 0.

let f ((a,a')::(b,b')::q) =
   let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in
   let i = ref 0 and d = ref max_float in
      List.iteri (fun j x -> let d' = dist m x in if d' < !d && not_in_line x (a,a') (b,b') then (i := j; d := d')) q;
      3 + !i;;

Scanf.scanf "%d" (fun n ->
let l = ref [] in
   for i=1 to n do
      Scanf.scanf " %f %f" (fun a b -> l := (a,b)::!l);
   done;
      Printf.printf "1 2 %d" (f (List.rev !l)))

let dist (a,b) (c,d) =
   let x = a -. c and y = b -. d in
      sqrt (x *. x +. y *. y)

let f ((a,a')::(b,b')::q) =
   let m = ((a +. b) /. 2.,(a' +. b') /. 2.) in
   let i = ref 0 and d = ref max_float in
      List.iteri (fun j x -> let d' = dist m x in if d' < !d then (i := j; d := d')) q;
      3 + !i;;

Scanf.scanf "%d" (fun n ->
let l = ref [] in
   for i=1 to n do
      Scanf.scanf " %f %f" (fun a b -> l := (a,b)::!l);
   done;
      Printf.printf "1 2 %d" (f (List.rev !l)))


The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).  If the wind blows to the east, the boat will move to (x + 1, y).  If the wind blows to the south, the boat will move to (x, y - 1).  If the wind blows to the west, the boat will move to (x - 1, y).  If the wind blows to the north, the boat will move to (x, y + 1). Alternatively, they can hold the boat by the anchor. In this case, the boat stays at (x, y). Given the wind direction for t seconds, what is the earliest time they sail to (ex, ey)?

The first line contains five integers t, sx, sy, ex, ey (1 ≤ t ≤ 105,  - 109 ≤ sx, sy, ex, ey ≤ 109). The starting location and the ending location will be different. The second line contains t characters, the i-th character is the wind blowing direction at the i-th second. It will be one of the four possibilities: "E" (east), "S" (south), "W" (west) and "N" (north).

If they can reach (ex, ey) within t seconds, print the earliest time they can achieve it. Otherwise, print "-1" (without quotes).

NoteIn the first sample, they can stay at seconds 1, 3, and move at seconds 2, 4.In the second sample, they cannot sail to the destination.

(* returns the number of elements consumed from xs
   to turn s1 to s2 *)
let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) [] in
let rec gen s1 s2 f ls v = match ls with
   | _ when s1 = s2 -> Some v
   | [] -> None
   | (h::t) -> gen (f s1 h) s2 f t (v+1) in
let next (x,y) = function
   | 'E' when x < 0 -> (x+1,y)
   | 'S' when y > 0 -> (x,y-1)
   | 'W' when x > 0 -> (x-1,y)
   | 'N' when y < 0 -> (x,y+1)
   | _              -> (x,y) in
let out sx sy ex ey wind =
   match gen (sx-ex,sy-ey) (0,0) next (explode wind) 0 with
      | Some v -> v
      | None -> ~-1 in
let ans = Scanf.bscanf Scanf.Scanning.stdin "%d %d %d %d %d %s" (fun _ -> out) in
Printf.printf "%d\n" ans;;


Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 ≤ li ≤ ri ≤ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).

The first line contains four integers n, m, s and f (1 ≤ n, m ≤ 105; 1 ≤ s, f ≤ n; s ≠ f; n ≥ 2). Each of the following m lines contains three integers ti, li, ri (1 ≤ ti ≤ 109, 1 ≤ li ≤ ri ≤ n). It is guaranteed that t1 < t2 < t3 < ... < tm.

Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X". As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.

let read_int _ = Scanf.scanf " %d" (fun x -> x)
let read_string _ = Scanf.scanf " %s" (fun x -> x)

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

let () =
  let n = read_int () in
  let m = read_int () in
  let s = read_int () in
  let f = read_int () in

  let next x = if s < f then (x + 1) else (x - 1) in
  let movement = if s < f then "R" else "L" in
  let bad x l r= x >= l && x <= r in

  let arr = Array.init m (fun _ ->
    let t = read_int () in
    let l = read_int () in
    let r = read_int () in
    (t,l,r))
  in

  let curr_watch = ref 0 in
  let curr_pos = ref s in
  let curr_time = ref 1 in

  while !curr_pos <> f do
    let can_move =
      if !curr_watch = m then true
      else
        let (t,l,r) = arr.(!curr_watch) in
        if t = !curr_time then curr_watch := !curr_watch + 1;
        let next_pos = next !curr_pos in
        if t <> !curr_time then true
        else if (bad !curr_pos l r) || (bad next_pos l r) then false
        else true
    in
    curr_time := !curr_time + 1;
    match can_move with
      | true ->
        curr_pos := next !curr_pos;
        Printf.printf "%s" movement;
      | false ->
        Printf.printf "X";
  done;

  Printf.printf "\n"