Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$ — the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.

The first line contains one integer $$$n$$$ — the number of vertices in the tree ($$$2 \le n \le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \le s_v \le 10^9$$$), where erased values are replaced by $$$-1$$$.

Output one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.

let rec fix f x = f (fix f) x
let (++),(--),max_int = Int64.(add,sub,max_int);;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let edg = make n [] in
  ignore @@
    init (n-1) (fun i ->
      let j = scanf " %d" @@ fun v -> v in (
        let i,j = i+1,j-1 in
        edg.(i) <- j :: edg.(i);
        edg.(j) <- i :: edg.(j)));
  (* iteri (fun i ls ->
    Printf.printf "%d: " i;
    List.iter (Printf.printf "%d ") ls;
    print_newline ()
  ) edg; *)
  let s = init n @@ fun _ -> scanf " %Ld" @@ fun v -> v in
  let undef = -7L in
  let a = make n undef in
  let visited = make n false in
  fix (fun f i even par ->
    visited.(i) <- true;
    if not even then (
      if i=0 then (
        a.(i) <- s.(i)
      ) else (
        a.(i) <- s.(i) -- s.(par)
      );
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    ) else (
      let sh = s.(par) in
      let smin = List.fold_left (fun mn j ->
        if par=j then mn
        else min mn s.(j)
      ) max_int edg.(i) in
      let smin = if smin = max_int then sh else smin in
      let si = smin -- sh in
      if si < 0L then (print_string "-1"; exit 0);
      s.(i) <- smin;
      a.(i) <- smin -- s.(par);
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    )
  ) 0 false 0;
  (* iter (Printf.printf "%d ") a;
  print_newline ();
  iter (Printf.printf "%d ") s;
  print_newline (); *)
  Printf.printf "%Ld" @@ fold_left (++) 0L a
))

let rec fix f x = f (fix f) x;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let edg = make n [] in
  ignore @@
    init (n-1) (fun i ->
      let j = scanf " %d" @@ fun v -> v in (
        let i,j = i+1,j-1 in
        edg.(i) <- j :: edg.(i);
        edg.(j) <- i :: edg.(j)));
  (* iteri (fun i ls ->
    Printf.printf "%d: " i;
    List.iter (Printf.printf "%d ") ls;
    print_newline ()
  ) edg; *)
  let s = init n @@ fun _ -> scanf " %d" @@ fun v -> v in
  let undef = -7 in
  let a = make n undef in
  let visited = make n false in
  fix (fun f i even par ->
    visited.(i) <- true;
    if not even then (
      if i=0 then (
        a.(i) <- s.(i)
      ) else (
        a.(i) <- s.(i) - s.(par)
      );
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    ) else (
      let sh = s.(par) in
      let smin = List.fold_left (fun mn j ->
        if par=j then mn
        else min mn s.(j)
      ) max_int edg.(i) in
      let smin = if smin = max_int then sh else smin in
      let si = smin - sh in
      if si < 0 then (print_string "-1"; exit 0);
      s.(i) <- smin;
      a.(i) <- smin - s.(par);
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    )
  ) 0 false 0;
  (* iter (Printf.printf "%d ") a;
  print_newline ();
  iter (Printf.printf "%d ") s;
  print_newline (); *)
  print_int @@ fold_left (+) 0 a
))


Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that $$$n$$$ persons took part in that party. To make the party funnier, each person wore one hat among $$$n$$$ kinds of weird hats numbered $$$1, 2, \ldots n$$$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the $$$i$$$-th person said that there were $$$a_i$$$ persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $$$b_i$$$ be the number of hat type the $$$i$$$-th person was wearing, Chouti wants you to find any possible $$$b_1, b_2, \ldots, b_n$$$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the number of persons in the party. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le n-1$$$), the statements of people.

If there is no solution, print a single line "Impossible". Otherwise, print "Possible" and then $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$). If there are multiple answers, print any of them.

NoteIn the answer to the first example, all hats are the same, so every person will say that there were no persons wearing a hat different from kind $$$1$$$.In the answer to the second example, the first and the second person wore the hat with type $$$1$$$ and all other wore a hat of type $$$2$$$.So the first two persons will say there were three persons with hats differing from their own. Similarly, three last persons will say there were two persons wearing a hat different from their own.In the third example, it can be shown that no solution exists.In the first and the second example, other possible configurations are possible.

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module Int64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array
module IMap = Map.Make(struct type t= int64 let compare = rv compare end)
module IMap2=Map.Make(Int64)
let () =
  let n = gi 0 in let a = iia n in
  let mp = ref IMap.empty in
  iter (fun v ->
    mp := IMap.add v (1L+try IMap.find v !mp with _ -> 0L) !mp
  ) a;
  let itoc = ref IMap2.empty in
  let color = ref 1L in
  IMap.iter (fun k c ->
    (* if k=0L then (
      let r = ref [] in
      rep 1L c (fun i -> r := (!color,k) :: !r; color += 1L);
      itoc := IMap2.add k !r !itoc
    ) else ( *)
      if c mod (n-k) <> 0L then (
        printf "Impossible"; exit 0
      );
      let r = ref [] in
      rep 1L (c/(n-k)) (fun i -> r := (!color,n-k) :: !r; color += 1L);
      (* r := (!color,c) :: !r; color += 1L; *)
      itoc := IMap2.add k !r !itoc;
      (* printf "added: %Ld : " k;
      print_list (fun (k,v) -> sprintf "%Ld:%Ld" k v) !r; *)
    (* ) *)
  ) !mp;
  let res = make (i32 n) 0L in
  iteri (fun i v ->
    (* printf "%d:%Ld\n" i v; *)
    (* let ls = IMap2.find v !itoc in
    let (c,rest)::tl = ls in
    printf "ls: "; print_list (fun (k,v) -> sprintf "%Ld,%Ld" k v) ls; *)
    let c,rest,tl = match IMap2.find v !itoc with
    | (c,rest)::tl -> c,rest,tl
    | _ -> fail 0 in
    (* printf "%Ld " c; *)
    res.(i) <- c;
    (* print_array ist res; *)
    if rest=1L then itoc := IMap2.add v tl !itoc
    else itoc := IMap2.add v ((c,rest-1L)::tl) !itoc
  ) a;
  printf "Possible\n";
  print_array ist res
  (* let p = mapi (fun i v -> (v,i)) a in
  sort (rv compare) p;
  let b = make (i32 n) 0L in
  let prev = ref 0L in
  iteri (fun i v ->
    if i=0 then (

    ) else (

    )
  ) p; *)


Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.  Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).  Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.

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 m = read_int () in

  let bit = Array.init (n + 1) (fun _ -> 0L) in

  let update x v =
    let x = ref x in
    while !x <= n do
      bit.(!x) <- Int64.add bit.(!x) v;
      x := !x + (!x land (~- !x));
    done
  in

  let sum x =
    let x = ref x in
    let ret = ref 0L in
    while !x > 0 do
      ret := Int64.add !ret bit.(!x);
      x := !x - (!x land (~- !x));
    done;
    !ret
  in

  let arr = Array.init n (fun _ -> Int64.of_int (read_int ())) in

  for i = 0 to n-1 do
    update (i+1) arr.(i);
    update (i+2) (Int64.neg arr.(i));
  done;

  for i = 1 to m do
    let t = read_int () in
    match t with
      | 1 ->
          let x = read_int () in
          let v = (Int64.of_int (read_int ())) in
          let curr = sum x in
          update x (Int64.neg curr);
          update (x+1) curr;
          update x v;
          update (x+1) (Int64.neg v);
      | 2 ->
          let y = Int64.of_int (read_int ()) in
          update 1 y;
      | 3 ->
          let q = read_int () in
          let curr = sum q in
          Printf.printf "%Ld\n" curr;
      | _ -> assert false
   done;

let () =
  let (@@) f x = f x in
  let (|>) x f = f x in
  let split_by_spaces = Str.split @@ Str.regexp_string " " in
  let n, m = match read_line () |> split_by_spaces |> List.map int_of_string with
    | [n; m] -> n, m
    | _ -> failwith "Error on line 1"
  in
  let arr = read_line () |> split_by_spaces |> List.map Int64.of_string |> Array.of_list in
  let inc = ref 0L in
  assert (Array.length arr = n);
  for k = 1 to m do
    match read_line () |> split_by_spaces |> List.map int_of_string with
      | [1; v; x] -> arr.(v - 1) <- Int64.(sub (of_int x) !inc)
      | [2; y]    -> inc := Int64.(add !inc @@ of_int y)
      | [3; q]    -> print_endline @@ Int64.(to_string @@ add arr.(q - 1) !inc)
      | _ -> failwith @@ "Error on line " ^ string_of_int @@ k + 2;
  done

let (+) = Int64.add
let (-) = Int64.sub

type state = {
    arr : int64 array;
    mutable inc : int64
}

let assign state v x =
  state.arr.(v) <- (x - state.inc)

let increment state y =
  state.inc <- state.inc + y

let print state q =
  print_endline (Int64.to_string (state.arr.(q) + state.inc))

let () =
  let open Pervasives in
  let split_by_spaces = Str.split (Str.regexp_string " ") in
  let n, m = match split_by_spaces (read_line ()) with
    | [n; m] -> int_of_string n, int_of_string m
    | _ -> failwith "Error on line 1"
  in
  let int_list_of_string_list = List.map int_of_string in
  let int64_list_of_string_list = List.map Int64.of_string in
  let state =
    { arr = Array.of_list (int64_list_of_string_list (split_by_spaces (read_line ())));
      inc = 0L }
  in
  assert (Array.length state.arr = n);
  let k = ref 0 in
  try while true do
    (match int_list_of_string_list (split_by_spaces (read_line ())) with
      | [1; v; x] -> assign state (v - 1) (Int64.of_int x)
      | [2; y]    -> increment state (Int64.of_int y)
      | [3; q]    -> print state (q - 1)
      | _ -> failwith ("Error on line " ^ (string_of_int (!k + 2))));
    k := !k + 1
  done with End_of_file -> assert (!k = m)

let () =
  let (@@) f x = f x in
  let (|>) x f = f x in
  let open List in
  let open Int64 in
  let split_by_spaces = Str.split @@ Str.regexp_string " " in
  read_line () |> split_by_spaces |> map int_of_string |> tl |> hd |> fun m ->
  read_line () |> split_by_spaces |> map of_string |> Array.of_list |> fun arr ->
  let inc = ref 0L in
  for k = 1 to m do
    read_line () |> split_by_spaces |> List.map int_of_string |> function
      | [1; v; x] -> arr.(v - 1) <- sub (of_int x) !inc
      | [2; y]    -> inc := add !inc @@ of_int y
      | [3; q]    -> print_endline @@ to_string @@ add arr.(q - 1) !inc
      | _ -> failwith @@ "Error on line " ^ string_of_int @@ k + 2
  done

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 m = read_int () in

  let bit = Array.init (n + 1) (fun _ -> 0) in

  let update x v =
    let x = ref x in
    while !x <= n do
      bit.(!x) <- bit.(!x) + v;
      x := !x + (!x land (~- !x));
    done
  in

  let sum x =
    let x = ref x in
    let ret = ref 0 in
    while !x > 0 do
      ret := !ret + bit.(!x);
      x := !x - (!x land (~- !x));
    done;
    !ret
  in

  let arr = Array.init n read_int in

  for i = 0 to n-1 do
    update (i+1) arr.(i);
    update (i+2) (-arr.(i));
  done;

  for i = 1 to m do
    let t = read_int () in
    match t with
      | 1 ->
          let x = read_int () in
          let v = read_int () in
          let curr = sum x in
          update x (-curr);
          update (x+1) curr;
          update x v;
          update (x+1) (-v);
      | 2 ->
          let y = read_int () in
          update 1 y;
      | 3 ->
          let q = read_int () in
          let curr = sum q in
          Printf.printf "%d\n" curr;
      | _ -> assert false
   done;

type state = {
    arr : int array;
    mutable inc : int
}

let assign state v x =
  state.arr.(v) <- (x - state.inc)

let increment state y =
  state.inc <- state.inc + y

let print state q =
  print_endline (string_of_int (state.arr.(q) + state.inc))

let () =
  let split_by_spaces = Str.split (Str.regexp_string " ") in
  let n, m = match split_by_spaces (read_line ()) with
    | [n; m] -> int_of_string n, int_of_string m
    | _ -> failwith "Error on line 1"
  in
  let int_list_of_string_list = List.map int_of_string in
  let state =
    { arr = Array.of_list (int_list_of_string_list (split_by_spaces (read_line ())));
      inc = 0 }
  in
  assert (Array.length state.arr = n);
  let k = ref 0 in
  try while true do
    (match int_list_of_string_list (split_by_spaces (read_line ())) with
      | [1; v; x] -> assign state (v - 1) x
      | [2; y]    -> increment state y
      | [3; q]    -> print state (q - 1)
      | _ -> failwith ("Error on line " ^ (string_of_int (!k + 2))));
    incr k
  done with End_of_file -> assert (!k = m)


You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \rightarrow 10 \rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$).

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

let solve (a : int) (b : int) : int =
  ((abs (a - b)) + 9) / 10

let () =
  let t = read_int () in
  for i = 1 to t do
    let a = read_int () in
    let b = read_int () in
    print_endline ( string_of_int (solve a b))
  done;

let () =
  let t = read_line () |> int_of_string in
  for i = 1 to t do
    let [a; b] =
      read_line ()
      |> Str.split (Str.regexp " ")
      |> List.map String.trim
      |> List.map int_of_string
    in
    let n = abs (b - a) in
    (n + 9) / 10
    |> string_of_int
    |> print_endline
  done


You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.

The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 100$$$). Each of the next $$$T$$$ lines contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 1000$$$) — the description of test cases.

For each test case output two lines. In the first line output a single integer $$$m$$$ — the number of chosen integers. In the second line output $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order.

let l = ref []

let () =
  for i=1 to (read_int ()) do
    l := (Scanf.scanf " %d %d" (fun x y -> x,y))::!l
  done

let rec getListfromArray a n k i =
  if i > n
  then []
  else if i > k
  then
  (i)::(getListfromArray a n k (i+1))
  else if i < k-1
    then if a.(i) = 1 then (i+1)::(getListfromArray a n k (i+1)) else getListfromArray a n k (i+1)
    else getListfromArray a n k (i+1)

let rec printList l =
  match l with
  | h::t -> (Printf.printf "%d " h; printList t)
  | _ -> print_newline ()

let findList (n,k) =
  let a = Array.make (k-1) 0 in
  let () = for i=1 to (k-1) do if a.(i-1) <> 1 then a.(k-i-1) <- 1 done in
  let l = getListfromArray a n k 0 in
  let () = print_endline (string_of_int (List.length l)) in
  printList l

let rec testCases l =
  match l with
  | h::t -> (testCases t; findList h)
  | _ -> ()

let rec testAll l =
  match l with
  | h::t -> (testAll t; findList h)
  | _ -> ()

let () = testAll !l

(* https://codeforces.com/contest/1493/problem/A *)

let solution m k =
    let nums = Array.make m true in
    nums.(k-1) <- false;
    let rec helper i =
        if i < 0
        then ()
        else if (i+1) > k
        then helper (i-1)
        else if (i+1) = k
        then helper (i-1)
        else if (i+1) < k && nums.(i)
        then begin
            let index = k - (i+1) - 1 in
            if index <> i
            then nums.(k-(i+1)-1) <- false;
            helper (i-1)
        end in
    helper (m-1);
    Array.mapi (fun i e -> if e then Some (i+1) else None) nums
    |> Array.to_list
    |> List.filter (fun e -> e <> None)
    |> List.map (fun (Some e) -> e)

let input_case () =
    read_line () |> Str.split (Str.regexp " ") |> List.map int_of_string

let print_sol arr =
    List.iter (fun e -> Printf.printf "%d " e) arr

let () =
    let cases = read_int () in
    for i = 1 to cases do
        let m::k::_ = input_case () in
        let sol = solution m k in
        Printf.printf "%d\n" (List.length sol);
        print_sol sol;
        print_newline ()
    done


How to make a cake you'll never eat.Ingredients.   2 carrots  0 calories  100 g chocolate spread  1 pack of flour  1 egg Method.   Put calories into the mixing bowl.  Take carrots from refrigerator.  Chop carrots.  Take chocolate spread from refrigerator.  Put chocolate spread into the mixing bowl.  Combine pack of flour into the mixing bowl.  Fold chocolate spread into the mixing bowl.  Add chocolate spread into the mixing bowl.  Put pack of flour into the mixing bowl.  Add egg into the mixing bowl.  Fold pack of flour into the mixing bowl.  Chop carrots until choped.  Pour contents of the mixing bowl into the baking dish. Serves 1.

The only line of input contains a sequence of integers a0, a1, ... (1 ≤ a0 ≤ 100, 0 ≤ ai ≤ 1000 for i ≥ 1).

let _ =
    let rdint =
        let l = ref 0 in
        let i = ref 0 in
        let s = String.create 65536 in
        let refill () =
            let n = input stdin s 0 65536 in
            i := 0;
            l := n in
        refill ();

        fun () ->
            let rec loop2 j k t f =
                let fin j t f =
                    let _ = i := j in
                    t * f in

                if j = k then (
                    let _ = refill () in
                    if !l > 0 then loop2 !i !l t f else fin j t f
                ) else if s.[j] >= '0' && s.[j] <= '9' then
                    loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f
                else fin j t f in

            let rec loop1 j k =
                if j = k then (
                    let _ = refill () in
                    if !l > 0 then loop1 !i !l else 0
                ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)
                else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1
                else loop1 (j + 1) k in
            loop1 !i !l
    in

    let main () =
        let rec loop i k acc =
            if i = 0 then Printf.printf "%d\n" acc else loop (i - 1) (k + 1) (acc + k * rdint ())
        in
        loop (rdint ()) 1 0
    in
    main ()


There are $$$n$$$ people sitting in a circle, numbered from $$$1$$$ to $$$n$$$ in the order in which they are seated. That is, for all $$$i$$$ from $$$1$$$ to $$$n-1$$$, the people with id $$$i$$$ and $$$i+1$$$ are adjacent. People with id $$$n$$$ and $$$1$$$ are adjacent as well.The person with id $$$1$$$ initially has a ball. He picks a positive integer $$$k$$$ at most $$$n$$$, and passes the ball to his $$$k$$$-th neighbour in the direction of increasing ids, that person passes the ball to his $$$k$$$-th neighbour in the same direction, and so on until the person with the id $$$1$$$ gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if $$$n = 6$$$ and $$$k = 4$$$, the ball is passed in order $$$[1, 5, 3, 1]$$$. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be $$$1 + 5 + 3 = 9$$$.Find and report the set of possible fun values for all choices of positive integer $$$k$$$. It can be shown that under the constraints of the problem, the ball always gets back to the $$$1$$$-st player after finitely many steps, and there are no more than $$$10^5$$$ possible fun values for given $$$n$$$.

The only line consists of a single integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number of people playing with the ball.

Suppose the set of all fun values is $$$f_1, f_2, \dots, f_m$$$. Output a single line containing $$$m$$$ space separated integers $$$f_1$$$ through $$$f_m$$$ in increasing order.

NoteIn the first sample, we've already shown that picking $$$k = 4$$$ yields fun value $$$9$$$, as does $$$k = 2$$$. Picking $$$k = 6$$$ results in fun value of $$$1$$$. For $$$k = 3$$$ we get fun value $$$5$$$ and with $$$k = 1$$$ or $$$k = 5$$$ we get $$$21$$$.   In the second sample, the values $$$1$$$, $$$10$$$, $$$28$$$, $$$64$$$ and $$$136$$$ are achieved for instance for $$$k = 16$$$, $$$8$$$, $$$4$$$, $$$10$$$ and $$$11$$$, respectively.

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module Int64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let slen s = String.length s
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array
let divisors v = (* O(sqrt n) *)
  let rec f0 i a =
    if i*i > v then a
    else if i*i = v && v mod i = 0L then i::a
    else if v mod i = 0L then f0 (i+1L) (i::(v/i)::a)
    else f0 (i+1L) a in f0 1L []
let () =
  let n = gi 0 in
  let div = divisors n in
  let w0 = (n * (n+1L)) / 2L in
  let r = ref [w0] in
  List.iter (fun v ->
    (* printf "%Ld\n" v; *)
    if v<>1L then (
      r := ((n*(n+2L-v)) / (2L*v))::!r;
    )
  ) div;
  List.sort compare !r |> print_list ist


A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \le |p_i - p_{i+1}| \le 4$$$ for each $$$i$$$ ($$$1 \le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is described by a single line containing an integer $$$n$$$ ($$$2 \le n \le 1000$$$).

Print $$$t$$$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.

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

open Printf

let init (x : int) (f : int -> 'a) : 'a list =
  let rec build k =
    if k = x then []
    else (f k) :: build (k + 1) in
  build 0
;;

let run () =
  let n = scan_int () in
  if n = 3 || n = 2 then print_endline "-1"
  else begin
    let ans =
      (
      let lst = ref [] in
      if n mod 4 = 0 then
        (let cur = ref 4 in
        while !cur <= n do
          let t = !cur in
          lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;
          cur := !cur + 4;
        done;
        !lst)
      else if n mod 4 = 1 then
        (lst := 1 :: !lst;
        let cur = ref 5 in
        while !cur <= n do
          let t = !cur in
          lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;
          cur := !cur + 4;
        done;
        !lst)
      else if n mod 4 = 2 then begin
        lst := 1 :: !lst;
        let cur = ref 5 in
        while !cur <= n do
          let t = !cur in
          lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;
          cur := !cur + 4;
        done;
        lst := n :: !lst;
        !lst
      end
      else begin
        lst := [5; 1; 3; 6; 2; 4; 7];
        let cur = ref 11 in
        while !cur <= n do
          let t = !cur in
          lst := (t - 1) :: (t - 3) :: t :: (t - 2) :: !lst;
          cur := !cur + 4;
        done;
        !lst;
      end
      )in
    List.iter (printf "%d ") (List.rev ans);
    print_endline ""
  end
;;

let () =
  let t = scan_int () in
  for i = 1 to t do
    run ()
  done
;;


Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly $$$a$$$ minutes to swim across the entire pool and come back, exactly $$$b$$$ minutes for the second swimmer and $$$c$$$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $$$0$$$, $$$a$$$, $$$2a$$$, $$$3a$$$, ... minutes after the start time, the second one will be at $$$0$$$, $$$b$$$, $$$2b$$$, $$$3b$$$, ... minutes, and the third one will be on the left side of the pool after $$$0$$$, $$$c$$$, $$$2c$$$, $$$3c$$$, ... minutes.You came to the left side of the pool exactly $$$p$$$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test case descriptions, one per line. Each line contains four integers $$$p$$$, $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \leq p, a, b, c \leq 10^{18}$$$), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.

For each test case, output one integer — how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.

NoteIn the first test case, the first swimmer is on the left side in $$$0, 5, 10, 15, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 4, 8, 12, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 8, 16, 24, \ldots$$$ minutes after the start time. You arrived at the pool in $$$9$$$ minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in $$$0, 6, 12, 18, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 10, 20, 30, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$2$$$ minutes after the start time and after $$$4$$$ minutes meet the first swimmer on the left side.In the third test case, you came to the pool $$$10$$$ minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$10$$$ minutes after the start time and after $$$8$$$ minutes meet all three swimmers on the left side.

(** https://codeforces.com/contest/1492/problem/0 *)

let read_case () =
    let p::swimmers =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map Int64.of_string in
    (p, swimmers) in

let solve_case (p, swimmers) =
    let times =
        List.map
            (fun swimmer ->
                if Int64.rem p swimmer = Int64.zero
                then Int64.zero
                else Int64.sub swimmer (Int64.rem p swimmer))
            swimmers in
    let rec min_time curr tms =
        match tms with
        | [] -> curr
        | time::rest -> min_time (if time < curr then time else curr) rest in
    match times with
    | h::t -> min_time h t in

let solve_n n =
    let rec helper i =
        if i = 0
        then ()
        else begin
            read_case ()
            |> solve_case
            |> Int64.to_string
            |> print_endline;
            helper (i-1)
        end in
    helper n in

let nb_cases = read_int () in
solve_n nb_cases


String x is an anagram of string y, if we can rearrange the letters in string x and get exact string y. For example, strings "DOG" and "GOD" are anagrams, so are strings "BABA" and "AABB", but strings "ABBAC" and "CAABA" are not.You are given two strings s and t of the same length, consisting of uppercase English letters. You need to get the anagram of string t from string s. You are permitted to perform the replacing operation: every operation is replacing some character from the string s by any other character. Get the anagram of string t in the least number of replacing operations. If you can get multiple anagrams of string t in the least number of operations, get the lexicographically minimal one.The lexicographic order of strings is the familiar to us "dictionary" order. Formally, the string p of length n is lexicographically smaller than string q of the same length, if p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ n). Here characters in the strings are numbered from 1. The characters of the strings are compared in the alphabetic order.

The input consists of two lines. The first line contains string s, the second line contains string t. The strings have the same length (from 1 to 105 characters) and consist of uppercase English letters.

In the first line print z — the minimum number of replacement operations, needed to get an anagram of string t from string s. In the second line print the lexicographically minimum anagram that could be obtained in z operations.

NoteThe second sample has eight anagrams of string t, that can be obtained from string s by replacing exactly two letters: "ADBADC", "ADDABC", "CDAABD", "CDBAAD", "CDBADA", "CDDABA", "DDAABC", "DDBAAC". These anagrams are listed in the lexicographical order. The lexicographically minimum anagram is "ADBADC".

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

let read_string () = Scanf.fscanf input " %s " (fun x -> x) ;;

let s = read_string () and t = read_string () ;;

let index c = int_of_char c - int_of_char 'A' ;;
let letter i = char_of_int (i + int_of_char 'A') ;;

let freqs = Array.make 26 0 and freqt = Array.make 26 0 ;;
for i = 0 to String.length s - 1 do
    freqs.(index s.[i]) <- freqs.(index s.[i]) + 1 ;
    freqt.(index t.[i]) <- freqt.(index t.[i]) + 1
done ;;

let (z, result) =
    let rec next_available i =
        if i > 25 then -1
        else if freqt.(i) > freqs.(i) then i
        else next_available (i + 1)
    and r = String.create (String.length s)
    in let rec loop i a cur =
        if i = String.length s then (a, r)
        else let c = index s.[i] in
            (* Need to replace this character *)
            if freqt.(c) = 0 || freqs.(c) > freqt.(c) && cur < c then
            (
                r.[i] <- letter cur ;
                freqt.(cur) <- freqt.(cur) - 1 ;
                freqs.(c) <- freqs.(c) - 1;
                loop (i + 1) (a + 1) (next_available cur)
            )
            (* Need to save this character *)
            else
            (
                r.[i] <- letter c ;
                freqt.(c) <- freqt.(c) - 1 ;
                freqs.(c) <- freqs.(c) - 1;
                loop (i + 1) a cur
            )
    in loop 0 0 (next_available 0) ;;

Printf.fprintf output "%d\n%s\n" z result ;;

let chan = Scanf.Scanning.from_channel (open_in "input.txt")
let read_str () = Scanf.bscanf chan " %s " (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 toint c = (int_of_char c) - (int_of_char 'A')
let tochar i = char_of_int ((int_of_char 'A') + i)

let () =
  let s = read_str() in
  let t = read_str() in
  let n = String.length s in
  let hs = Array.make 26 0 in
  let h = Array.make 26 0 in

  let () =
    for i=0 to n-1 do
      let (c,d) = (toint s.[i], toint t.[i]) in
	hs.(c) <- hs.(c) + 1;
	h.(c) <- h.(c) + 1;
	h.(d) <- h.(d) - 1
    done
  in

  let tot = sum 0 25 (fun i-> abs h.(i)) in
  let () = print_string (Printf.sprintf "%d\n" (tot/2)) in

  let () =
    for i=0 to n-1 do
      let c = toint s.[i] in
	if h.(c) <= 0 then (
	  print_string (Printf.sprintf "%c" (tochar c));
	) else (
	  let rec loop j = if h.(j) < 0 then j else loop (j+1) in
	  let d = loop 0 in
	    if d > c && hs.(c) > h.(c) then (
	      print_string (Printf.sprintf "%c" (tochar c));
	    ) else (
	      h.(d) <- h.(d) + 1;
	      h.(c) <- h.(c) - 1;
	      print_string (Printf.sprintf "%c" (tochar d))
	    )
	);
	hs.(c) <- hs.(c) - 1
    done
  in
    print_string "\n"

let chan = Scanf.Scanning.from_channel (open_in "input.txt")
let read_str () = Scanf.bscanf chan " %s " (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 toint c = (int_of_char c) - (int_of_char 'A')
let tochar i = char_of_int ((int_of_char 'A') + i)

let () =
  let s = read_str() in
  let t = read_str() in
  let n = String.length s in
  let hs = Array.make n 0 in
  let h = Array.make n 0 in

  let () =
    for i=0 to n-1 do
      let (c,d) = (toint s.[i], toint t.[i]) in
	hs.(c) <- hs.(c) + 1;
	h.(c) <- h.(c) + 1;
	h.(d) <- h.(d) - 1
    done
  in

  let () =
    for i=0 to n-1 do
      let c = toint s.[i] in
	if h.(c) <= 0 then (
	  print_string (Printf.sprintf "%c" (tochar c));
	) else (
	  let rec loop j = if h.(j) < 0 then j else loop (j+1) in
	  let d = loop 0 in
	    if d > c && hs.(c) > h.(c) then (
	      print_string (Printf.sprintf "%c" (tochar c));
	    ) else (
	      h.(d) <- h.(d) + 1;
	      h.(c) <- h.(c) - 1;
	      print_string (Printf.sprintf "%c" (tochar d))
	    )
	);
	hs.(c) <- hs.(c) - 1
    done
  in
    print_string "\n"


Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p1, it'll move to p2, again, choosing one of the shortest ways, then to p3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.

The first line of input contains the only positive integer n (1 ≤ n ≤ 2·105) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R — to the right, U — to the top and D — to the bottom. Have a look at the illustrations for better explanation.

The only line of input should contain the minimum possible length of the sequence.

NoteThe illustrations to the first three tests are given below.  The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let path = read_string () in

  let path = Array.init n (fun i ->
    match path.[i] with 'R' -> 0 | 'U' -> 1 | 'L' -> 2 | 'D' -> 3 | _ -> failwith "bad input"
  ) in

  let used = Array.make 4 false in
  let cc i =  if used.(i) then 1 else 0 in
  let clear () = for i=0 to 3 do used.(i) <- false done in
  let count () = (cc 0) + (cc 1) + (cc 2) + (cc 3) in

  let rec loop i ac = if i=n then ac else (
    if used.(path.(i)) then loop (i+1) ac
    else (
      let c = count () in
      if c = 0 then (
	used.(path.(i)) <- true;
	loop (i+1) ac
      )
      else if c = 1 then (
	if used.((2+path.(i)) mod 4) then (
	  clear ();
	  used.(path.(i)) <- true;
	  loop (i+1) (ac+1)
	) else (
	  used.(path.(i)) <- true;
	  loop (i+1) ac
	)
      )
      else (
	clear ();
	used.(path.(i)) <- true;
	loop (i+1) (ac+1)
      )
    )
  ) in

  printf "%d\n" (1+(loop 0 0))


User ainta decided to paint a wall. The wall consists of n2 tiles, that are arranged in an n × n table. Some tiles are painted, and the others are not. As he wants to paint it beautifully, he will follow the rules below.  Firstly user ainta looks at the wall. If there is at least one painted cell on each row and at least one painted cell on each column, he stops coloring. Otherwise, he goes to step 2.  User ainta choose any tile on the wall with uniform probability.  If the tile he has chosen is not painted, he paints the tile. Otherwise, he ignores it.  Then he takes a rest for one minute even if he doesn't paint the tile. And then ainta goes to step 1.   However ainta is worried if it would take too much time to finish this work. So he wants to calculate the expected time needed to paint the wall by the method above. Help him find the expected time. You can assume that choosing and painting any tile consumes no time at all.

The first line contains two integers n and m (1 ≤ n ≤ 2·103; 0 ≤ m ≤ min(n2, 2·104)) — the size of the wall and the number of painted cells. Next m lines goes, each contains two integers ri and ci (1 ≤ ri, ci ≤ n) — the position of the painted cell. It is guaranteed that the positions are all distinct. Consider the rows of the table are numbered from 1 to n. Consider the columns of the table are numbered from 1 to n.

In a single line print the expected time to paint the wall in minutes. Your answer will be considered correct if it has at most 10 - 4 absolute or relative error.

open Printf
open Scanf

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 read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int()in
  let m = read_int() in
  let rowempty = Array.make n 1 in
  let colempty = Array.make n 1 in
  for i=1 to m do
    let r = read_int() in
    let c = read_int() in
    rowempty.(r-1) <- 0;
    colempty.(c-1) <- 0;
  done;

  let r = sum 0 (n-1) (fun i -> rowempty.(i)) in
  let c = sum 0 (n-1) (fun i -> colempty.(i)) in

  let dp = Array.make_matrix (r+1) (c+1) None in

  let rec calc r c =
    if r<0 || c<0 then 0.0 else
      match dp.(r).(c) with Some x -> x | None ->
	let answer =
	  if r=0 && c=0 then 0.0 else (
	    let cells = float (n * (r+c) - r*c) in
	    let area = float (n*n) in
	    let p = cells /. area in
	  (* prob that we hit a useful one.  1/p is E(time till we hit) *)

	  (* now, given that we hit a useful one what is the probability of the
	     three different types .... *)
	    let pboth = (float (r*c)) /. cells in
	    let pcol = ((float (c*(n-r))) /. cells) in
	    let prow = ((float (r*(n-c))) /. cells) in

	    (1.0 /. p) +.
	      pboth *. (calc (r-1) (c-1)) +.
	      pcol *. (calc r (c-1)) +.
	      prow *. (calc (r-1) c)
	  )
	in
	dp.(r).(c) <- Some answer;
	answer
  in

  printf "%15.10f\n" (calc r c)


Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line.

The single line contains two integers n and m (3 ≤ m ≤ 100, m ≤ n ≤ 2m).

If there is no solution, print "-1". Otherwise, print n pairs of integers — the coordinates of points of any set with the convexity of m. The coordinates shouldn't exceed 108 in their absolute value.

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

let pi = 2.0 *. (atan2 1.0 0.0)

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

  let outer = Array.make m (0.0,0.0) in
  let inner = Array.make (n-m) (0.0,0.0) in

  let eps = 0.000001 in

  let r = 10000000.0 in
  let r' = r -. 1000.0 in

  let delta = (2.0 *. pi) /. (float m) in

    for i=0 to m-1 do
      let alpha = (float i) *. delta in
	outer.(i) <- (r *. (cos alpha) , r *. (sin alpha))
    done;

    for i=0 to (n-m)-1 do
      let alpha = (float i) *. delta in
	inner.(i) <- (r' *. (cos (alpha+.eps)) , r' *. (sin (alpha+.eps)))
    done;

    if (n,m) = (6,3) || (n,m) = (5,3) then (
      Printf.printf "-1\n"
    ) else (
      for i=0 to m-1 do
	let (x,y) = outer.(i) in
	let (x,y) = (int_of_float x, int_of_float y) in
	  Printf.printf "%d %d\n" x y
      done;

      for i=0 to (n-m)-1 do
	let (x,y) = inner.(i) in
	let (x,y) = (int_of_float x, int_of_float y) in
	  Printf.printf "%d %d\n" x y
      done
    )

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

let pi = 2.0 *. (atan2 1.0 0.0)

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

  let outer = Array.make m (0.0,0.0) in

  let eps = 0.0001 in

  let r = 10000000.0 in
  let r' = r -. 1000.0 in

  let delta = (2.0 *. pi) /. (float m) in

    for i=0 to m-1 do
      let alpha = (float i) *. delta in
	outer.(i) <- (r *. (cos alpha) , r *. (sin alpha))
    done;

    let inner = Array.make (n-m) (0.0,0.0) in

      for i=0 to (n-m)-1 do
	let alpha = (float i) *. delta in
	  inner.(i) <- (r' *. (cos (alpha+.eps)) , r' *. (sin (alpha+.eps)))
      done;

      if (n,m) = (6,3) || (n,m) = (5,3) then (
	Printf.printf "-1\n"
      ) else (
	for i=0 to m-1 do
	  let (x,y) = outer.(i) in
	  let (x,y) = (int_of_float x, int_of_float y) in
	    Printf.printf "%d %d\n" x y
	done;

	for i=0 to (n-m)-1 do
	  let (x,y) = inner.(i) in
	  let (x,y) = (int_of_float x, int_of_float y) in
	    Printf.printf "%d %d\n" x y
	done
      )


The Fair Nut likes kvass very much. On his birthday parents presented him $$$n$$$ kegs of kvass. There are $$$v_i$$$ liters of kvass in the $$$i$$$-th keg. Each keg has a lever. You can pour your glass by exactly $$$1$$$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $$$s$$$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $$$s$$$ liters of kvass.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le s \le 10^{12}$$$) — the number of kegs and glass volume. The second line contains $$$n$$$ integers $$$v_1, v_2, \ldots, v_n$$$ ($$$1 \le v_i \le 10^9$$$) — the volume of $$$i$$$-th keg.

If the Fair Nut cannot pour his glass by $$$s$$$ liters of kvass, print $$$-1$$$. Otherwise, print a single integer — how much kvass in the least keg can be.

NoteIn the first example, the answer is $$$3$$$, the Fair Nut can take $$$1$$$ liter from the first keg and $$$2$$$ liters from the third keg. There are $$$3$$$ liters of kvass in each keg.In the second example, the answer is $$$2$$$, the Fair Nut can take $$$3$$$ liters from the first keg and $$$1$$$ liter from the second keg.In the third example, the Fair Nut can't pour his cup by $$$7$$$ liters, so the answer is $$$-1$$$.

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module Int64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

let () =
  let n,s = g2 0 in let a = iia n in
  let sum = fold_left (+) 0L a in
  if s > sum then (printf "-1"; exit 0)
  else if s=sum then (printf "0"; exit 0);
  let mn = fold_left min max_i64 a in
  let left = sum - mn*n in
  if s <= left then (printf "%Ld" mn; exit 0);
  let d = ceildiv (s-left) n in
  printf "%Ld" @@ mn - d


Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?

The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 ≤ ti ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.

let solve (a:int array) =
	let n = Array.length a in
	let rec find l l_sum r r_sum =
		if l>r then l,(n-l)
		else if l_sum<=r_sum then find (l+1) (l_sum + a.(l)) r r_sum
		else find l l_sum (r-1) (r_sum+a.(r))
	in
	let l, r = find 0 0 (n-1) 0 in
	Printf.printf "%d %d\n" (l) (n-l);;

let trim (line: string) =
	(* trim leading white space *)
	let line = Str.replace_first (Str.regexp "^[ \t\n\r]+") "" line in
	(* trim trailing white space *)
	let line = Str.replace_first (Str.regexp "[ \t\n\r]+$") "" line in
	line
;;

let ints_of_string (line: string) =
	Array.of_list (List.map int_of_string (Str.split (Str.regexp " ") (trim line)))
;;

let _ =
	let _ = int_of_string (read_line()) in
	let a = ints_of_string (read_line()) in
	solve a

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

let ubound a n =
  let rec go l h =
    if l = h then
      l
    else
      let m = (l+h)/2 in
      if (if m > 0 then a.(m-1) else 0) <= a.(n-1)-a.(m) then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  for i = 1 to n-1 do
    a.(i) <- a.(i)+a.(i-1)
  done;
  let x = ubound a n in
  Printf.printf "%d %d\n" x (n-x)

let solve (a:int array) =
    let n = Array.length a in
    let s = Array.fold_left (fun s x -> s + x) 0 a in
    let half = s / 2 in
    let rec find idx s =
        if s+a.(idx)>half then idx
        else find (idx+1) (s + a.(idx))
    in
    let l = find 0 0 in
    print_int l;
    print_string " ";
    print_int (n-l);
    print_newline ()
    ;;

let trim (line: string) =
    (* trim leading white space *)
    let line = Str.replace_first (Str.regexp "^[ \t\n\r]+") "" line in
    (* trim trailing white space *)
    let line = Str.replace_first (Str.regexp "[ \t\n\r]+$") "" line in
    line
;;

let ints_of_string (line: string) =
    Array.of_list (List.map int_of_string (Str.split (Str.regexp " ") (trim line)))
;;

let _ =
    let n = int_of_string (read_line()) in
    let a = ints_of_string (read_line()) in
    solve a

let solve (a:int array) =
	let n = Array.length a in
	let s = Array.fold_left (fun s x -> s + x) 0 a in
	let half = (1+ s) / 2 in
	let rec find idx s =
		if (idx >= n || s+a.(idx)>half) then idx
		else find (idx+1) (s + a.(idx))
	in
	let l = find 1 (a.(0)) in
	Printf.printf "%d %d\n" l (n-l);;
	(*
	print_int l;
	print_string " ";
	print_int (n-l);
	print_newline ()
	;;
*)

let trim (line: string) =
	(* trim leading white space *)
	let line = Str.replace_first (Str.regexp "^[ \t\n\r]+") "" line in
	(* trim trailing white space *)
	let line = Str.replace_first (Str.regexp "[ \t\n\r]+$") "" line in
	line
;;

let ints_of_string (line: string) =
	Array.of_list (List.map int_of_string (Str.split (Str.regexp " ") (trim line)))
;;

let _ =
	let n = int_of_string (read_line()) in
	let a = ints_of_string (read_line()) in
	solve a

let solve (a:int array) =
    let n = Array.length a in
    let s = Array.fold_left (fun s x -> s + x) 0 a in
    let half = (1+ s) / 2 in
    let rec find idx s =
        if (idx >= n || s+a.(idx)>half) then idx
        else find (idx+1) (s + a.(idx))
    in
    let l = find 0 0 in
    Printf.printf "%d %d\n" l (n-l);;
    (*
    print_int l;
    print_string " ";
    print_int (n-l);
    print_newline ()
    ;;
*)

let trim (line: string) =
    (* trim leading white space *)
    let line = Str.replace_first (Str.regexp "^[ \t\n\r]+") "" line in
    (* trim trailing white space *)
    let line = Str.replace_first (Str.regexp "[ \t\n\r]+$") "" line in
    line
;;

let ints_of_string (line: string) =
    Array.of_list (List.map int_of_string (Str.split (Str.regexp " ") (trim line)))
;;

let _ =
    let n = int_of_string (read_line()) in
    let a = ints_of_string (read_line()) in
    solve a

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

let ubound a n =
  let rec go l h =
    if l = h then
      l
    else
      let m = (l+h)/2 in
      if a.(m) <= a.(n-1)-a.(m) then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  for i = 1 to n-1 do
    a.(i) <- a.(i)+a.(i-1)
  done;
  let x = ubound a n in
  Printf.printf "%d %d\n" x (n-x)


Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:  Add the integer xi to the first ai elements of the sequence.  Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1)  Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≤ ti ≤ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≤ 103; 1 ≤ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≤ 103). If ti = 3, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.

Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

NoteIn the second sample, the sequence becomes

(******************************* Splay tree code ********************************)

type tree =
    Empty | Node of tree * float * tree * int
(*                  left   key     right  size *)
type direction = Left | Right
type path = Item of tree * direction

let size = function Empty -> 0 | Node(_, _, _, size) -> size

let getroot = function
  | Node(left, k, right, _) -> (left, k, right)
  | _ -> failwith "called getroot on Empty"

let correct n y = match n with Empty -> Empty
  | Node(l,k,r,s) -> Node(l,k+.y,r,s)

(*
let getkey = function
  | Empty -> 0
  | Node(_, key, _, _) -> key
*)

let glue (l, key, r) =
  let (l,r) = (correct l (-.key), correct r (-.key)) in
     Node(l, key, r, ((size l) + (size r) + 1))

let snip = function
  | Node(l, key, r, s) -> Node(correct l key, key, correct r key, 0)
  | _ -> failwith "called snip on Empty"

let connect (l, key, r) = Node(l, key, r, 0)

let splay t rank =
  (* splay the node of the given rank (which are numbered starting at 0)
     to the root *)

  (* The following splay function takes as input the currently splayed
     tree (so far) t, and a path list.  It takes one or two steps up,
     and calls itself recursively.  *)
  let rec rsplay = function
    | (t,[]) -> glue (getroot t)
    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->
	rsplay (connect(tL,tK,glue(tR,bK,glue(bR,cK,cR))), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->
        rsplay (connect(glue(glue(cL,cK,bL), bK, tL),tK,tR), tail)

    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->
	rsplay (connect(tL,tK,glue(tR,bK,bR)), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->
	rsplay (connect(glue(bL,bK,tL),tK,tR), tail)

    | (_,_) -> failwith "Splay_failed (Should not happen)"
  in

  let rec build_path t r path = (* r = the rank of the target node in the current tree t *)
    let t = snip t in
      match t with
	| Empty -> failwith "failed build_path"
	| Node(left, _, right, _) ->
	    let sl = size left in
	      if r < sl then build_path left r (Item(t, Left)::path)
	      else if r = sl then (t,path)
	      else build_path right (r-sl-1) (Item(t, Right)::path)
  in
    if t=Empty then t else rsplay (build_path t rank [])

let append t k = glue(t, k, Empty)

(* let key_of_rank t rank = getkey (splay t rank) *)

let add_to_root delta t =
  if t = Empty then t else
    let (l,k,r) = getroot t in
      Node (l, k+.delta, r, size t)

(*************************************************************************)

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
let read_pair _ = let u = read_int 0 in (u,read_int 0)

let () =
  let printave t total =
    Printf.printf "%.6f\n" (total/. (float (size t)));
  in

  let n = read_int 0 in
  let t = append Empty 0.0 in
  let rec loop i total t = if i=n then () else
    match read_int 0 with
      | 1 ->
	  let a = read_int 0 in (* increment the first a elements by x *)
	  let x = float (read_int 0) in
	  let t = splay t (a-1) in
	  let t = snip t in
	  let (l,k,r) = getroot t in
	  let l = add_to_root x l in
	  let t = glue(l,k+.x,r) in
	  let total = total +. (float a)*.x in
	    printave t total;
	    loop (i+1) total t
      | 2 ->
	  let k = float (read_int 0) in
	  let total = total +. k in
	  let t = append t k in
	    printave t total;
	    loop (i+1) total t
      | 3 ->
	  let s = size t in
	  let t = splay t (s-1) in
	  let t = snip t in
	  let (l,k,_) = getroot t in
	  let t = l in
	  let total = total -. k in
	    printave t total;
	    loop (i+1) total t
      | _ -> failwith "bad input"

  in
    ignore (loop 0 0.0 t)

(******************************* Splay tree code ********************************)

type tree =
    Empty | Node of tree * int * tree * int
(*                  left   key   right  size *)
type direction = Left | Right
type path = Item of tree * direction

let size = function Empty -> 0 | Node(_, _, _, size) -> size

let getroot = function
  | Node(left, k, right, _) -> (left, k, right)
  | _ -> failwith "called getroot on Empty"

let correct n y = match n with Empty -> Empty
  | Node(l,k,r,s) -> Node(l,k+y,r,s)

let getkey = function
  | Empty -> 0
  | Node(_, key, _, _) -> key

let glue (l, key, r) =
  let (l,r) = (correct l (-key), correct r (-key)) in
     Node(l, key, r, ((size l) + (size r) + 1))

let snip = function
  | Node(l, key, r, s) -> Node(correct l key, key, correct r key, 0)
  | _ -> failwith "called snip on Empty"

let connect (l, key, r) = Node(l, key, r, 0)

let splay t rank =
  (* splay the node of the given rank (which are numbered starting at 0)
     to the root *)

  (* The following splay function takes as input the currently splayed
     tree (so far) t, and a path list.  It takes one or two steps up,
     and calls itself recursively.  *)
  let rec rsplay = function
    | (t,[]) -> glue (getroot t)
    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->
	rsplay (connect(tL,tK,glue(tR,bK,glue(bR,cK,cR))), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->
        rsplay (connect(glue(glue(cL,cK,bL), bK, tL),tK,tR), tail)

    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->
	rsplay (connect(tL,tK,glue(tR,bK,bR)), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->
	rsplay (connect(glue(bL,bK,tL),tK,tR), tail)

    | (_,_) -> failwith "Splay_failed (Should not happen)"
  in

  let rec build_path t r path = (* r = the rank of the target node in the current tree t *)
    let t = snip t in
      match t with
	| Empty -> failwith "failed build_path"
	| Node(left, _, right, _) ->
	    let sl = size left in
	      if r < sl then build_path left r (Item(t, Left)::path)
	      else if r = sl then (t,path)
	      else build_path right (r-sl-1) (Item(t, Right)::path)
  in
    if t=Empty then t else rsplay (build_path t rank [])

let append t k = glue(t, k, Empty)

let key_of_rank t rank = getkey (splay t rank)

let add_to_root delta t =
  if t = Empty then t else
    let (l,k,r) = getroot t in
      Node (l, k+delta, r, size t)

(*************************************************************************)

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
let read_pair _ = let u = read_int 0 in (u,read_int 0)

let () =
  let printave t total =
    let len = size t in
      Printf.printf "%.6f\n" ((float total) /. (float len));
  in

  let n = read_int 0 in
  let t = append Empty 0 in
  let rec loop i total t = if i=n then () else
    match read_int 0 with
      | 1 ->
	  let a = read_int 0 in (* increment the first a elements by x *)
	  let x = read_int 0 in
	  let t = splay t (a-1) in
	  let t = snip t in
	  let (l,k,r) = getroot t in
	  let l = add_to_root x l in
	  let t = glue(l,k+x,r) in
	  let total = total + a*x in
	    printave t total;
	    loop (i+1) total t
      | 2 ->
	  let k = read_int 0 in
	  let total = total + k in
	  let t = append t k in
	    printave t total;
	    loop (i+1) total t
      | 3 ->
	  let s = size t in
	  let t = splay t (s-1) in
	  let t = snip t in
	  let (l,k,_) = getroot t in
	  let t = l in
	  let total = total - k in
	    printave t total;
	    loop (i+1) total t
      | _ -> failwith "bad input"

  in
    ignore (loop 0 0 t)


Masha has $$$n$$$ types of tiles of size $$$2 \times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$) — the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines.  The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.

For each test case print the answer: "YES" (without quotes) if Masha can construct the square of size $$$m \times m$$$ which is a symmetric matrix. Otherwise, print "NO" (withtout quotes).

NoteThe first test case of the input has three types of tiles, they are shown on the picture below.  Masha can construct, for example, the following square of size $$$4 \times 4$$$ which is a symmetric matrix:

let rec case t =
    if t > 0 then
        let check a b c d =
            if b = c then 1 else 0
        in let rec input acc ntimes =
            if ntimes = 0 then acc
            else input (acc + Scanf.scanf "%d %d\n%d %d\n" (fun a b c d -> check a b c d)) (ntimes - 1)
        in Scanf.scanf "%d %d\n" (fun n m -> if (input 0 n > 0) && (m mod 2 = 0) then Printf.printf "YES\n" else Printf.printf("NO\n"); case (t - 1))
in Scanf.scanf "%d\n" (fun t -> case t)


Pushok the dog has been chasing Imp for a few hours already.  Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of string "sh" as a subsequence in it, in other words, the number of such pairs (i, j), that i < j and  and . The robot is off at the moment. Imp knows that it has a sequence of strings ti in its memory, and he can arbitrary change their order. When the robot is started, it generates the string t as a concatenation of these strings in the given order. The noise of the resulting string equals the noise of this concatenation.Help Imp to find the maximum noise he can achieve by changing the order of the strings.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of strings in robot's memory. Next n lines contain the strings t1, t2, ..., tn, one per line. It is guaranteed that the strings are non-empty, contain only English letters 's' and 'h' and their total length does not exceed 105.

Print a single integer — the maxumum possible noise Imp can achieve by changing the order of the strings.

NoteThe optimal concatenation in the first sample is ssshhshhhs.

let identity x = x

let read_lines (n: int): string list =
  let rec read_single l i =
    if i == n then l
    else read_single (Scanf.scanf "%s\n" identity :: l) (i + 1)
  in read_single [] 0

let count_of (cc: char) (src: string): int =
  let ret = ref 0 in
  String.iter (fun c -> if c == cc then ret := !ret + 1) src;
  !ret

let preprocess_lines (src: string list): (string * int * int) list =
  List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src

let postprocess_lines (src: (string * int * int) list): string list =
  List.map (fun (str, s, h) -> str) src

let sort_lines (src: (string * int * int) list): (string * int * int) list =
  let l, il = List.partition (fun (ss, s, h) -> h != 0) src in
  let l = List.map (fun (ss, s, h) -> (ss, s, h, (float_of_int s) /. (float_of_int h))) l in
  let comparator (_, _, _, lr) (_, _, _, rr) = -(compare lr rr) in
  let l = List.sort comparator l in
  il @ List.map (fun (ss, s, h, _) -> (ss, s, h)) l
  (* let comparator (lss, ls, lh) (rss, rs, rh) =
    if lh > rh
    then 1
    else if lh < rh
         then -1
         else if ls > rs
              then -1
              else if ls < rs
                   then 1
                   else 0
  in List.sort comparator src *)

let join_lines (src: string list): string =
  String.concat "" src

let count_subseq (src: string): Int64.t =
  let open Int64 in
  let (+) = Int64.add in
  let ret = ref zero in
  let cur_s = ref zero in
  String.iter (function
    | 's' -> cur_s := !cur_s + Int64.one
    | 'h' -> ret := !ret + !cur_s
    | _ -> ()
  ) src;
  !ret

let debug_string (src: string): string =
  print_endline src;
  src

let () =
  Scanf.scanf "%u\n" identity |>
    read_lines |>
    preprocess_lines |>
    sort_lines |>
    postprocess_lines |>
    join_lines |>
    (* debug_string |> *)
    count_subseq |> Int64.to_string |>
    print_endline

let identity x = x

let read_lines (n: int): string list =
  let rec read_single l i =
    if i == n then l
    else read_single (Scanf.scanf "%s\n" identity :: l) (i + 1)
  in read_single [] 0

let count_of (cc: char) (src: string): int =
  let ret = ref 0 in
  String.iter (fun c -> if c == cc then ret := !ret + 1) src;
  !ret

let preprocess_lines (src: string list): (string * int * int) list =
  List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src

let postprocess_lines (src: (string * int * int) list): string list =
  List.map (fun (str, s, h) -> str) src

let sort_lines (src: (string * int * int) list): (string * int * int) list =
  let l, il = List.partition (fun (ss, s, h) -> h != 0) src in
  let l = List.map (fun (ss, s, h) -> (ss, s, h, (float_of_int s) /. (float_of_int h))) l in
  let comparator (_, _, _, lr) (_, _, _, rr) = -(compare lr rr) in
  let l = List.sort comparator l in
  il @ List.map (fun (ss, s, h, _) -> (ss, s, h)) l
  (* let comparator (lss, ls, lh) (rss, rs, rh) =
    if lh > rh
    then 1
    else if lh < rh
         then -1
         else if ls > rs
              then -1
              else if ls < rs
                   then 1
                   else 0
  in List.sort comparator src *)

let join_lines (src: string list): string =
  String.concat "" src

let count_subseq (src: string): int =
  let ret = ref 0 in
  let cur_s = ref 0 in
  String.iter (function
    | 's' -> cur_s := !cur_s + 1
    | 'h' -> ret := !ret + !cur_s
    | _ -> ()
  ) src;
  !ret

let debug_string (src: string): string =
  print_endline src;
  src

let () =
  Scanf.scanf "%u\n" identity |>
    read_lines |>
    preprocess_lines |>
    sort_lines |>
    postprocess_lines |>
    join_lines |>
    debug_string |>
    count_subseq |> string_of_int |>
    print_endline

let identity x = x

let read_lines (n: int): string list =
  let rec read_single l i =
    if i == n then l
    else read_single (Scanf.scanf "%s\n" identity :: l) (i + 1)
  in read_single [] 0

let count_of (cc: char) (src: string): int =
  let ret = ref 0 in
  String.iter (fun c -> if c == cc then ret := !ret + 1) src;
  !ret

let preprocess_lines (src: string list): (string * int * int) list =
  List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src

let postprocess_lines (src: (string * int * int) list): string list =
  List.map (fun (str, s, h) -> str) src

let sort_lines (src: (string * int * int) list): (string * int * int) list =
  let comparator (lss, ls, lh) (rss, rs, rh) =
    if lh > rh
    then 1
    else if lh < rh
         then -1
         else if ls > rs
              then -1
              else if ls < rs
                   then 1
                   else 0
  in List.sort comparator src

let join_lines (src: string list): string =
  String.concat "" src

let count_subseq (src: string): int =
  let ret = ref 0 in
  let cur_s = ref 0 in
  String.iter (function
    | 's' -> cur_s := !cur_s + 1
    | 'h' -> ret := !ret + !cur_s
    | _ -> ()
  ) src;
  !ret

let () =
  Scanf.scanf "%u\n" identity;
  Scanf.scanf "%s\n" identity;
  Scanf.scanf "%s\n" identity;
  Scanf.scanf "%s\n" identity;
  Scanf.scanf "%s\n" identity |> print_endline;
(*
let () =
  Scanf.scanf "%u\n" identity |>
    read_lines |>
    preprocess_lines |>
    sort_lines |>
    postprocess_lines |>
    join_lines |>
    count_subseq |> string_of_int |>
    print_endline *)

let identity x = x
let () =
  Scanf.scanf "%u" identity;
  print_endline "h";

let identity x = x

let read_lines (n: int): string list =
  let rec read_single l i =
    if i == n then l
    else read_single (Scanf.scanf "%s\n" identity :: l) (i + 1)
  in read_single [] 0

let count_of (cc: char) (src: string): int =
  let ret = ref 0 in
  String.iter (fun c -> if c == cc then ret := !ret + 1) src;
  !ret

let preprocess_lines (src: string list): (string * int * int) list =
  List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src

let postprocess_lines (src: (string * int * int) list): string list =
  List.map (fun (str, s, h) -> str) src

let sort_lines (src: (string * int * int) list): (string * int * int) list =
  let l, il = List.partition (fun (ss, s, h) -> h != 0) src in
  let l = List.map (fun (ss, s, h) -> (ss, s, h, (float_of_int s) /. (float_of_int h))) l in
  let comparator (_, _, _, lr) (_, _, _, rr) = -(compare lr rr) in
  let l = List.sort comparator l in
  il @ List.map (fun (ss, s, h, _) -> (ss, s, h)) l
  (* let comparator (lss, ls, lh) (rss, rs, rh) =
    if lh > rh
    then 1
    else if lh < rh
         then -1
         else if ls > rs
              then -1
              else if ls < rs
                   then 1
                   else 0
  in List.sort comparator src *)

let join_lines (src: string list): string =
  String.concat "" src

let count_subseq (src: string): int =
  let ret = ref 0 in
  let cur_s = ref 0 in
  String.iter (function
    | 's' -> cur_s := !cur_s + 1
    | 'h' -> ret := !ret + !cur_s
    | _ -> ()
  ) src;
  !ret

let debug_string (src: string): string =
  print_endline src;
  src

let () =
  Scanf.scanf "%u\n" identity |>
    read_lines |>
    preprocess_lines |>
    sort_lines |>
    postprocess_lines |>
    join_lines |>
    (* debug_string |> *)
    count_subseq |> string_of_int |>
    print_endline

let identity x = x

let read_lines (n: int): string list =
  let rec read_single l i =
    if i == n then l
    else read_single (Scanf.scanf "%s\n" identity :: l) (i + 1)
  in read_single [] 0

let count_of (cc: char) (src: string): int =
  let ret = ref 0 in
  String.iter (fun c -> if c == cc then ret := !ret + 1) src;
  !ret

let preprocess_lines (src: string list): (string * int * int) list =
  List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src

let postprocess_lines (src: (string * int * int) list): string list =
  List.map (fun (str, s, h) -> str) src

let sort_lines (src: (string * int * int) list): (string * int * int) list =
  let comparator (lss, ls, lh) (rss, rs, rh) =
    if lh > rh
    then 1
    else if lh < rh
         then -1
         else if ls > rs
              then -1
              else if ls < rs
                   then 1
                   else 0
  in List.sort comparator src

let join_lines (src: string list): string =
  String.concat "" src

let count_subseq (src: string): int =
  let ret = ref 0 in
  let cur_s = ref 0 in
  String.iter (function
    | 's' -> cur_s := !cur_s + 1
    | 'h' -> ret := !ret + !cur_s
    | _ -> ()
  ) src;
  !ret

let () =
  Scanf.scanf "%u\n" identity |>
    read_lines |>
    preprocess_lines |>
    sort_lines |>
    postprocess_lines |>
    join_lines |>
    count_subseq |> string_of_int |>
    print_endline

let identity x = x

let read_lines (n: int): string list =
  let rec read_single l i =
    if i == n then l
    else read_single (input_line stdin :: l) (i + 1)
  in read_single [] 0

let count_of (cc: char) (src: string): int =
  let ret = ref 0 in
  String.iter (fun c -> if c == cc then ret := !ret + 1) src;
  !ret

let preprocess_lines (src: string list): (string * int * int) list =
  List.map (fun s -> (s, count_of 's' s, count_of 'h' s)) src

let postprocess_lines (src: (string * int * int) list): string list =
  List.map (fun (str, s, h) -> str) src

let sort_lines (src: (string * int * int) list): (string * int * int) list =
  let comparator (lss, ls, lh) (rss, rs, rh) =
    if lh > rh
    then 1
    else if lh < rh
         then -1
         else if ls > rs
              then -1
              else if ls < rs
                   then 1
                   else 0
  in List.sort comparator src

let join_lines (src: string list): string =
  String.concat "" src

let count_subseq (src: string): int =
  let ret = ref 0 in
  let cur_s = ref 0 in
  String.iter (function
    | 's' -> cur_s := !cur_s + 1
    | 'h' -> ret := !ret + !cur_s
    | _ -> ()
  ) src;
  !ret

let () =
  Scanf.scanf "%u" identity |>
    string_of_int |>
    print_endline