Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from $$$1$$$ to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains $$$3$$$ steps, and the second contains $$$4$$$ steps, she will pronounce the numbers $$$1, 2, 3, 1, 2, 3, 4$$$.You are given all the numbers pronounced by Tanya. How many stairways did she climb? Also, output the number of steps in each stairway.The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

The first line contains $$$n$$$ ($$$1 \le n \le 1000$$$) — the total number of numbers pronounced by Tanya. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — all the numbers Tanya pronounced while climbing the stairs, in order from the first to the last pronounced number. Passing a stairway with $$$x$$$ steps, she will pronounce the numbers $$$1, 2, \dots, x$$$ in that order. The given sequence will be a valid sequence that Tanya could have pronounced when climbing one or more stairways.

In the first line, output $$$t$$$ — the number of stairways that Tanya climbed. In the second line, output $$$t$$$ numbers — the number of steps in each stairway she climbed. Write the numbers in the correct order of passage of the stairways.

open Scanf
open Printf

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

let l = Array.to_list (Array.init n (fun i -> scanf " %d" (fun i -> i)))

let rec process_l l out =
  match l with
  | [] -> l, out
  | h::t ->
    if h > out then
      process_l t h
    else
      l, out

let rec process l out out_st =
  match l with
  | [] -> out, out_st
  | _ ->
    let l', st = process_l l 0 in
    process l' (out + 1) (st::out_st)

let () =
  let out, out_st = process l 0 [] in
  printf "%d\n" out;
  List.iter (fun i -> printf "%d " i) (List.rev out_st);
  ()

(* Codeforces 1005 A Tanya and Stairways *)

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

(* reading reversed list *)
let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;

let rec to_tania acc last l = match l with
	| [] -> last :: acc
	| h :: t -> match h with
			| 1 ->
				let lacc = if last == 0 then acc else last :: acc in
				to_tania lacc 1 t
			| _ -> to_tania acc h t;;

let main() =
	let n = gr () in
	let ra = readlist n [] in
	let a = List.rev ra in
	let ro = to_tania [] 0 a in
	let o = List.rev ro in
	let lno = List.length o in
	begin
		print_int lno;
		print_string "\n";
		printlisti o;
		print_string "\n"
	end;;

main();;

open Printf
let input_int_array n =
	Array.init n (fun _ -> Scanf.scanf " %d" (fun v -> v))

let get_int () = Scanf.scanf " %d" (fun v -> v)
let get_2_ints () = Scanf.scanf " %d %d" (fun u v -> u,v)
let get_3_ints () = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w)
let get_4_ints () = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x)
let get_5_ints () = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)

let print_int_endline n = n |> string_of_int |> print_endline

let () =
  let n = get_int ()
  in let ar = input_int_array n
  in
  let l = Array.fold_left (fun (c,l) v ->
    if v=c+1 then (v,l)
    else if v=1 then (v,c::l)
    else failwith ""
  ) (0,[]) ar
  |> (fun (last,l) -> last::l)
  |> List.rev
  in
  print_endline @@ (List.length l |> string_of_int);
  l |> List.iter (printf "%d ");
  print_newline ()


They say that Berland has exactly two problems, fools and roads. Besides, Berland has n cities, populated by the fools and connected by the roads. All Berland roads are bidirectional. As there are many fools in Berland, between each pair of cities there is a path (or else the fools would get upset). Also, between each pair of cities there is no more than one simple path (or else the fools would get lost). But that is not the end of Berland's special features. In this country fools sometimes visit each other and thus spoil the roads. The fools aren't very smart, so they always use only the simple paths.A simple path is the path which goes through every Berland city not more than once.The Berland government knows the paths which the fools use. Help the government count for each road, how many distinct fools can go on it.Note how the fools' paths are given in the input.

The first line contains a single integer n (2 ≤ n ≤ 105) — the number of cities.  Each of the next n - 1 lines contains two space-separated integers ui, vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that means that there is a road connecting cities ui and vi.  The next line contains integer k (0 ≤ k ≤ 105) — the number of pairs of fools who visit each other.  Next k lines contain two space-separated numbers. The i-th line (i > 0) contains numbers ai, bi (1 ≤ ai, bi ≤ n). That means that the fool number 2i - 1 lives in city ai and visits the fool number 2i, who lives in city bi. The given pairs describe simple paths, because between every pair of cities there is only one simple path.

Print n - 1 integer. The integers should be separated by spaces. The i-th number should equal the number of fools who can go on the i-th road. The roads are numbered starting from one in the order, in which they occur in the input.

NoteIn the first sample the fool number one goes on the first and third road and the fool number 3 goes on the second, first and fourth ones.In the second sample, the fools number 1, 3 and 5 go on the first road, the fool number 5 will go on the second road, on the third road goes the fool number 3, and on the fourth one goes fool number 1.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let es = Array.make n [] in
  let () =
    for i = 0 to n - 2 do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(u) <- (v, i) :: es.(u);
	es.(v) <- (u, i) :: es.(v);
    done
  in
  let es = Array.map Array.of_list es in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make k 0 in
  let b = Array.make k 0 in
  let () =
    for i = 0 to k - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1;
      b.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1;
    done
  in
  let min (x : int) y = if x < y then x else y in
  let used = Array.make n false in
  let pe = Array.make n (-1) in
  let tin = Array.make n (-1) in
  let tout = Array.make n (-1) in
  let t = ref 0 in
  let up = Array.make_matrix n 20 0 in
  let stack = Array.make (2 * n) (fun _ -> ()) in
  let stack_pos = ref 0 in
  let rec execute () =
    if !stack_pos > 0 then (
      decr stack_pos;
      let f = stack.(!stack_pos) in
	f ();
	execute ()
    )
  in
  (*let rec dfs3 u depth =
    used.(u) <- true;
    g1.(u) <- !pos;
    d.(!pos) <- depth;
    de.(!pos) <- u;
    incr pos;
    for i = 0 to Array.length es.(u) - 1 do
      let v = es.(u).(i) in
	if not used.(v) then (
	  dfs3 v (depth + 1);
	  g2.(u) <- !pos;
	  d.(!pos) <- depth;
	  de.(!pos) <- u;
	  incr pos;
	)
    done
  in*)
  let rec dfs3 u prev =
    used.(u) <- true;
    tin.(u) <- !t;
    tout.(u) <- !t;
    incr t;
    up.(u).(0) <- prev;
    for i = 1 to 19 do
      up.(u).(i) <- up.(up.(u).(i - 1)).(i - 1)
    done;
    let rec aux i =
      if i < Array.length es.(u) then (
	stack.(!stack_pos) <- (fun () -> aux (i + 1));
	incr stack_pos;
	let (v, edge) = es.(u).(i) in
	  if not used.(v) then (
	    let f () =
	      pe.(v) <- edge;
	      tout.(u) <- !t;
	      incr t;
	    in
	      stack.(!stack_pos) <- f;
	      incr stack_pos;
	      stack.(!stack_pos) <- (fun () -> dfs3 v u);
	      incr stack_pos;
	  )
      )
    in
      aux 0
  in
    stack_pos := 0;
    dfs3 0 0;
    execute ();
    let is_ancestor u v =
      tin.(u) <= tin.(v) && tout.(u) >= tout.(v)
    in
    let rec lca u v =
      if is_ancestor u v
      then u
      else if is_ancestor v u
      then v
      else (
	let u = ref u in
	  for i = 19 downto 0 do
	    if not (is_ancestor up.(!u).(i) v)
	    then u := up.(!u).(i)
	  done;
	  up.(!u).(0)
      )
    in
    let s = Array.make n 0 in
    let res = Array.make (n - 1) 0 in
      for i = 0 to k - 1 do
	let u = a.(i)
	and v = b.(i) in
	let w = lca u v in
	  s.(u) <- s.(u) + 1;
	  s.(v) <- s.(v) + 1;
	  s.(w) <- s.(w) - 2;
      done;
      let rec dfs u prev =
	let rec aux i =
	  if i < Array.length es.(u) then (
	    stack.(!stack_pos) <- (fun () -> aux (i + 1));
	    incr stack_pos;
	    let (v, edge) = es.(u).(i) in
	      if v <> prev then (
		let f () =
		  s.(u) <- s.(u) + s.(v)
		in
		  stack.(!stack_pos) <- f;
		  incr stack_pos;
		  stack.(!stack_pos) <- (fun () -> dfs v u);
		  incr stack_pos;
	      )
	  )
	in
	  aux 0
      in
	stack_pos := 0;
	dfs 0 0;
	execute ();
	for u = 0 to n - 1 do
	  if pe.(u) >= 0
	  then res.(pe.(u)) <- s.(u)
	done;
	for i = 0 to n - 2 do
	  Printf.printf "%d " res.(i)
	done;
	Printf.printf "\n"


There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:  Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i, j \leq n$$$; $$$i \neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\max(a)-\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of buildings. The second line of each test case contains $$$n$$$ space separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the heights of the buildings.

For each test case, output a single integer — the minimum possible ugliness of the buildings.

NoteIn the first test case, the ugliness is already $$$0$$$.In the second test case, you should do one operation, with $$$i = 1$$$ and $$$j = 3$$$. The new heights will now be $$$[2, 2, 2, 2]$$$, with an ugliness of $$$0$$$.In the third test case, you may do three operations:   with $$$i = 3$$$ and $$$j = 1$$$. The new array will now be $$$[2, 2, 2, 1, 5]$$$,  with $$$i = 5$$$ and $$$j = 4$$$. The new array will now be $$$[2, 2, 2, 2, 4]$$$,  with $$$i = 5$$$ and $$$j = 3$$$. The new array will now be $$$[2, 2, 3, 2, 3]$$$.  The resulting ugliness is $$$1$$$. It can be proven that this is the minimum possible ugliness for this test.

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

let rec to_arr = function
| (n, arr, i) ->
     if (i=n) then arr
     else begin
         arr.(i) <- read_int ();
         to_arr (n, arr, i+1)
     end
;;

let rec find_x = function
| (n, arr, p, i, j) ->
  (* Array.iter (fun x -> Printf.printf " %d" x) arr;
  print_newline (); *)
  (* print_int i; *)
    (* Printf.printf " %d %d %d\n" p i j; *)
     if (i==j) then begin
         if (arr.(i-1)<arr.(p)) then begin
         let temp_i = arr.(i-1) in
         arr.(i-1) <- arr.(p);
         arr.(p) <- temp_i;
         i
         end
        else
         p
     end
     else if (arr.(i)<=arr.(p) && arr.(j-1)>=arr.(p)) then find_x (n, arr, p, i+1, j-1)
     else if (arr.(i)<=arr.(p)) then find_x (n, arr, p, i+1, j)
     else if (arr.(j-1)>=arr.(p)) then find_x (n, arr, p, i, j-1)
     else begin
         let temp_i = arr.(i) in
         arr.(i) <- arr.(j-1);
         arr.(j-1) <- temp_i;
         find_x (n, arr, p, i+1, j-1)
     end
;;
(* 1, 5, 6, 2
   sort_arr (4, arr, 0, 1, 3)
   x = 0
   sort_arr (4, arr, 1, 2, 3)
   1, 5, 6, 2
   x = 2
    *)
let rec sort_arr = function
| (n, arr, p, i, j) ->
     let x = find_x (n, arr, p, i, j) in
     if ((x-1<n) && ((x-1)>(i+1))) then sort_arr (n, arr, i, i, (x-1));
     if ((x+1<n) && (x+1)<j) then sort_arr (n, arr, (x+1), (x+1), j);
;;

(* let arr = [|1; 5; 6; 2; 1; 8; 7; 3; 10; 9; 20; 15|] in
sort_arr (12, arr, 0, 0, 12);
Array.iter (fun x -> Printf.printf " %d" x) arr;; *)

let read_long () = Scanf.scanf " %Ld" (fun l -> l);;
let rec get_sum = function
| 0L -> Int64.zero
| n -> Int64.add (read_long ()) (get_sum (Int64.pred n))
;;

let run_case = function
| () ->
  let n = read_long () in
  let s = get_sum (n) in
  let m = Int64.sub s (Int64.mul (Int64.div s n) n) in
  if (m=0L) then Printf.printf "%d\n" 0
  else Printf.printf "%d\n" 1
;;

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

let t=read_int() in
iter_cases (t);;


You are given $$$n$$$ segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or $$$0$$$ in case the intersection is an empty set.For example, the intersection of segments $$$[1;5]$$$ and $$$[3;10]$$$ is $$$[3;5]$$$ (length $$$2$$$), the intersection of segments $$$[1;5]$$$ and $$$[5;7]$$$ is $$$[5;5]$$$ (length $$$0$$$) and the intersection of segments $$$[1;5]$$$ and $$$[6;6]$$$ is an empty set (length $$$0$$$).Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $$$(n - 1)$$$ segments has the maximal possible length.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 3 \cdot 10^5$$$) — the number of segments in the sequence. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i \le r_i \le 10^9$$$) — the description of the $$$i$$$-th segment.

Print a single integer — the maximal possible length of the intersection of $$$(n - 1)$$$ remaining segments after you remove exactly one segment from the sequence.

NoteIn the first example you should remove the segment $$$[3;3]$$$, the intersection will become $$$[2;3]$$$ (length $$$1$$$). Removing any other segment will result in the intersection $$$[3;3]$$$ (length $$$0$$$).In the second example you should remove the segment $$$[1;3]$$$ or segment $$$[2;6]$$$, the intersection will become $$$[2;4]$$$ (length $$$2$$$) or $$$[1;3]$$$ (length $$$2$$$), respectively. Removing any other segment will result in the intersection $$$[2;3]$$$ (length $$$1$$$).In the third example the intersection will become an empty set no matter the segment you remove.In the fourth example you will get the intersection $$$[3;10]$$$ (length $$$7$$$) if you remove the segment $$$[1;5]$$$ or the intersection $$$[1;5]$$$ (length $$$4$$$) if you remove the segment $$$[3;10]$$$.


Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.

The first line contains three integers: a, b, n (1 ≤ a, b, n ≤ 105).

In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.

(* Codeforces 246C KonkursKrasoti written *)

open String;;
open Hashtbl;;

let gr () = Scanf.scanf " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line Pervasives.stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let rec readlist n acc = match n with
	| 0 -> List.rev acc
	| _ -> readlist (n -1) (gr() :: acc);;

let debug = false;;

let a = gr();;
let b = gr();;
let n = gr();;
let ch = Array.make n 0;;

let rec nextchar ao c idx ca =
	if idx >= n then 0
	else if c > 9 then -1
	else if ((10 * ao + c) mod b) != 0 then nextchar ao (c +1) idx ca
	else
		let oo = 0 in
		begin
			ca.(idx) <- c;
			nextchar oo 0 (idx +1) ca
		end;;

let prichars a ca n =
	begin
		print_int a;
		for i = 1 to n do
			print_int ca.(i -1)
		done;
		print_newline()
	end;;

let main () =
	let ret = nextchar a 0 0 ch in
	if ret < 0 then begin print_int (-1); print_newline() end
	else prichars a ch n;;

main();;

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

let () =
    let a = read_int() in
    let b = read_int() in
    let n = read_int() in
    let rec f d = if d = 10 then (-1) else if (10*a+d) mod b = 0 then d else f (d+1) in
    let d = f 0 in
        if d = -1 then Printf.printf "-1\n"
        else (
            Printf.printf "%d%d" a d;
            for i = 1 to n-1 do Printf.printf "0" done;
            print_newline()
        )

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

let a = read_int () and b = read_int () and n = read_int () ;;

let result =
    let rec loop d =
        if d >= 10 then -1
        else if (a * 10 + d) mod b = 0 then (a * 10 + d)
        else loop (d + 1)
    in loop 0 ;;

Printf.printf "%d" result ;;

if result <> -1 then
    for i = 1 to n - 1 do
        Printf.printf "0"
    done ;;

Printf.printf "\n" ;;

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

let () =
  let a = read_int() in
  let b = read_int() in
  let n = read_int() in

  let rec first d = if d=10 then -1 else if (10*a+d) mod b = 0 then d else first (d+1) in

  let d = first 0 in
    if d = -1 then (
      Printf.printf "-1\n"
    ) else (
      Printf.printf "%d%d" a d;
      for i=1 to n-1 do Printf.printf "0" done;
      print_newline()
    )


A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.

The first input line contains integer k (1 ≤ k ≤ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000, where |s| is the length of string s.

Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print "-1" (without quotes).

open Scanf;;
open Printf;;
open Str;;

let split_by_space = split (regexp " +")

let rec head n ls =
  if n < 0 then invalid_arg "head : passed negative integer"
  else
    match (n, ls) with
      (0, _) -> []
    | (n, []) -> failwith "head : list is too short"
    | (n, x::xs) -> x :: (head (n - 1) xs)

let rec tail n ls =
  if n < 0 then invalid_arg "tail : passed negative integer"
  else
    match (n, ls) with
      (0, ls) -> ls
    | (n, []) -> failwith "tail : list is too short"
    | (n, x::xs) -> tail (n - 1) xs

module UF = struct
  type t = int array

  let make n = Array.make n (-1)

  let rec root x uf =
    if uf.(x) < 0 then x
    else (uf.(x) <- root uf.(x) uf; uf.(x))

  let union_set x y uf =
    let x = root x uf and
        y = root y uf in
    begin
      if x != y then
        let x, y = if uf.(y) < uf.(x) then y, x else x, y in
        begin
          uf.(x) <- uf.(x) + uf.(y);
          uf.(y) <- x
        end
    end;
    x != y

  let find_set x y uf = root x uf = root y uf

  let size x uf = - uf.(x)
end

let input () =
  let k = int_of_string (read_line ()) and
      s = read_line () in
  (k, s)

let rec rep i c =
  match i with
    0 -> []
  | n -> c :: rep (n - 1) c

let make_str l =
  List.fold_left (fun x y -> x ^ y) "" l

let rec repeat n s =
  match n with
    0 -> ""
  | n -> s ^ repeat (n - 1) s

let make_k_str arr n k =
  let a = Array.map (fun x -> x / k) arr in
  let l = ref [] in
  for i = 0 to 26 - 1 do
    l := (rep a.(i) (String.make 1 (Char.chr (i + Char.code 'a')))) @ !l
  done;
  let s = make_str !l in
  repeat k s

let solve (k, s) =
  let len = String.length s in
  if len mod k <> 0 then "-1"
  else if k = 1 then
    s
  else begin
    let arr = Array.make 26 0 in
    let a_code = Char.code 'a' in
    for i = 0 to len - 1 do
      let idx = Char.code (s.[i]) - a_code in
      arr.(idx) <- arr.(idx) + 1
    done;
    let n = len / k in
    if Array.fold_left (fun x y -> x && (y mod k = 0)) true arr then
      make_k_str arr n k
    else "-1"
  end

let () =
  let inp = input () in
  let res = solve inp in
  print_string (res ^ "\n")

open Scanf;;
open Printf;;
open Str;;

let split_by_space = split (regexp " +")

let rec head n ls =
  if n < 0 then invalid_arg "head : passed negative integer"
  else
    match (n, ls) with
      (0, _) -> []
    | (n, []) -> failwith "head : list is too short"
    | (n, x::xs) -> x :: (head (n - 1) xs)

let rec tail n ls =
  if n < 0 then invalid_arg "tail : passed negative integer"
  else
    match (n, ls) with
      (0, ls) -> ls
    | (n, []) -> failwith "tail : list is too short"
    | (n, x::xs) -> tail (n - 1) xs

module UF = struct
  type t = int array

  let make n = Array.make n (-1)

  let rec root x uf =
    if uf.(x) < 0 then x
    else (uf.(x) <- root uf.(x) uf; uf.(x))

  let union_set x y uf =
    let x = root x uf and
        y = root y uf in
    begin
      if x != y then
        let x, y = if uf.(y) < uf.(x) then y, x else x, y in
        begin
          uf.(x) <- uf.(x) + uf.(y);
          uf.(y) <- x
        end
    end;
    x != y

  let find_set x y uf = root x uf = root y uf

  let size x uf = - uf.(x)
end

let input () =
  let k = int_of_string (read_line ()) and
      s = read_line () in
  (k, s)

let rec rep i c =
  match i with
    0 -> []
  | n -> c :: rep (n - 1) c

let make_str l =
  List.fold_left (fun x y -> x ^ y) "" l

let rec repeat n s =
  match n with
    0 -> ""
  | n -> s ^ repeat (n - 1) s

let make_k_str arr n k =
  let a = Array.map (fun x -> x / n) arr in
  let l = ref [] in
  for i = 0 to 26 - 1 do
    l := (rep a.(i) (String.make 1 (Char.chr (i + Char.code 'a')))) @ !l
  done;
  let s = make_str !l in
  repeat n s

let solve (k, s) =
  let len = String.length s in
  if len mod k <> 0 then "-1"
  else begin
    let arr = Array.make 26 0 in
    let a_code = Char.code 'a' in
    for i = 0 to len - 1 do
      let idx = Char.code (s.[i]) - a_code in
      arr.(idx) <- arr.(idx) + 1
    done;
    let n = len / k in
    if Array.fold_left (fun x y -> x && (y mod n = 0)) true arr then
      make_k_str arr n k
    else "-1"
  end

let () =
  let inp = input () in
  let res = solve inp in
  print_string (res ^ "\n")

open Scanf;;
open Printf;;
open Str;;

let split_by_space = split (regexp " +")

let rec head n ls =
  if n < 0 then invalid_arg "head : passed negative integer"
  else
    match (n, ls) with
      (0, _) -> []
    | (n, []) -> failwith "head : list is too short"
    | (n, x::xs) -> x :: (head (n - 1) xs)

let rec tail n ls =
  if n < 0 then invalid_arg "tail : passed negative integer"
  else
    match (n, ls) with
      (0, ls) -> ls
    | (n, []) -> failwith "tail : list is too short"
    | (n, x::xs) -> tail (n - 1) xs

module UF = struct
  type t = int array

  let make n = Array.make n (-1)

  let rec root x uf =
    if uf.(x) < 0 then x
    else (uf.(x) <- root uf.(x) uf; uf.(x))

  let union_set x y uf =
    let x = root x uf and
        y = root y uf in
    begin
      if x != y then
        let x, y = if uf.(y) < uf.(x) then y, x else x, y in
        begin
          uf.(x) <- uf.(x) + uf.(y);
          uf.(y) <- x
        end
    end;
    x != y

  let find_set x y uf = root x uf = root y uf

  let size x uf = - uf.(x)
end

let input () =
  let k = int_of_string (read_line ()) and
      s = read_line () in
  (k, s)

let rec rep i c =
  match i with
    0 -> []
  | n -> c :: rep (n - 1) c

let make_str l =
  List.fold_left (fun x y -> x ^ y) "" l

let rec repeat n s =
  match n with
    0 -> ""
  | n -> s ^ repeat (n - 1) s

let make_k_str arr n k =
  let a = Array.map (fun x -> x / n) arr in
  let l = ref [] in
  for i = 0 to 26 - 1 do
    l := (rep a.(i) (String.make 1 (Char.chr (i + Char.code 'a')))) @ !l
  done;
  let s = make_str !l in
  repeat n s

let solve (k, s) =
  let len = String.length s in
  if len mod k <> 0 then "-1"
  else if k = 1 then
    s
  else begin
    let arr = Array.make 26 0 in
    let a_code = Char.code 'a' in
    for i = 0 to len - 1 do
      let idx = Char.code (s.[i]) - a_code in
      arr.(idx) <- arr.(idx) + 1
    done;
    let n = len / k in
    if Array.fold_left (fun x y -> x && (y mod n = 0)) true arr then
      make_k_str arr n k
    else "-1"
  end

let () =
  let inp = input () in
  let res = solve inp in
  print_string (res ^ "\n")


Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.

If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes).

NoteIn the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".

let a_count = ref 0 and
    d_count = ref 0 and
    n = int_of_string (read_line ()) and
    s = read_line () in
for i = 0 to n - 1 do
 begin
   a_count := !a_count + (if s.[i] = 'A' then 1 else 0);
   d_count := !d_count + (if s.[i] = 'D' then 1 else 0);
 end
done;
print_string ( if a_count = d_count then "Friendship"
    else if  a_count > d_count then "Anton"
    else "Danik"
)

let () =
  Scanf.scanf "%d " @@ fun n ->
  let anton = ref 0 in
  let danik = ref 0 in
  Scanf.scanf "%s " @@ String.iter (function 'A' -> incr anton | 'D' -> incr danik | _ -> failwith "");
  if !anton = !danik then
    print_endline "Friendship"
  else if !anton > !danik then
    print_endline "Anton"
  else
    print_endline "Danik"

let char_count s len c =
  let rec cc i sum =
    if i = len then
      sum
    else
      let n = if s.[i] = c then 1 else 0 in
      cc (i + 1) (sum + n)
  in cc 0 0

let n = read_int () ;;
let s = read_line () ;;
let a = char_count s n 'A'
and d = char_count s n 'D'
in
if a = d then
  print_string "Friendship\n"
else if a > d then
  print_string "Anton\n"
else
  print_string "Danik\n"
;;

let _ = read_int () in
let str = read_line () in

let trans c = match c with
| 'A' ->  1
| 'D' -> -1
| _   ->  0 in

let rec count_ad s i l =
        if i >= l then 0
        else (count_ad s (i+1) l) + trans s.[i] in

let get_output c =
        if c = 0 then "Friendship"
        else if c > 0 then "Anton"
        else "Danik" in

print_endline (get_output (count_ad str 0 (String.length str)))

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

let solve list =
    let anton_wins = List.length (List.filter (fun c -> c = 'A') list) in
    let danik_wins = List.length (List.filter (fun c -> c = 'D') list) in
    if anton_wins = danik_wins
    then
        "Friendship"
    else
        if anton_wins > danik_wins
        then
            "Anton"
        else
            "Danik"

let print result = Printf.printf "%s\n" result
let () = print (solve (input ()))


Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.

The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj).

In a single line print a single integer — the answer to the problem.

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

let read_pair () = let a = read_int () in (a , read_int ());;

let n , k = read_pair ();;

let data = Array.init n (fun i -> read_pair ());;

let ans = ref 0 and  cnt = ref 0;;
for i = 0 to (n-1) do
     let first , second = data.(i) in
           cnt := !cnt + (second - first + 1)
done;;

if (!cnt) mod k = 0 then Printf.printf "0\n"
else Printf.printf "%d\n" ( ((!cnt)/k + 1)*k - (!cnt)) ;;


After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?

The first line contains an integer $$$n$$$ ($$$0 \leq n \leq 10^{9}$$$) — the number of turns. Next 3 lines contain 3 ribbons of Kuro, Shiro and Katie one per line, respectively. Each ribbon is a string which contains no more than $$$10^{5}$$$ uppercase and lowercase Latin letters and is not empty. It is guaranteed that the length of all ribbons are equal for the purpose of fairness. Note that uppercase and lowercase letters are considered different colors.

Print the name of the winner ("Kuro", "Shiro" or "Katie"). If there are at least two cats that share the maximum beauty, print "Draw".

7
treasurehunt
threefriends
hiCodeforces

NoteIn the first example, after $$$3$$$ turns, Kuro can change his ribbon into ooooo, which has the beauty of $$$5$$$, while reaching such beauty for Shiro and Katie is impossible (both Shiro and Katie can reach the beauty of at most $$$4$$$, for example by changing Shiro's ribbon into SSiSS and changing Katie's ribbon into Kaaaa). Therefore, the winner is Kuro.In the fourth example, since the length of each of the string is $$$9$$$ and the number of turn is $$$15$$$, everyone can change their ribbons in some way to reach the maximal beauty of $$$9$$$ by changing their strings into zzzzzzzzz after 9 turns, and repeatedly change their strings into azzzzzzzz and then into zzzzzzzzz thrice. Therefore, the game ends in a draw.

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create (26 * 2) 0 in
  for i = 0 to String.length src - 1 do
    let idx =
      let ccode = String.get src i |> Char.code in
      if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')
      then ccode - Char.code 'A'
      else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')
      then ccode - Char.code 'a' + 26
      else raise Not_found
    in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let get_beauty n l a =
  if n <= l - a
  then a + n
  else if l - a <= 1 && n < 2 then l - 1 else l

let max_map_list (src: int list): int * int =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let max_beauty (n: int) (l: int) (map: int array) =
  Array.map (get_beauty n l) map |> max_map |> snd

let print_list (l: int list): unit =
  List.iter (fun i -> Printf.printf "%d " i) l;
  print_newline ()

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let max_beauties = List.map (max_beauty n l) maps in
  (* let _ = print_list max_beauties in *)
  let (i, max) = max_map_list max_beauties in
  let ret =
    if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1
    then None
    else Some i
  in
  ret |> result |> print_endline

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create 128 0 in
  for i = 0 to String.length src - 1 do
    let idx = (String.get src i |> Char.code) - Char.code 'A' in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let maxes = List.map max_map maps in
  let drawed = List.filter (fun (i, v) -> l - v <= n) maxes |> List.length > 1 in
  if drawed
  then result None |> print_endline
  else maxes |>
       max_map_i |>
       fst |> (fun i -> Some i) |>
       result |> print_endline

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create (26 * 2) 0 in
  for i = 0 to String.length src - 1 do
    let idx =
      let ccode = String.get src i |> Char.code in
      if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')
      then ccode - Char.code 'A'
      else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')
      then ccode - Char.code 'a' + 26
      else raise Not_found
    in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let get_beauty n l a =
  if n <= l - a
  then a + n
  else l

let max_map_list (src: int list): int * int =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let max_beauty (n: int) (l: int) (map: int array) =
  Array.map (get_beauty n l) map |> max_map |> snd

let print_list (l: int list): unit =
  List.iter (fun i -> Printf.printf "%d " i) l;
  print_newline ()

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let max_beauties = List.map (max_beauty n l) maps in
  let _ = print_list max_beauties in
  let (i, max) = max_map_list max_beauties in
  let ret =
    if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1
    then None
    else Some i
  in
  ret |> result |> print_endline

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create (26 * 2) 0 in
  for i = 0 to String.length src - 1 do
    let idx =
      let ccode = String.get src i |> Char.code in
      if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')
      then ccode - Char.code 'A'
      else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')
      then ccode - Char.code 'a' + 26
      else raise Not_found
    in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let get_beauty n l a =
  if n <= l - a
  then a + n
  else
    let t = (a + n) mod l in
    max t (l - t)

let max_map_list (src: int list): int * int =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let max_beauty (n: int) (l: int) (map: int array) =
  Array.map (get_beauty n l) map |> max_map |> snd

let print_list (l: int list): unit =
  List.iter (fun i -> Printf.printf "%d " i) l;
  print_newline ()

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let max_beauties = List.map (max_beauty n l) maps in
  (* let _ = print_list max_beauties in *)
  let (i, max) = max_map_list max_beauties in
  let ret =
    if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1
    then None
    else Some i
  in
  ret |> result |> print_endline

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create 128 0 in
  for i = 0 to String.length src - 1 do
    let idx = (String.get src i |> Char.code) - Char.code 'A' in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let get_beauty n l a =
  let ret = (a + n) mod l in
  if ret = 0 then l else ret

let max_map_list (src: int list): int * int =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let max_beauty (n: int) (l: int) (map: int array) =
  Array.map (fun v -> if v != 0 then get_beauty n l v else 0) map |> max_map |> snd

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let maxes = List.map max_map maps in
  let max_beauties = List.map (max_beauty n l) maps in
  let (i, max) = max_map_list max_beauties in
  let ret =
    if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1
    then None
    else Some i
  in
  ret |> result |> print_endline

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create (26 * 2) 0 in
  for i = 0 to String.length src - 1 do
    let idx =
      let ccode = String.get src i |> Char.code in
      if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')
      then ccode - Char.code 'A'
      else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')
      then ccode - Char.code 'a' + 26
      else raise Not_found
    in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let get_beauty n l a =
  if n <= l - a
  then a + n
  else if l - a > 1 then l else l - 1

let max_map_list (src: int list): int * int =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let max_beauty (n: int) (l: int) (map: int array) =
  Array.map (get_beauty n l) map |> max_map |> snd

let print_list (l: int list): unit =
  List.iter (fun i -> Printf.printf "%d " i) l;
  print_newline ()

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let max_beauties = List.map (max_beauty n l) maps in
  (* let _ = print_list max_beauties in *)
  let (i, max) = max_map_list max_beauties in
  let ret =
    if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1
    then None
    else Some i
  in
  ret |> result |> print_endline

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create (26 * 2) 0 in
  for i = 0 to String.length src - 1 do
    let idx =
      let ccode = String.get src i |> Char.code in
      if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')
      then ccode - Char.code 'A'
      else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')
      then ccode - Char.code 'a' + 26
      else raise Not_found
    in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let get_beauty n l a =
  if n <= l - a
  then a + n
  else l

let max_map_list (src: int list): int * int =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let max_beauty (n: int) (l: int) (map: int array) =
  Array.map (get_beauty n l) map |> max_map |> snd

let print_list (l: int list): unit =
  List.iter (fun i -> Printf.printf "%d " i) l;
  print_newline ()

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let max_beauties = List.map (max_beauty n l) maps in
  (* let _ = print_list max_beauties in *)
  let (i, max) = max_map_list max_beauties in
  let ret =
    if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1
    then None
    else Some i
  in
  ret |> result |> print_endline

let list_init n f =
  Array.init n f |> Array.to_list

let input_ribbons (n: int): string list =
  list_init n (fun i -> Scanf.scanf " %s" (fun v -> v))

let ribbon_to_map (src: string): int array =
  (* NOTE: there is a gap between ASCII 'Z' and 'a'! *)
  let ret = Array.create (26 * 2) 0 in
  for i = 0 to String.length src - 1 do
    let idx =
      let ccode = String.get src i |> Char.code in
      if ccode >= (Char.code 'A') && ccode <= (Char.code 'Z')
      then ccode - Char.code 'A'
      else if ccode >= (Char.code 'a') && ccode <= (Char.code 'z')
      then ccode - Char.code 'a' + 26
      else raise Not_found
    in
    ret.(idx) <- ret.(idx) + 1
  done;
  ret

let max_map (src: int array): int * int =
    let src = Array.mapi (fun i v -> (i, v)) src in
    Array.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let min_map (src: int array): int * int =
  let src = Array.mapi (fun i v -> (i, v)) src in
  let f ((mi, mv) as m) ((i, v) as n) =
    match v with
    | 0 -> m
    | _ when v < mv -> n
    | _ -> m
  in
  Array.fold_left f src.(0) src

let result (winner: int option): string =
  match winner with
  | None -> "Draw"
  | Some i ->
    match i with
    | 0 -> "Kuro"
    | 1 -> "Shiro"
    | 2 -> "Katie"
    | _ -> raise Not_found

let get_beauty n l a =
  if n <= l - a
  then a + n
  else if l - a > 1 && n < 2 then l else l - 1

let max_map_list (src: int list): int * int =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (fun ((mi, mv) as m) ((i, v) as n) -> if mv > v then m else n)
      (0, 0) src

let max_map_i (src: (int * int) list): int * (int * int) =
    let src = List.mapi (fun i v -> (i, v)) src in
    List.fold_left (
      fun ((mi, (mj, mv)) as m) ((i, (j, v)) as n) ->
        if mv > v then m else n)
      (List.hd src) src

let max_beauty (n: int) (l: int) (map: int array) =
  Array.map (get_beauty n l) map |> max_map |> snd

let print_list (l: int list): unit =
  List.iter (fun i -> Printf.printf "%d " i) l;
  print_newline ()

let () =
  let _ = Printexc.record_backtrace true in
  let n = Scanf.scanf " %u" (fun v -> v) in
  let ribbons = input_ribbons 3 in
  let l = ribbons |> List.hd |> String.length in
  let maps = List.map ribbon_to_map ribbons in
  let max_beauties = List.map (max_beauty n l) maps in
  (* let _ = print_list max_beauties in *)
  let (i, max) = max_map_list max_beauties in
  let ret =
    if max_beauties |> List.filter (fun v -> v = max) |> List.length > 1
    then None
    else Some i
  in
  ret |> result |> print_endline


n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.

The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1). The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).

Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.

NoteLet's consider first example:   In the first step child 4 is eliminated, child 5 becomes the leader.  In the second step child 2 is eliminated, child 3 becomes the leader.  In the third step child 5 is eliminated, child 6 becomes the leader.  In the fourth step child 6 is eliminated, child 7 becomes the leader.  In the final step child 1 is eliminated, child 3 becomes the leader.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.init n (fun i -> i + 1) in
  let a = ref (Array.to_list a) in
  let rotate a =
    match a with
      | x :: xs ->
	  xs @ [x]
      | [] -> assert false
  in
    for i = 0 to k - 1 do
      let c = Scanf.bscanf sb "%d " (fun s -> s) in
      let c = c mod (n - i) in
	for j = 1 to c do
	  a := rotate !a;
	done;
	match !a with
	  | x :: a' ->
	      Printf.printf "%d " x;
	      a := a'
	  | [] -> assert false
    done;
    Printf.printf "\n"


Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))":  1st bracket is paired with 8th,  2d bracket is paired with 3d,  3d bracket is paired with 2d,  4th bracket is paired with 7th,  5th bracket is paired with 6th,  6th bracket is paired with 5th,  7th bracket is paired with 4th,  8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported:  «L» — move the cursor one position to the left,  «R» — move the cursor one position to the right,  «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation "D" below.  All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.Polycarp is very proud of his development, can you implement the functionality of his editor?

The first line contains three positive integers n, m and p (2 ≤ n ≤ 500 000, 1 ≤ m ≤ 500 000, 1 ≤ p ≤ n) — the number of brackets in the correct bracket sequence, the number of operations and the initial position of cursor. Positions in the sequence are numbered from left to right, starting from one. It is guaranteed that n is even. It is followed by the string of n characters "(" and ")" forming the correct bracket sequence. Then follow a string of m characters "L", "R" and "D" — a sequence of the operations. Operations are carried out one by one from the first to the last. It is guaranteed that the given operations never move the cursor outside the bracket sequence, as well as the fact that after all operations a bracket sequence will be non-empty.

Print the correct bracket sequence, obtained as a result of applying all operations to the initial sequence.

NoteIn the first sample the cursor is initially at position 5. Consider actions of the editor:  command "R" — the cursor moves to the position 6 on the right;  command "D" — the deletion of brackets from the position 5 to the position 6. After that CBS takes the form (())(), the cursor is at the position 5;  command "L" — the cursor moves to the position 4 on the left;  command "D" — the deletion of brackets from the position 1 to the position 4. After that CBS takes the form (), the cursor is at the position 1. Thus, the answer is equal to ().

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 m = read_int () in
  let p = read_int () in
  let s = read_string() in
  let moves = read_string() in

  let next = Array.init n (fun i -> if i=n-1 then -1 else i+1) in
  let prev = Array.init n (fun i -> i-1) in

  let pairing = Array.make n 0 in

  let rec scan i stack = if i<n then (
    match s.[i] with
      | '(' -> scan (i+1) (i::stack)
      | ')' ->
	let j = List.hd stack in
	pairing.(j) <- i;
	pairing.(i) <- j;
	scan (i+1) (List.tl stack)
      | _ -> failwith "bad string"
  ) in

  scan 0 [];

  let c = ref (p-1) in  (* the curson *)

  let do_L () =
    c := prev.(!c);
    if !c = -1 then failwith "bad L";
  in

  let do_R () =
    c := next.(!c);
    if !c = -1 then failwith "bad R";
  in

  let do_D () =
    let i = !c in
    let j = pairing.(i) in
    let (i,j) = (min i j, max i j) in
    let (pi, nj) = (prev.(i), next.(j)) in
    if pi >= 0 then next.(pi) <- nj;
    if nj >= 0 then prev.(nj) <- pi;
    if next.(j) >= 0 then c := next.(j)
    else if prev.(i) >= 0 then c:= prev.(i)
    else failwith "bad move"
  in

  for i=0 to m-1 do
    match moves.[i] with
      | 'L' -> do_L ()
      | 'R' -> do_R ()
      | 'D' -> do_D ()
      | _-> failwith "bad op"
  done;

  let rec findleft () =
    if prev.(!c) = -1 then !c
    else (
      c := prev.(!c);
      findleft ()
    )
  in

  let rec loop i = if i >= 0 then (
    printf "%c" s.[i];
    loop next.(i)
  ) in

  loop (findleft());
  print_newline()


A country called Flatland is an infinite two-dimensional plane. Flatland has n cities, each of them is a point on the plane.Flatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four distinct straight lines, such that two of them are parallel to the Ox axis, and two others are parallel to the Oy axis. At that, no straight line can go through any city. Thus, Flatland will be divided into 9 parts, and each son will be given exactly one of these parts. Circle IV thought a little, evaluated his sons' obedience and decided that the i-th son should get the part of Flatland that has exactly ai cities.Help Circle find such four straight lines that if we divide Flatland into 9 parts by these lines, the resulting parts can be given to the sons so that son number i got the part of Flatland which contains ai cities.

The first line contains integer n (9 ≤ n ≤ 105) — the number of cities in Flatland. Next n lines each contain two space-separated integers: xi, yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th city. No two cities are located at the same point. The last line contains nine space-separated integers: .

If there is no solution, print a single integer -1. Otherwise, print in the first line two distinct real space-separated numbers: x1, x2 — the abscissas of the straight lines that are parallel to the Oy axis. And in the second line print two distinct real space-separated numbers: y1, y2 — the ordinates of the straight lines, parallel to the Ox. If there are multiple solutions, print any of them.  When the answer is being checked, a city is considered to lie on a straight line, if the distance between the city and the line doesn't exceed 10 - 6. Two straight lines are considered the same if the distance between them doesn't exceed 10 - 6.

NoteThe solution for the first sample test is shown below:  The solution for the second sample test is shown below:  There is no solution for the third sample test.

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

let size tree = match tree with Empty -> 0 | Node(_, _, _, (size,_)) -> size
let depth tree = match tree with Empty -> 0 | Node(_, _, _, (_,depth)) -> depth

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

let newNode (l, x, r) = Node(l, x, r, (1 + (size l) + (size r), 1 + max (depth l) (depth r)))

let rec build_path p t path =
(* the node this finds is either the rightmost that is <= p or the leftmost that is > p *)
  match t with
    | Empty -> failwith "failed build_path"
    | Node(left, x, right, _) ->
	if p < x then if left<>Empty then build_path p left (Item(t, Left)::path) else (t,path)
	else if (* p >= x && *) right<>Empty then build_path p right (Item(t, Right)::path)
	else (t,path)

let rec build_deep_path t path =
(* finds the deepest node in the tree *)
  match t with
    | Empty -> failwith "failed build_deep_path"
    | Node(Empty, _, Empty, _) -> (t,path)
    | Node(left, _, right, _) ->
	if depth left >= depth right
	then build_deep_path left (Item(t, Left)::path)
	else build_deep_path right (Item(t, Right)::path)

(* 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,[]) -> t
  | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->
      rsplay (newNode(tL,tK,newNode(tR,bK,newNode(bR,cK,cR))), tail)

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

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

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

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

let splay t p =
  if t=Empty then t else rsplay (build_path p t [])

let splaydeep t =
  if t=Empty then t else rsplay (build_deep_path t [])

let split t x =
  (* split the list of segments in two.  The first part is all the keys <=x
     the rest is all keys > x. *)
  if t=Empty then (Empty,Empty) else
    let (left, k, right) = getroot (splay t x) in
      if k <= x
      then (newNode(left, k, Empty), right)
      else (left, newNode(Empty, k, right))

let balance t =
  let rec lg n = if n <= 1 then 0 else 1 + lg (n/2) in
  let l = lg (size t) in
  let rec loop t =
    if (depth t)-1 <= 4*l then t else loop (splaydeep t)
  in
    loop t

let insert t x = let (left, right) = split t x in balance (newNode(left, x, right))

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

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

let main () =
  let n = read_int() in
  let px = Array.make n 0 in
  let py = Array.make n 0 in
  let p = Array.init n (
    fun i ->
      let (x,y) = read_pair() in
	px.(i) <- x;
	py.(i) <- y;
	(x,y)
  ) in

  let a = Array.init 9 (fun _ -> read_int()) in

  let () = Array.sort compare px in
  let () = Array.sort compare py in
  let () = Array.sort compare p in

  let tree = Array.make (n+1) Empty in
  let rec make_trees i ac =
    tree.(i) <- ac;
    if i=n then () else make_trees (i+1) (insert ac (snd p.(i)))
  in
  let () = make_trees 0 Empty in

  let valid_split () = (* return (true,(x0,x1,y0,y1)) if this permutation of the array works *)
    let sum l = List.fold_left (fun ac e -> ac + a.(e)) 0 l in

    let split_ok pp pop = pop = n || pop = 0 || pp.(pop-1) <> pp.(pop) in

    let spt pp pop =
      if pop=0 then (float pp.(0)) -. 0.5
      else (float pp.(pop-1)) +. 0.5
    in

    let left1 = sum [0;3;6] in
    let left2 = left1 + sum [1;4;7] in
    let bot1 = sum [6;7;8] in
    let bot2 = bot1 + sum [3;4;5] in

    if (split_ok px left1) && (split_ok px left2) && (split_ok py bot1) && (split_ok py bot2) && (
      (* tree.(left1) and tree.(left2) are the two trees we're interested in *)
      let y b = if b>0 then py.(b-1) else py.(0)-1 in
      let (y1,y2) = (y bot1, y bot2) in
	  size (fst (split tree.(left1) y1)) = sum[6] &&
	  size (fst (split tree.(left1) y2 )) = sum[3;6] &&
	  size (fst (split tree.(left2) y1)) = sum[6;7] &&
	  size (fst (split tree.(left2) y2)) = sum[3;4;6;7]
    ) then (true, (spt px left1, spt px left2, spt py bot1, spt py bot2)) else (false, (0.0,0.0,0.0,0.0))
  in

  let swap i j =
    let t = a.(i) in
      a.(i) <- a.(j);
      a.(j) <- t
  in

  let rec gen_perm i = if i=9 then fst (valid_split ()) else
    let rec loop j = if j=9 then false else (
      swap i j;
      if gen_perm (i+1) then true else (
	swap i j;
	loop (j+1)
      )
    )
    in
      loop i
  in

    if gen_perm 0 then (
      let (_,(x1,x2,y1,y2)) = valid_split () in
	Printf.printf "%.1f %.1f\n%.1f %.1f\n" x1 x2 y1 y2;
    ) else (
      Printf.printf "-1\n"
    )
;;
main()


Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $$$n$$$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements. Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $$$0$$$, and removing $$$i$$$-th character increases the ambiguity by $$$a_i$$$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $$$4$$$ even though you delete it from the string had).Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the statement. The second line contains one string $$$s$$$ of length $$$n$$$, consisting of lowercase Latin letters — the statement written by Vasya. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 998244353$$$).

Print minimum possible ambiguity of the statement after Vasya deletes some (possibly zero) characters so the resulting statement is easy.

NoteIn the first example, first two characters are removed so the result is ardh.In the second example, $$$5$$$-th character is removed so the result is hhzawde.In the third example there's no need to remove anything.

open Printf
let read_string () = Scanf.bscanf Scanf.Scanning.stdin " %s" (fun x -> x)
let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
let read_long_int () = Scanf.bscanf Scanf.Scanning.stdin " %Ld" (fun x -> x)
let (+) x y = Int64.add x y

let () =
    let n = read_int() in
    let s = read_string() in
    let tab = Array.make n 0L in
    let h = ref 0L and a = ref 0L and r = ref 0L and d = ref 0L in

    for i = 0 to n - 1 do
        tab.(i) <- read_long_int()
    done;

    for i = 0 to n - 1 do
        if s.[i] = 'h' then h := !h + tab.(i)
        else if s.[i] = 'a' then a := min !h (!a + tab.(i))
        else if s.[i] = 'r' then r := min !a (!r + tab.(i))
        else if s.[i] = 'd' then d := min !r (!d + tab.(i))
    done;

    printf "%Ld\n" !d

let max_i64,(++) = Int64.(shift_left 1L 60,add);;
Scanf.(Array.(
  scanf " %d %s" @@ fun n s ->
    let t = "hard" in
    let a = init n (fun _ -> scanf " %Ld" @@ fun v -> v)
    in
    let dp = make_matrix (n+2) 5 max_i64 in
    let update i j v =
      dp.(i).(j) <- min dp.(i).(j) v
    in
    dp.(0).(0) <- 0L;
    for i=1 to n do
      for j=0 to 3 do
        if s.[i-1] = t.[j] then (
          update i (j+1) @@ dp.(i-1).(j);
          update i j     @@ dp.(i-1).(j) ++ a.(i-1)
        ) else (
          update i j     @@ dp.(i-1).(j)
        )
      done
    done;
    (* for i=0 to n do
      for j=0 to 4 do
        Printf.printf "%Ld " dp.(i).(j)
      done;
      print_newline ()
    done; *)
    Printf.printf "%Ld" @@
      List.fold_left min max_i64 @@
        List.tl @@ List.rev @@ to_list dp.(n)
))

open Printf
let read_string () = Scanf.bscanf Scanf.Scanning.stdin " %s" (fun x -> x)
let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)

let () =
    let n = read_int() in
    let s = read_string() in
    let tab = Array.make n 0 in
    let h = ref 0 and a = ref 0 and r = ref 0 and d = ref 0 in

    for i = 0 to n - 1 do
        tab.(i) <- read_int()
    done;

    for i = n - 1 downto 0 do
        if s.[i] = 'd' then d := !d + tab.(i)
        else if s.[i] = 'r' && !d <> 0 then r := !r + tab.(i)
        else if s.[i] = 'a' && !r <> 0 then a := !a + tab.(i)
        else if s.[i] = 'h' && !a <> 0 then h := !h + tab.(i)
    done;

    if !h = 0 then printf "0\n"
    else printf "%d\n" (min (min !h !a) (min !r !d))

open Printf
let read_string () = Scanf.bscanf Scanf.Scanning.stdin " %s" (fun x -> x)
let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
let read_long_int () = Scanf.bscanf Scanf.Scanning.stdin " %Ld" (fun x -> x)
let (+) x y = Int64.add x y

let () =
    let n = read_int() in
    let s = read_string() in
    let tab = Array.make n 0L in
    let h = ref 0L and a = ref 0L and r = ref 0L and d = ref 0L in

    for i = 0 to n - 1 do
        tab.(i) <- read_long_int()
    done;

    for i = n - 1 downto 0 do
        if s.[i] = 'd' then d := !d + tab.(i)
        else if s.[i] = 'r' && !d <> 0L then r := !r + tab.(i)
        else if s.[i] = 'a' && !r <> 0L then a := !a + tab.(i)
        else if s.[i] = 'h' && !a <> 0L then h := !h + tab.(i)
    done;

    if !h = 0L then printf "0\n"
    else printf "%Ld\n" (min (min !h !a) (min !r !d))

let max_i64,(++) = Int64.(max_int,add);;
Scanf.(Array.(
  scanf " %d %s" @@ fun n s ->
    let t = "hard" in
    let a = init n (fun _ -> scanf " %Ld" @@ fun v -> v)
    in
    let dp = make_matrix (n+2) 5 max_i64 in
    let update i j v =
      dp.(i).(j) <- min dp.(i).(j) v
    in
    dp.(0).(0) <- 0L;
    for i=1 to n do
      for j=0 to 3 do
        if s.[i-1] = t.[j] then (
          update i (j+1) @@ dp.(i-1).(j);
          update i j     @@ dp.(i-1).(j) ++ a.(i-1)
        ) else (
          update i j     @@ dp.(i-1).(j)
        )
      done
    done;
    (* for i=0 to n do
      for j=0 to 4 do
        Printf.printf "%Ld " dp.(i).(j)
      done;
      print_newline ()
    done; *)
    Printf.printf "%Ld" @@ fold_left min max_i64 dp.(n)
))

let max_i64,(++) = Int64.(shift_left 1L 60,add);;
Scanf.(Array.(
  scanf " %d %s" @@ fun n s ->
    let t = "hard" in
    let a = init n (fun _ -> scanf " %Ld" @@ fun v -> v)
    in
    let dp = make_matrix (n+2) 5 max_i64 in
    let update i j v =
      if v>=0L then dp.(i).(j) <- min dp.(i).(j) v
    in
    dp.(0).(0) <- 0L;
    for i=1 to n do
      for j=0 to 3 do
        if s.[i-1] = t.[j] then (
          update i (j+1) @@ dp.(i-1).(j);
          update i j     @@ dp.(i-1).(j) ++ a.(i-1)
        ) else (
          update i j     @@ dp.(i-1).(j)
        )
      done
    done;
    (* for i=0 to n do
      for j=0 to 4 do
        Printf.printf "%Ld " dp.(i).(j)
      done;
      print_newline ()
    done; *)
    Printf.printf "%Ld" @@ fold_left min max_i64 dp.(n)
));;


Grandma Capa has decided to knit a scarf and asked Grandpa Sher to make a pattern for it, a pattern is a string consisting of lowercase English letters. Grandpa Sher wrote a string $$$s$$$ of length $$$n$$$.Grandma Capa wants to knit a beautiful scarf, and in her opinion, a beautiful scarf can only be knit from a string that is a palindrome. She wants to change the pattern written by Grandpa Sher, but to avoid offending him, she will choose one lowercase English letter and erase some (at her choice, possibly none or all) occurrences of that letter in string $$$s$$$.She also wants to minimize the number of erased symbols from the pattern. Please help her and find the minimum number of symbols she can erase to make string $$$s$$$ a palindrome, or tell her that it's impossible. Notice that she can only erase symbols equal to the one letter she chose.A string is a palindrome if it is the same from the left to the right and from the right to the left. For example, the strings 'kek', 'abacaba', 'r' and 'papicipap' are palindromes, while the strings 'abb' and 'iq' are not.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$2 \cdot t$$$ lines contain the description of test cases. The description of each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the string. The second line of each test case contains the string $$$s$$$ consisting of $$$n$$$ lowercase English letters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print the minimum number of erased symbols required to make the string a palindrome, if it is possible, and $$$-1$$$, if it is impossible.

5
8
abcaacab
6
xyzxyz
4
abba
8
rprarlap
10
khyyhhyhky

NoteIn the first test case, you can choose a letter 'a' and erase its first and last occurrences, you will get a string 'bcaacb', which is a palindrome. You can also choose a letter 'b' and erase all its occurrences, you will get a string 'acaaca', which is a palindrome as well.In the second test case, it can be shown that it is impossible to choose a letter and erase some of its occurrences to get a palindrome.In the third test case, you don't have to erase any symbols because the string is already a palindrome.

let solve_char (s: string) (c: char) =
  let n = String.length s in
  let rec solve_char_ s i j res =
    if i >= j then
      res
    else if (s.[i] == s.[j]) then
      solve_char_ s (i+1) (j-1) res
    else if (s.[i] == c) then
      solve_char_ s (i+1) j (res + 1)
    else if (s.[j] == c) then
      solve_char_ s i (j-1) (res + 1)
    else
      max_int
  in solve_char_ s 0 (n-1) 0

let solve (s: string) =
  let res = ref (solve_char s 'a') in
  let c = ref 'b' in
  while (!c <= 'z') do
    res := min (!res) (solve_char s !c);
    c := char_of_int (succ (int_of_char (!c)))
  done;
  if !res = max_int then
    -1
  else !res

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


A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.

The first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer a (1 ≤ a ≤ 2) which denotes the number of the rail at which the person was holding.

Print character "R" if the VIP is right-handed or "L" if he is left-handed.

let () =
	let in_data = open_in "input.txt" in
	let out_data = open_out "output.txt" in
	let _ = Scanf.fscanf in_data "%s %d" (fun d p ->
		let bp = (p = 1) in
		let bd = (d = "front") in
		Printf.fprintf out_data "%s" (
			if bp <> bd then "R" else "L"
		)
	) in
	let _ = close_out out_data in
	close_in in_data
;;


Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he:   will buy exactly $$$n$$$ shovels in total;  the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.

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, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.

Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.

NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.

let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let t = Scanf.sscanf (read_line ()) "%d" @@ fun t -> t

let rec f1 acc n i =
  if i * i > n then acc
  else f1 (if n mod i = 0 then (n / i) :: i :: acc else acc) n (i + 1)

let rec f n k =
  let acc = f1 [] n 2 |> List.sort compare in
  (* List.map string_of_int acc |> String.concat " " |> print_endline; *)
  let a = List.fold_left (fun s t -> if t <= k then t else s) 1 acc in
  (* Printf.printf "a = %d\n" a; *)
  n / a

let () = for _ = 1 to t do
  let (n, k) = Scanf.sscanf (read_line ()) "%d %d" @@ fun n k -> (n, k) in
  if n <= k then print_endline "1"
  else Printf.printf "%d\n" @@ f n k
done


You are given an array $$$a[0 \ldots n-1]$$$ of length $$$n$$$ which consists of non-negative integers. Note that array indices start from zero.An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $$$i$$$ ($$$0 \le i \le n - 1$$$) the equality $$$i \bmod 2 = a[i] \bmod 2$$$ holds, where $$$x \bmod 2$$$ is the remainder of dividing $$$x$$$ by 2.For example, the arrays [$$$0, 5, 2, 1$$$] and [$$$0, 17, 0, 3$$$] are good, and the array [$$$2, 4, 6, 7$$$] is bad, because for $$$i=1$$$, the parities of $$$i$$$ and $$$a[i]$$$ are different: $$$i \bmod 2 = 1 \bmod 2 = 1$$$, but $$$a[i] \bmod 2 = 4 \bmod 2 = 0$$$.In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).Find the minimum number of moves in which you can make the array $$$a$$$ good, or say that this is not possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 40$$$) — the length of the array $$$a$$$. The next line contains $$$n$$$ integers $$$a_0, a_1, \ldots, a_{n-1}$$$ ($$$0 \le a_i \le 1000$$$) — the initial array.

For each test case, output a single integer — the minimum number of moves to make the given array $$$a$$$ good, or -1 if this is not possible.

NoteIn the first test case, in the first move, you can swap the elements with indices $$$0$$$ and $$$1$$$, and in the second move, you can swap the elements with indices $$$2$$$ and $$$3$$$.In the second test case, in the first move, you need to swap the elements with indices $$$0$$$ and $$$1$$$.In the third test case, you cannot make the array good.

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

let () =
  let t = read_int () in
  for i = 1 to t do
    let n = read_int () in
    let (a, b) =
      let rec loop a b = function
        | 0 -> (a, b)
        | m ->
            let x = read_int () in
            if not ((x mod 2) = ((n-m) mod 2)) then
              if ((n-m) mod 2) = 0 then
                loop (a+1) b (m-1)
              else
                loop a (b+1) (m-1)
            else
              loop a b (m-1)
      in loop 0 0 n
    in
    if not (a = b) then Printf.printf "-1\n" else Printf.printf "%d\n" a
  done

let read_ints () =
  let str = read_line () in
  List.map (fun x -> int_of_string x) (Str.split (Str.regexp " +") str)
;;

let rec count (num : int list) (modi : int) (ind : int)=
  match num with
  |[] -> 0
  |h :: t -> if ((ind mod 2) <> modi && h mod 2 = modi) then 1 + count t modi (ind + 1) else count t modi (ind + 1)
;;

let rec main (t : int) =
  if t = 0 then
    ()
  else
    (
      let siz = read_int () in
      let a = read_ints () in
      let one_zero = count a 0 0 in
      let zero_one = count a 1 0 in
      if (one_zero <> zero_one) then print_endline "-1" else print_endline (string_of_int one_zero);
      main (t - 1)
    )
;;
let t = read_int() in
main t


One day Vasya was on a physics practical, performing the task on measuring the capacitance. He followed the teacher's advice and did as much as n measurements, and recorded the results in the notebook. After that he was about to show the results to the teacher, but he remembered that at the last lesson, the teacher had made his friend Petya redo the experiment because the largest and the smallest results differed by more than two times. Vasya is lazy, and he does not want to redo the experiment. He wants to do the task and go home play computer games. So he decided to cheat: before Vasya shows the measurements to the teacher, he will erase some of them, so as to make the largest and the smallest results of the remaining measurements differ in no more than two times. In other words, if the remaining measurements have the smallest result x, and the largest result y, then the inequality y ≤ 2·x must fulfill. Of course, to avoid the teacher's suspicion, Vasya wants to remove as few measurement results as possible from his notes.Help Vasya, find what minimum number of measurement results he will have to erase from his notes so that the largest and the smallest of the remaining results of the measurements differed in no more than two times.

The first line contains integer n (2 ≤ n ≤ 105) — the number of measurements Vasya made. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 5000) — the results of the measurements. The numbers on the second line are separated by single spaces.

Print a single integer — the minimum number of results Vasya will have to remove.

NoteIn the first sample you can remove the fourth and the sixth measurement results (values 8 and 7). Then the maximum of the remaining values will be 5, and the minimum one will be 3. Or else, you can remove the third and fifth results (both equal 3). After that the largest remaining result will be 8, and the smallest one will be 4.

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

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

let () =
  let n = read_int() in
  let c = Array.init n (fun i -> read_int()) in
  let () = Array.sort compare c in

  let rec loop i j ac =
    if i=n then ac else
      if j >= n-1 || c.(j+1) > 2*c.(i) then
	loop (i+1) j (max (j-i+1) ac)
      else loop i (j+1) ac
  in

  let a = loop 0 0 0 in
    print_string (Printf.sprintf "%d\n" (n-a))

open Scanf;;
open Array;;
open Printf;;

(*print_endline "begin";;
 *)

let file_in = "input.txt";;
let file_out = "output.txt";;

let ic = open_in file_in;;
let n = Scanf.bscanf (Scanf.Scanning.from_channel ic) "%d " (fun x -> x);;
let a = Array.make n 0;;

(*print_endline "xx";;
 *)
let () =
  for i = 0 to n-1 do
    let x = Scanf.bscanf (Scanf.Scanning.from_channel ic) "%d " (fun x -> x) in
    a.(i) <- x
  done in
    Array.sort (fun x y -> y - x) a
;;

(*Array.iter (fun x -> print_int x; print_endline "") a;;
 *)

close_in ic;;

let my_min x y = if x < y then x else y;;

exception Found;;

let nrow =
  let row = ref 0 in
  let i = ref (n - 1) in
  try
    while (!i >=0) do
      if a.(0) <= (2*a.(!i)) then raise Found;
      row := !row + 1;
      i:=!i-1
    done; !row+1
  with Found -> !row+1;;

let ncol =
  let col = ref 0 in
  let i = ref 0 in
  try
    while (!i < n) do
      if 2*a.(n-1) >= a.(!i) then raise Found;
      col := !col + 1;
      i:=!i+1
    done; !col+1
  with Found -> !col+1;;

let biggest = max_int;;
let b = Array.make_matrix nrow ncol 0;;
(*Initialize the matrix*)
let () =
  for i = ncol-1 downto 1 do
    b.(nrow-1).(i) <- biggest
  done;
  for i = nrow-1 downto 1 do
    b.(i).(ncol-1) <- biggest
  done
;;

let () =
  b.(nrow-1).(0) <- nrow - 1;
  b.(0).(ncol-1) <- ncol -1
;;

let my_min x y z = min (min x y) (min y z);;

  (*
for i = ncol-2 downto 0 do
  for j = nrow -2 downto 0 do
    let x = b.(j+1).(i) in
    let y = b.(j).(i+1) in
    let z = if a.(nrow - 1 - j) > 2*a.(n-1 - (ncol-1 - i)) then biggest else (ncol-1-i)+(nrow-1-j)
    in
    b.(j).(i) <- (my_min x y z)
  done
done; let oc = open_out file_out in
      if b.(0).(0) = biggest then
	Printf.fprintf oc "%d\n" 1
      else
	Printf.fprintf oc "%d\n" b.(0).(0);;
   *)

let ncold = ncol -1 in
let nrowd = nrow -1 in
let rec find_b00 i j =
  match i,j with
    (0, ncold) -> nrowd
   |(x, ncold) when x>0 -> biggest
   |(nrowd, 0) -> ncold
   |(nrowd, x) when x>0 -> nrowd
   |_ ->
     begin
       let x = find_b00 (j+1) (i) in
       let y = find_b00 (j) (i+1) in
       let z = if a.(nrow - 1 - j) > 2*a.(n-1 - (ncol-1 - i)) then biggest else (ncol-1-i)+(nrow-1-j)
       in
       my_min x y z
     end
    in let rslt = find_b00 0 0 in
       let oc = open_out file_out in
       Printf.fprintf oc "%d\n" rslt;;

open Scanf;;
open Array;;
open Printf;;

(* This version uses binary search and rec
 *)

let file_in = "input.txt";;
let file_out = "output.txt";;

let ic = open_in file_in;;
let oc = open_out file_out;;

let n = Scanf.bscanf (Scanf.Scanning.from_channel ic) "%d " (fun x -> x);;
let a = Array.make n 0;;

let () =
  for i = 0 to n-1 do
    let x = Scanf.bscanf (Scanf.Scanning.from_channel ic) "%d " (fun x -> x) in
    a.(i) <- x
  done in
    Array.sort (fun x y -> y - x) a
;; (*array a is from large to small*)

(*
Array.iter (fun x -> print_int x; print_string " ") a;;
print_endline "\n-------";;
 *)

close_in ic;;

let my_min x y z = min (min x y ) (min y z )

exception Found;;

let rec b1search x ii jj =
  let mid = (ii+jj)/2 in
  if mid = ii then ii
  else
    if x > 2*a.(mid) then b1search x (mid+1) jj
    else b1search x ii mid
;;

let rec b2search x ii jj =
let mid = (ii+jj)/2 in
if mid = ii then ii
else
  if 2*x < a.(mid) then b2search x (mid+1) jj
  else b2search x ii mid
;;

(*let y = b1search 8 0 5 in
print_int y;;
 *)

let rec solve i j =
  if i >= j then 0
  else if
    a.(i) <= 2*a.(j)
  then i+(n-1-j)
  else
    begin
      let x = j-(b1search a.(i) i j) in (*b1search search for small value*)
      let y = (b2search a.(j) i j)-i in  (*b2 search searchh for large value*)
      let z = 2 + (solve (i+1) (j-1)) in
      my_min x y z;
    end
;;

let rslt = solve 0 (n-1)
    in
    Printf.fprintf oc "%d\n" rslt
;;

(*amazing: this version uses the technique of two pointers*)

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

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

let () =
  let n = read_int() in
  let c = Array.init n (fun i -> read_int()) in
  let () = Array.sort compare c in

  let rec loop i j ac =
    if i=j then ac else
      if c.(j) <= 2*c.(i) then
	loop (i+1) j (max (j-i+1) ac)
      else loop i (j-1) ac
  in

  let a = loop 0 (n-1) 0 in
    print_string (Printf.sprintf "%d\n" (n-a))


The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor.

In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them.

NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3.

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 read_string() = bscanf Scanning.stdib " %s " (fun x->x)
let () =
  let n = read_int() in
  let adj = Array.init n (fun _-> read_string()) in
  let a = Array.init n (fun _-> read_int()) in
  (* set.(i) = true means excluse i from party*)
  let set = Array.make n false in
  let count = Array.make n 0 in

  (* compute each person get how many msgs*)
  let compute() =
	Array.fill count 0 n 0;
	for i=0 to n-1 do
	  if set.(i) then
		for j=0 to n-1 do
		  if adj.(i).[j]='1' then count.(j)<-count.(j)+1
		done
	done
  in

  let rec find_bad_person i =
	if i>=n then i
	else
	  if a.(i)=count.(i) then i else find_bad_person (i+1)
  in

  let rec loop() =
	compute();
	let i = find_bad_person 0 in
	if i<n then (
	  set.(i)<-true;
	  loop()
	)
  in

  loop();
  let c = sum 0 (n-1) (fun i -> if set.(i) then 1 else 0) in
  printf "%d\n" c;

  for i=0 to n-1 do
	if set.(i) then printf "%d " (i+1)
  done;
  print_newline();

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 read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let adj = Array.init n (fun _ -> read_string()) in
  let a = Array.init n (fun _ -> read_int()) in

  let set = Array.make n false in
  let count = Array.make n 0 in

  let compute_count () =
    Array.fill count 0 n 0;
    for i=0 to n-1 do
      if set.(i) then
	for j=0 to n-1 do
	  if adj.(i).[j] = '1' then count.(j) <- count.(j) + 1
	done
    done
  in

  let rec find_correct_item i = if i=n then -1 else
      if a.(i) = count.(i) then i else find_correct_item (i+1)
  in

  let rec loop () =
    compute_count ();
    let k = find_correct_item 0 in
    if k >= 0 then (
      set.(k) <- true;
      loop ()
    )
  in

  loop ();

  let c = sum 0 (n-1) (fun i -> if set.(i) then 1 else 0) in

  printf "%d\n" c;

  for i=0 to n-1 do
    if set.(i) then printf "%d " (i+1)
  done;

  print_newline();

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 _ = Array.init n (fun _ -> read_string()) in
  let a = Array.init n (fun _ -> read_int()) in

  if a.(0) = 0 then (
    printf "1\n";
    printf "1\n"
  ) else (
    printf "0\n";
    printf "\n";
  )

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 _ = Array.init n (fun _ -> read_string()) in
  let a = Array.init n (fun _ -> read_int()) in

  if a.(0) = 0 then (
    printf "1\n";
    printf "1\n"
  ) else (
    printf "0\n"
  )