You are given an array $$$a_1, a_2, \dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \le a_2 \le \ldots \le a_n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases.  The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of array $$$a$$$.  The second line of each test case contains $$$n$$$ positive integers $$$a_1, a_2, \ldots a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array itself.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output "YES" if it is possible to make the array $$$a$$$ non-decreasing using the described operation, or "NO" if it is impossible to do so.

Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $$$a_1$$$ and $$$a_3$$$ first, and swap $$$a_1$$$ and $$$a_5$$$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation.

(* Codeforces 1401 C Mere Array train *)

(* 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 find_min minv a = match a with
	| [] -> minv
	| h :: t -> find_min (if minv < h then minv else h) t;;

let rec is_sorted a = match a with
	| [] -> true
	| l :: [] -> true
	| h0 :: h1 :: t ->
		if h0 > h1 then false
		else is_sorted (h1 :: t);;

let rec same_list a b = match a, b with
	| [],[] -> true
	| [], bb :: t -> false
	| aa :: t, [] -> false
	| aa :: ta, bb :: tb ->
		if aa != bb then false
		else same_list ta tb;;

(* extract list of elements not divisible on mn *)
let rec extract_ndiv mn a =
	List.filter (fun x -> (x mod mn) != 0) a;;

(* extract list 0 - divisible mn, 1 - not divisible *)
let divis_bits mn a =
	List.map (fun e -> if ((e mod mn) == 0) then 0 else 1) a;;

let do_one () =
    let n = gr() in
		let a = List.rev (readlist n []) in
		let sa = List.sort compare a in
		let mn = find_min 1000111222 a in
    let bta = divis_bits mn a in
    let btsa = divis_bits mn sa in
		if not (same_list bta btsa) then print_string "NO\n"
		else
			let ndl = extract_ndiv mn a in
			if not (is_sorted ndl) then print_string "NO\n"
			else print_string "YES\n";;

let do_all () =
    let t = gr () in
    for i = 1 to t do
        do_one ()
    done;;

let main() =
	do_all ();;

main();;


According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.You are given a jacket with n buttons. Determine if it is fastened in a right way.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of buttons on the jacket. The second line contains n integers ai (0 ≤ ai ≤ 1). The number ai = 0 if the i-th button is not fastened. Otherwise ai = 1.

In the only line print the word "YES" if the jacket is fastened in a right way. Otherwise print the word "NO".

let read_nums () =
    let s = read_line () in
    let n = int_of_string s in
    let s = read_line () in
    let nums = List.map int_of_string (Str.split (Str.regexp " ") s) in
    (n, nums)

;;

let rec sum nums acc = match nums with
    | [] ->  acc
    | hd :: tl -> sum tl (acc + hd)

;;

let get_ans () =

    let (n, nums) = read_nums () in
    let x = sum nums 0 in
    if (n = 1 && x = 1) then
        true
    else if (n > 1 && (n-1) = x) then
        true
    else
        false
;;

let r = get_ans () in
if r then
    print_string "YES\n"
else
    print_string "NO\n"

let () = Scanf.scanf "%d\n" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
    let s = Array.fold_left (+) 0 a in
    print_endline (if (n = 1 && s = 1) || (n > 1 && s = n - 1) then "YES" else "NO"))

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let cnt = ref 0 in
    for i = 1 to n do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
	if k = 0
	then incr cnt
    done;
    if (n > 1 && !cnt = 1) || (n = 1 && !cnt = 0)
    then Printf.printf "YES\n"
    else Printf.printf "NO\n"

let read_nums () =
    let s = read_line () in
    let n = int_of_string s in
    let s = read_line () in
    let nums = List.map int_of_string (Str.split (Str.regexp " ") s) in
    (n, nums)

;;

let rec sum nums acc = match nums with
    | [] ->  acc
    | hd :: tl -> sum tl (acc + hd)

let get_ans () =

    let (n, nums) = read_nums () in
    let x = sum nums 0 in
    (n = 1 && x = 1) || ((n-1) = x)

;;

let r = get_ans () in
if r then
    print_string "YES\n"
else
    print_string "NO\n"


People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:  every integer from 1 to n2 appears in the table exactly once;  in each row numbers are situated in increasing order;  the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.

The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.

First print the sum of the integers in the k-th column of the required table. Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on. If there are multiple suitable table, you are allowed to print any.

(* started 8:23 *)
open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))

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

  let m = Array.make_matrix n n 0 in

  let x = ref 1 in

  for i=0 to n-1 do
    for j=0 to k-1 do
      m.(i).(j) <- !x;
      x := !x + 1
    done
  done;

  x := n*n;

  for i=n-1 downto 0 do
    for j=n-1 downto k do
      m.(i).(j) <- !x;
      x := !x - 1
    done
  done;

  let answer = sum 0 (n-1) (fun i -> m.(i).(k)) 0 in

  printf "%d\n" answer;

  for i=0 to n-1 do
    for j=0 to n-1 do
      printf "%d " m.(i).(j)
    done;
    print_newline()
  done


By the age of three Smart Beaver mastered all arithmetic operations and got this summer homework from the amazed teacher:You are given a sequence of integers a1, a2, ..., an. Your task is to perform on it m consecutive operations of the following type:  For given numbers xi and vi assign value vi to element axi.  For given numbers li and ri you've got to calculate sum , where f0 = f1 = 1 and at i ≥ 2: fi = fi - 1 + fi - 2.  For a group of three numbers li ri di you should increase value ax by di for all x (li ≤ x ≤ ri). Smart Beaver planned a tour around great Canadian lakes, so he asked you to help him solve the given problem.

The first line contains two integers n and m (1 ≤ n, m ≤ 2·105) — the number of integers in the sequence and the number of operations, correspondingly. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each describes an operation. Each line starts with an integer ti (1 ≤ ti ≤ 3) — the operation type:    if ti = 1, then next follow two integers xi vi (1 ≤ xi ≤ n, 0 ≤ vi ≤ 105);  if ti = 2, then next follow two integers li ri (1 ≤ li ≤ ri ≤ n);  if ti = 3, then next follow three integers li ri di (1 ≤ li ≤ ri ≤ n, 0 ≤ di ≤ 105).  The input limits for scoring 30 points are (subproblem E1):    It is guaranteed that n does not exceed 100, m does not exceed 10000 and there will be no queries of the 3-rd type.  The input limits for scoring 70 points are (subproblems E1+E2):    It is guaranteed that there will be queries of the 1-st and 2-nd type only.  The input limits for scoring 100 points are (subproblems E1+E2+E3):    No extra limitations.

For each query print the calculated sum modulo 1000000000 (109).

let _ =
  let mm = 1000000000 in
  let mmm = 1000000000l in
  let mmmm = 1000000000L in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let add x y =
    let r =
      Int32.to_int
	(Int32.rem
	   (Int32.add
	      (Int32.of_int x)
	      (Int32.of_int y))
	   mmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let mul x y =
    let r =
      Int64.to_int
	(Int64.rem
	   (Int64.mul
	      (Int64.of_int x)
	      (Int64.of_int y))
	   mmmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let o = 131072 * 2 in
  (*let o = 16 in*)
  let fib = Array.make (o + 1) 0 in
  let _ =
    fib.(1) <- 1;
    for i = 2 to o do
      fib.(i) <- add fib.(i - 1) fib.(i - 2)
    done
  in
  let d = Array.make (o + 1) 0 in
  let shift ofs v v' =
    let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) v') in
      (*Printf.printf "shift %d %d %d  %d -> %d\n" ofs v v' fib.(ofs + 1) res;*)
      res
  in
  let a = Array.make (2 * o) 0 in
  let a' = Array.make (2 * o) 0 in
  let rec update i x l r k =
    if l = r then (
      a.(k) <- x;
      a'.(k) <- 0;
    ) else (
      let m = (l + r) / 2 in
	if i <= m
	then update i x l m (2 * k + 1)
	else update i x (m + 1) r (2 * k + 2);
	let a1 = a.(2 * k + 1) in
	let a2 = a.(2 * k + 2) in
	let a1' = a'.(2 * k + 1) in
	let a2' = a'.(2 * k + 2) in
	  a.(k) <- add a1 (shift (m - l + 1) a2 a2');
	  a'.(k) <- add a1' (shift (m - l + 0) a2 a2');
    )
  in
  let rec rmq x y l r k =
    if x <= l && r <= y
    then (
      shift (l - x) a.(k) a'.(k)
    ) else (
      let m = (l + r) / 2 in
	if m < x
	then rmq x y (m + 1) r (2 * k + 2)
	else if m >= y
	then rmq x y l m (2 * k + 1)
	else
	  let a1 = rmq x y l m (2 * k + 1)
	  and a2 = rmq x y (m + 1) r (2 * k + 2) in
	    add a1 a2
    )
  in
  let () =
    for i = 1 to n do
      d.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      update i d.(i) 1 o 0
    done;
  in
    for k = 1 to m do
(*for j = 0 to Array.length a - 1 do
  Printf.printf "%d " a.(j);
done;
Printf.printf "\n";*)
      let op = Scanf.bscanf sb "%d " (fun s -> s) in
	match op with
	  | 1 ->
	      let i = Scanf.bscanf sb "%d " (fun s -> s) in
	      let v = Scanf.bscanf sb "%d " (fun s -> s) in
		d.(i) <- v;
		update i v 1 o 0;
	  | 2 ->
	      let l = Scanf.bscanf sb "%d " (fun s -> s) in
	      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	      let res = rmq l r 1 o 0 in
		Printf.printf "%d\n" res;
	  | _ -> assert false
    done

let _ =
  let mm = 1000000000 in
  let mmm = 1000000000l in
  let mmmm = 1000000000L in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let add x y =
    let r =
      Int32.to_int
	(Int32.rem
	   (Int32.add
	      (Int32.of_int x)
	      (Int32.of_int y))
	   mmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let mul x y =
    let r =
      Int64.to_int
	(Int64.rem
	   (Int64.mul
	      (Int64.of_int x)
	      (Int64.of_int y))
	   mmmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let o = 131072 * 2 in
  (*let o = 16 in*)
  let fib = Array.make (o + 1) 0 in
  let _ =
    fib.(1) <- 1;
    for i = 2 to o do
      fib.(i) <- add fib.(i - 1) fib.(i - 2)
    done
  in
  let d = Array.make (o + 1) 0 in
  let shift pos ofs v =
    let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (add v (-d.(pos)))) in
      (*Printf.printf "shift %d %d %d  %d %d -> %d\n" pos ofs v d.(pos) fib.(ofs + 1) res;*)
      res
  in
  let a = Array.make (2 * o) 0 in
  let rec update i x l r k =
    if l = r then (
      a.(k) <- x;
    ) else (
      let m = (l + r) / 2 in
	if i <= m
	then update i x l m (2 * k + 1)
	else update i x (m + 1) r (2 * k + 2);
	let a1 = a.(2 * k + 1) in
	let a2 = a.(2 * k + 2) in
	  a.(k) <- add a1 (shift (m + 1) (m - l + 1) a2);
    )
  in
  let rec rmq x y l r k =
    if x <= l && r <= y
    then (
      a.(k)
    ) else (
      let m = (l + r) / 2 in
	if m < x
	then rmq x y (m + 1) r (2 * k + 2)
	else if m >= y
	then rmq x y l m (2 * k + 1)
	else
	  let a1 = rmq x y l m (2 * k + 1)
	  and a2 = rmq x y (m + 1) r (2 * k + 2) in
	    add a1 (shift (m + 1) (m - x + 1) a2)
    )
  in
  let () =
    for i = 1 to n do
      d.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      update i d.(i) 1 o 0
    done;
  in
    for k = 1 to m do
(*for j = 0 to Array.length a - 1 do
  Printf.printf "%d " a.(j);
done;
Printf.printf "\n";*)
      let op = Scanf.bscanf sb "%d " (fun s -> s) in
	match op with
	  | 1 ->
	      let i = Scanf.bscanf sb "%d " (fun s -> s) in
	      let v = Scanf.bscanf sb "%d " (fun s -> s) in
		d.(i) <- v;
	  | 2 ->
	      let l = Scanf.bscanf sb "%d " (fun s -> s) in
	      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	      let res = ref 0 in
		for i = l to r do
		  res := add !res (mul fib.(i - l + 1) d.(i))
		done;
		Printf.printf "%d\n" !res;
	  | _ -> assert false
    done

let _ =
  let mm = 1000000000 in
  let mmm = 1000000000l in
  let mmmm = 1000000000L in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let add x y =
    let r =
      Int32.to_int
	(Int32.rem
	   (Int32.add
	      (Int32.of_int x)
	      (Int32.of_int y))
	   mmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let mul x y =
    let r =
      Int64.to_int
	(Int64.rem
	   (Int64.mul
	      (Int64.of_int x)
	      (Int64.of_int y))
	   mmmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let o = 131072 * 2 in
  (*let o = 8 in*)
  let fib = Array.make (o + 1) 0 in
  let _ =
    fib.(1) <- 1;
    for i = 2 to o do
      fib.(i) <- add fib.(i - 1) fib.(i - 2)
    done
  in
  let d = Array.make (o + 1) 0 in
  let shift pos ofs v =
    let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (add v (-d.(pos)))) in
      (*Printf.printf "shift %d %d %d  %d %d -> %d\n" pos ofs v d.(pos) fib.(ofs + 1) res;*)
      res
  in
  let a = Array.make (2 * o) 0 in
  let rec update i x l r k =
    if l = r then (
      a.(k) <- x;
    ) else (
      let m = (l + r) / 2 in
	if i <= m
	then update i x l m (2 * k + 1)
	else update i x (m + 1) r (2 * k + 2);
	let a1 = a.(2 * k + 1) in
	let a2 = a.(2 * k + 2) in
	  a.(k) <- add a1 (shift (m + 1) (m - l + 1) a2);
    )
  in
  let rec rmq x y l r k =
    if x <= l && r <= y
    then (
      a.(k)
    ) else (
      let m = (l + r) / 2 in
	if m < x
	then rmq x y (m + 1) r (2 * k + 2)
	else if m >= y
	then rmq x y l m (2 * k + 1)
	else
	  let a1 = rmq x y l m (2 * k + 1)
	  and a2 = rmq x y (m + 1) r (2 * k + 2) in
	    add a1 (shift (m + 1) (m - x + 1) a2)
    )
  in
  let () =
    for i = 1 to n do
      d.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      update i d.(i) 1 o 0
    done;
  in
    for k = 1 to m do
(*for j = 0 to Array.length a - 1 do
  Printf.printf "%d " a.(j);
done;
Printf.printf "\n";*)
      let op = Scanf.bscanf sb "%d " (fun s -> s) in
	match op with
	  | 1 ->
	      let i = Scanf.bscanf sb "%d " (fun s -> s) in
	      let v = Scanf.bscanf sb "%d " (fun s -> s) in
		d.(i) <- v;
		update i v 1 o 0;
	  | 2 ->
	      let l = Scanf.bscanf sb "%d " (fun s -> s) in
	      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	      let res = rmq l r 1 o 0 in
		Printf.printf "%d\n" res;
	  | _ -> assert false
    done

let _ =
  let mm = 1000000000 in
  let mmm = 1000000000l in
  let mmmm = 1000000000L in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let add x y =
    let r =
      Int32.to_int
	(Int32.rem
	   (Int32.add
	      (Int32.of_int x)
	      (Int32.of_int y))
	   mmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let mul x y =
    let r =
      Int64.to_int
	(Int64.rem
	   (Int64.mul
	      (Int64.of_int x)
	      (Int64.of_int y))
	   mmmm)
    in
      if r < 0
      then r + mm
      else r
  in
  let o = 131072 * 2 in
  (*let o = 8 in*)
  let fib = Array.make (o + 1) 0 in
  let _ =
    fib.(1) <- 1;
    for i = 2 to o do
      fib.(i) <- add fib.(i - 1) fib.(i - 2)
    done
  in
  let d = Array.make (o + 1) 0 in
  let shift pos ofs v =
    let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (v - d.(pos))) in
      (*Printf.printf "shift %d %d %d  %d %d -> %d\n" pos ofs v d.(pos) fib.(ofs + 1) res;*)
      res
  in
  let a = Array.make (2 * o) 0 in
  let rec update i x l r k =
    if l = r then (
      a.(k) <- x;
    ) else (
      let m = (l + r) / 2 in
	if i <= m
	then update i x l m (2 * k + 1)
	else update i x (m + 1) r (2 * k + 2);
	let a1 = a.(2 * k + 1) in
	let a2 = a.(2 * k + 2) in
	  a.(k) <- add a1 (shift (m + 1) (m - l + 1) a2);
    )
  in
  let rec rmq x y l r k =
    if x <= l && r <= y
    then (
      a.(k)
    ) else (
      let m = (l + r) / 2 in
	if m < x
	then rmq x y (m + 1) r (2 * k + 2)
	else if m >= y
	then rmq x y l m (2 * k + 1)
	else
	  let a1 = rmq x y l m (2 * k + 1)
	  and a2 = rmq x y (m + 1) r (2 * k + 2) in
	    add a1 (shift (m + 1) (m - x + 1) a2)
    )
  in
  let () =
    for i = 1 to n do
      d.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      update i d.(i) 1 o 0
    done;
  in
    for k = 1 to m do
(*for j = 0 to Array.length a - 1 do
  Printf.printf "%d " a.(j);
done;
Printf.printf "\n";*)
      let op = Scanf.bscanf sb "%d " (fun s -> s) in
	match op with
	  | 1 ->
	      let i = Scanf.bscanf sb "%d " (fun s -> s) in
	      let v = Scanf.bscanf sb "%d " (fun s -> s) in
		d.(i) <- v;
		update i v 1 o 0;
	  | 2 ->
	      let l = Scanf.bscanf sb "%d " (fun s -> s) in
	      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	      let res = rmq l r 1 o 0 in
		Printf.printf "%d\n" res;
	  | _ -> assert false
    done

let _ =
  let mm = 1000000000 in
  let mmm = 1000000000l in
  let mmmm = 1000000000L in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let add x y =
    Int32.to_int
      (Int32.rem
	 (Int32.add
	    (Int32.of_int x)
	    (Int32.of_int y))
	 mmm)
  in
  let mul x y =
    Int64.to_int
      (Int64.rem
	 (Int64.mul
	    (Int64.of_int x)
	    (Int64.of_int y))
	 mmmm)
  in
  let o = 131072 * 2 in
  (*let o = 8 in*)
  let fib = Array.make (o + 1) 0 in
  let _ =
    fib.(1) <- 1;
    for i = 2 to o do
      fib.(i) <- add fib.(i - 1) fib.(i - 2)
    done
  in
  let d = Array.make (o + 1) 0 in
  let shift pos ofs v =
    let res = add (mul fib.(ofs + 1) v) (mul fib.(ofs) (v - d.(pos))) in
      (*Printf.printf "shift %d %d %d  %d %d -> %d\n" pos ofs v d.(pos) fib.(ofs + 1) res;*)
      res
  in
  let a = Array.make (2 * o) 0 in
  let rec update i x l r k =
    if l = r then (
      a.(k) <- x;
    ) else (
      let m = (l + r) / 2 in
	if i <= m
	then update i x l m (2 * k + 1)
	else update i x (m + 1) r (2 * k + 2);
	let a1 = a.(2 * k + 1) in
	let a2 = a.(2 * k + 2) in
	  a.(k) <- a1 + shift (m + 1) (m - l + 1) a2;
    )
  in
  let rec rmq x y l r k =
    if x <= l && r <= y
    then (
      a.(k)
    ) else (
      let m = (l + r) / 2 in
	if m < x
	then rmq x y (m + 1) r (2 * k + 2)
	else if m >= y
	then rmq x y l m (2 * k + 1)
	else
	  let a1 = rmq x y l m (2 * k + 1)
	  and a2 = rmq x y (m + 1) r (2 * k + 2) in
	    a1 + shift (m + 1) (m - x + 1) a2
    )
  in
  let () =
    for i = 1 to n do
      d.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      update i d.(i) 1 o 0
    done;
  in
    for k = 1 to m do
(*for j = 0 to Array.length a - 1 do
  Printf.printf "%d " a.(j);
done;
Printf.printf "\n";*)
      let op = Scanf.bscanf sb "%d " (fun s -> s) in
	match op with
	  | 1 ->
	      let i = Scanf.bscanf sb "%d " (fun s -> s) in
	      let v = Scanf.bscanf sb "%d " (fun s -> s) in
		d.(i) <- v;
		update i v 1 o 0;
	  | 2 ->
	      let l = Scanf.bscanf sb "%d " (fun s -> s) in
	      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	      let res = rmq l r 1 o 0 in
		Printf.printf "%d\n" res;
	  | _ -> assert false
    done


The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crime he/she has committed. The greater the number, the more severe his/her crime was.Then, the mayor told you to choose the c prisoners, who will be transferred to the other prison. He also imposed two conditions. They are,  The chosen c prisoners has to form a contiguous segment of prisoners.  Any of the chosen prisoner's crime level should not be greater then t. Because, that will make the prisoner a severe criminal and the mayor doesn't want to take the risk of his running away during the transfer. Find the number of ways you can choose the c prisoners.

The first line of input will contain three space separated integers n (1 ≤ n ≤ 2·105), t (0 ≤ t ≤ 109) and c (1 ≤ c ≤ n). The next line will contain n space separated integers, the ith integer is the severity ith prisoner's crime. The value of crime severities will be non-negative and will not exceed 109.

Print a single integer — the number of ways you can choose the c prisoners.

open Scanf
open Printf

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

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

let comp (l, r) x =
    if x > t then (0, r)
    else (l + 1, (if l + 1 >= c then r + 1 else r))

let () = printf "%d\n" (snd (Array.fold_left comp (0, 0) a))


Berland has n cities connected by m bidirectional roads. No road connects a city to itself, and each pair of cities is connected by no more than one road. It is not guaranteed that you can get from any city to any other one, using only the existing roads.The President of Berland decided to make changes to the road system and instructed the Ministry of Transport to make this reform. Now, each road should be unidirectional (only lead from one city to another).In order not to cause great resentment among residents, the reform needs to be conducted so that there can be as few separate cities as possible. A city is considered separate, if no road leads into it, while it is allowed to have roads leading from this city.Help the Ministry of Transport to find the minimum possible number of separate cities after the reform.

The first line of the input contains two positive integers, n and m — the number of the cities and the number of roads in Berland (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000).  Next m lines contain the descriptions of the roads: the i-th road is determined by two distinct integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the numbers of the cities connected by the i-th road. It is guaranteed that there is no more than one road between each pair of cities, but it is not guaranteed that from any city you can get to any other one, using only roads.

Print a single integer — the minimum number of separated cities after the reform.

NoteIn the first sample the following road orientation is allowed: , , .The second sample: , , , , .The third sample: , , , , .

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";; let pnl () = print_newline ();;
let b2i x = if x == true then 1 else 0;;
let dbg x = print_int(x); pnl();;

let n = scan_int() and m = scan_int();;
let rep = Array.init n (fun i -> i) and
    rnk = Array.make n 0 and czy = Array.make n false;;

let rec find x =
  if rep.(x) = x then x else begin
    rep.(x) <- find (rep.(x));
    rep.(x);
  end;;

let rec union a b =
  let rA = find a and rB = find b in
  if rA = rB then czy.(rA) <- true
  else begin
    if rnk.(rA) > rnk.(rB) then union rB rA
    else begin
      rep.(rB) <- rA;
      rnk.(rA) <- max (rnk.(rA)) (rnk.(rB) + 1);
      czy.(rA) <- czy.(rA) || czy.(rB);
    end;
  end;;

for i = 1 to m do
  let a = scan_int() - 1 and b = scan_int() - 1 in
  union a b;
done;;

let cnt = ref 0 and odw = Array.make n false;;
for i = 0 to n - 1 do
  let ojciec = find i in
  if odw.(ojciec) = false then begin
    if czy.(ojciec) = false then incr cnt;
    odw.(ojciec) <- true;
  end;
done;;

print_int !cnt;;


Fedya studies in a gymnasium. Fedya's maths hometask is to calculate the following expression:(1n + 2n + 3n + 4n) mod 5for given value of n. Fedya managed to complete the task. Can you? Note that given number n can be extremely large (e.g. it can exceed any integer type of your programming language).

The single line contains a single integer n (0 ≤ n ≤ 10105). The number doesn't contain any leading zeroes.

Print the value of the expression without leading zeros.

NoteOperation x mod y means taking remainder after division x by y.Note to the first sample:

let pf = Printf.printf ;;
let epf = Printf.eprintf ;;
let sf = Scanf.scanf ;;

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

module Array = ArrayLabels ;;
module List  = struct
  include ListLabels ;;
  let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;
  let rec drop n a =
    if n = 0 then a
    else match a with
    | [] -> failwith "cannot take"
    | x :: xs -> drop (n - 1) xs ;;
end
module H = Hashtbl ;;

let i n = Char.code n - Char.code '0' ;;

let () =
  sf "%s " (fun ss ->
    let l = String.length ss in
    let n =
      if l = 1 then i ss.[l - 1]
      else i ss.[l - 2] * 10 + i ss.[l - 1] in
    if n mod 4 = 0 then pf "4\n"
    else pf "0\n")
;;


Polycarp has $$$26$$$ tasks. Each task is designated by a capital letter of the Latin alphabet.The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".Help Polycarp find out if his teacher might be suspicious.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of days during which Polycarp solved tasks. The second line contains a string of length $$$n$$$, consisting of uppercase Latin letters, which is the order in which Polycarp solved the tasks.

For each test case output:    "YES", if the teacher cannot be suspicious;  "NO", otherwise.  You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB

(** https://codeforces.com/problemset/problem/1520/A *)

let has tbl elem =
    try
        let _ = Hashtbl.find tbl elem in
        true
    with
    | Not_found -> false

let is_distracted tasks =
    let len = String.length tasks and
    task_table = Hashtbl.create 26 in
    let rec helper i =
        if i = len
        then false
        else (
            let current_task = tasks.[i] and
            previous_task = tasks.[i-1] in
            if current_task <> previous_task
            then if has task_table current_task
                then true
                else (
                    Hashtbl.add task_table current_task true;
                    helper (i+1)
                )
            else helper (i+1)
        ) in
    Hashtbl.add task_table tasks.[0] true;
    helper 1

let solve_n nb_cases =
    let rec helper i =
        if i > 0
        then (
            let _ = read_int () and
            tasks = read_line () in
            (if is_distracted tasks then "NO" else "YES")
            |> print_endline;
            helper (i-1)
        ) in
    helper nb_cases

let () =
    let nb_cases = read_int () in
    solve_n nb_cases


There are $$$n$$$ logs, the $$$i$$$-th log has a length of $$$a_i$$$ meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game.errorgorn and maomao90 will take turns chopping the logs with errorgorn chopping first. On his turn, the player will pick a log and chop it into $$$2$$$ pieces. If the length of the chosen log is $$$x$$$, and the lengths of the resulting pieces are $$$y$$$ and $$$z$$$, then $$$y$$$ and $$$z$$$ have to be positive integers, and $$$x=y+z$$$ must hold. For example, you can chop a log of length $$$3$$$ into logs of lengths $$$2$$$ and $$$1$$$, but not into logs of lengths $$$3$$$ and $$$0$$$, $$$2$$$ and $$$2$$$, or $$$1.5$$$ and $$$1.5$$$.The player who is unable to make a chop will be the loser. Assuming that both errorgorn and maomao90 play optimally, who will be the winner?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$)  — the number of logs. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 50$$$)  — the lengths of the logs. Note that there is no bound on the sum of $$$n$$$ over all test cases.

For each test case, print "errorgorn" if errorgorn wins or "maomao90" if maomao90 wins. (Output without quotes).

NoteIn the first test case, errorgorn will be the winner. An optimal move is to chop the log of length $$$4$$$ into $$$2$$$ logs of length $$$2$$$. After this there will only be $$$4$$$ logs of length $$$2$$$ and $$$1$$$ log of length $$$1$$$.After this, the only move any player can do is to chop any log of length $$$2$$$ into $$$2$$$ logs of length $$$1$$$. After $$$4$$$ moves, it will be maomao90's turn and he will not be able to make a move. Therefore errorgorn will be the winner.In the second test case, errorgorn will not be able to make a move on his first turn and will immediately lose, making maomao90 the winner.

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

let rec read_log_lengths = function
    | 0 -> []
    | n -> (read_int ())::(read_log_lengths (n-1))
;;

let rec get_num_moves = function
    | 0 -> 0
    | n ->
        let log_length=read_int () in
        log_length-1 + get_num_moves (n-1)
;;

(* Moves | Length 0 | 1, 1 | 2, 2 | 3, 3 | 4 *)
let calculate_test_case = function
    | num_moves ->
        if (num_moves mod 2 == 0) then "maomao90"
        else "errorgorn"

;;

let rec iterate_through_cases = function
    | 0 -> 0
    | n ->
        let num_logs = read_int () in
        let num_moves = get_num_moves num_logs in
        print_string (calculate_test_case num_moves);
        print_newline ();
        iterate_through_cases (n-1)
;;

let num_cases = read_int () in
iterate_through_cases num_cases;;

let parse len str = let rep = Array.make len (-1) in
  let temp = ref "" in
  let j = ref 0 in
  for i = 0 to String.length str -1 do
    if str.[i] = ' ' then
      (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=""  )
    else
      (temp:= !temp ^ (String.make 1 str.[i]))
  done; rep.(!j) <- (int_of_string !temp) ;rep
;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let len = int_of_string (input_line stdin) in
  let str = (input_line stdin) in
  let tab = parse len str in
  let rep = ref 0 in
  for j = 0 to len -1 do
    rep := !rep + tab.(j) -1
  done;
  if !rep mod 2 = 1 then
    print_endline "errorgorn"
  else
    print_endline "maomao90"
done;;


Once Petya read a problem about a bracket sequence. He gave it much thought but didn't find a solution. Today you will face it.You are given string s. It represents a correct bracket sequence. A correct bracket sequence is the sequence of opening ("(") and closing (")") brackets, such that it is possible to obtain a correct mathematical expression from it, inserting numbers and operators between the brackets. For example, such sequences as "(())()" and "()" are correct bracket sequences and such sequences as ")()" and "(()" are not.In a correct bracket sequence each bracket corresponds to the matching bracket (an opening bracket corresponds to the matching closing bracket and vice versa). For example, in a bracket sequence shown of the figure below, the third bracket corresponds to the matching sixth one and the fifth bracket corresponds to the fourth one.   You are allowed to color some brackets in the bracket sequence so as all three conditions are fulfilled:   Each bracket is either not colored any color, or is colored red, or is colored blue.  For any pair of matching brackets exactly one of them is colored. In other words, for any bracket the following is true: either it or the matching bracket that corresponds to it is colored.  No two neighboring colored brackets have the same color. Find the number of different ways to color the bracket sequence. The ways should meet the above-given conditions. Two ways of coloring are considered different if they differ in the color of at least one bracket. As the result can be quite large, print it modulo 1000000007 (109 + 7).

The first line contains the single string s (2 ≤ |s| ≤ 700) which represents a correct bracket sequence.

Print the only number — the number of ways to color the bracket sequence that meet the above given conditions modulo 1000000007 (109 + 7).

NoteLet's consider the first sample test. The bracket sequence from the sample can be colored, for example, as is shown on two figures below.     The two ways of coloring shown below are incorrect.

(* codeforces 106.  Danny Sleator *)
(* This version is modified because apparently you can't make an
   array that is 5Million long on the codeforces server.  *)
let read_string () = Scanf.bscanf Scanf.Scanning.stdib " %s " (fun x -> x)

let m = 1000000007L
let ( ++ ) a b = Int64.rem (Int64.add a b) m
let ( ** ) a b = Int64.rem (Int64.mul a b) m

let () =
  let s = read_string() in
  let n = String.length s in

  let pair = Array.make n (-1) in  (* if i is a left paren, pair.(i) is its matching right *)

  let rec scan i stack = if i=n then () else
    if s.[i] = '(' then scan (i+1) (i::stack) else (
      pair.(List.hd stack) <- i;
      scan (i+1) (List.tl stack)
    )
  in

  let () = scan 0 [] in

  let table = Array.make_matrix n (n * 3 * 3) None in
  let index j c1 c2 = c2 + 3*(c1 + 3*j) in
  let lookup i j c1 c2 = table.(i).(index j c1 c2) in
  let store i j c1 c2 x = table.(i).(index j c1 c2) <- x in

  let valid_pair c1 c2 = (c1=0 || c2=0) && (c1 <> c2) in
  let vn c1 c2 = c1=0 || c2=0 || c1 <> c2 in  (* valid neighbors *)

  let color_list = [(0,0);(0,1);(0,2);(1,0);(1,1);(1,2);(2,0);(2,1);(2,2)] in

  let rec count i j c1 c2 =  (* i is left, j is right, at the same level, and c1 and c2 are their colors *)
    match lookup i j c1 c2 with Some x -> x | None ->
      let answer =
	if pair.(i) = j then ( (* matching pair *)
	  if not (valid_pair c1 c2) then 0L
	  else if i+1=j then 1L
	  else (
	    List.fold_left
	      (fun ac (d1,d2) ->
		 if (vn c1 d1) && (vn d2 c2) then ac ++ count (i+1) (j-1) d1 d2 else ac
	      ) 0L color_list
	  )
	) else (
	  List.fold_left
	    (fun ac (d1,d2) ->
	       if (valid_pair c1 d1) && (vn d1 d2)
	       then ac ++ (count i pair.(i) c1 d1) ** (count (pair.(i)+1) j d2 c2)
	       else ac
	    ) 0L color_list
	)
      in
	store i j c1 c2 (Some answer);
	answer
  in

  let full_count = List.fold_left (fun ac (d1,d2) -> ac ++ count 0 (n-1) d1 d2) 0L color_list in
    Printf.printf "%s\n" (Int64.to_string full_count)

(* codeforces 106.  Danny Sleator *)
let read_string () = Scanf.bscanf Scanf.Scanning.stdib " %s " (fun x -> x)

let m = 1000000007L
let ( ++ ) a b = Int64.rem (Int64.add a b) m
let ( ** ) a b = Int64.rem (Int64.mul a b) m

let () =
  let s = read_string() in
  let n = String.length s in

  let pair = Array.make n (-1) in  (* if i is a left paren, pair.(i) is its matching right *)

  let rec scan i stack = if i=n then () else
    if s.[i] = '(' then scan (i+1) (i::stack) else (
      pair.(List.hd stack) <- i;
      scan (i+1) (List.tl stack)
    )
  in

  let () = scan 0 [] in

  let table = Array.make (n * n * 3 * 3) None in
  let index i j c1 c2 = c2 + 3*(c1 + 3*(j + n*i)) in
  let lookup i j c1 c2 = table.(index i j c1 c2) in
  let store i j c1 c2 x = table.(index i j c1 c2) <- x in

  let valid_pair c1 c2 = (c1=0 || c2=0) && (c1 <> c2) in
  let vn c1 c2 = c1=0 || c2=0 || c1 <> c2 in  (* valid neighbors *)

  let color_list = [(0,0);(0,1);(0,2);(1,0);(1,1);(1,2);(2,0);(2,1);(2,2)] in

  let rec count i j c1 c2 =  (* i is left, j is right, at the same level, and c1 and c2 are their colors *)
    match lookup i j c1 c2 with Some x -> x | None ->
      let answer =
	if pair.(i) = j then ( (* matching pair *)
	  if not (valid_pair c1 c2) then 0L
	  else if i+1=j then 1L
	  else (
	    List.fold_left
	      (fun ac (d1,d2) ->
		 if (vn c1 d1) && (vn d2 c2) then ac ++ count (i+1) (j-1) d1 d2 else ac
	      ) 0L color_list
	  )
	) else (
	  List.fold_left
	    (fun ac (d1,d2) ->
	       if (valid_pair c1 d1) && (vn d1 d2)
	       then ac ++ (count i pair.(i) c1 d1) ** (count (pair.(i)+1) j d2 c2)
	       else ac
	    ) 0L color_list
	)
      in
	store i j c1 c2 (Some answer);
	answer
  in

  let full_count = List.fold_left (fun ac (d1,d2) -> ac ++ count 0 (n-1) d1 d2) 0L color_list in
    Printf.printf "%s\n" (Int64.to_string full_count)


Alice and Bob play a game. Alice has $$$n$$$ cards, the $$$i$$$-th of them has the integer $$$a_i$$$ written on it. Bob has $$$m$$$ cards, the $$$j$$$-th of them has the integer $$$b_j$$$ written on it.On the first turn of the game, the first player chooses one of his/her cards and puts it on the table (plays it). On the second turn, the second player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the first turn, and plays it. On the third turn, the first player chooses one of his/her cards such that the integer on it is greater than the integer on the card played on the second turn, and plays it, and so on — the players take turns, and each player has to choose one of his/her cards with greater integer than the card played by the other player on the last turn.If some player cannot make a turn, he/she loses.For example, if Alice has $$$4$$$ cards with numbers $$$[10, 5, 3, 8]$$$, and Bob has $$$3$$$ cards with numbers $$$[6, 11, 6]$$$, the game may go as follows:  Alice can choose any of her cards. She chooses the card with integer $$$5$$$ and plays it.  Bob can choose any of his cards with number greater than $$$5$$$. He chooses a card with integer $$$6$$$ and plays it.  Alice can choose any of her cards with number greater than $$$6$$$. She chooses the card with integer $$$10$$$ and plays it.  Bob can choose any of his cards with number greater than $$$10$$$. He chooses a card with integer $$$11$$$ and plays it.  Alice can choose any of her cards with number greater than $$$11$$$, but she has no such cards, so she loses. Both Alice and Bob play optimally (if a player is able to win the game no matter how the other player plays, the former player will definitely win the game).You have to answer two questions:  who wins if Alice is the first player?  who wins if Bob is the first player?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of four lines. The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of cards Alice has. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 50$$$) — the numbers written on the cards that Alice has. The third line contains one integer $$$m$$$ ($$$1 \le m \le 50$$$) — the number of Bob's cards. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le 50$$$) — the numbers on Bob's cards.

For each test case, print two lines. The first line should be Alice if Alice wins when she is the first player; otherwise, the first line should be Bob. The second line should contain the name of the winner if Bob is the first player, in the same format.

NoteLet's consider the first test case of the example.Alice has one card with integer $$$6$$$, Bob has two cards with numbers $$$[6, 8]$$$.If Alice is the first player, she has to play the card with number $$$6$$$. Bob then has to play the card with number $$$8$$$. Alice has no cards left, so she loses.If Bob is the first player, then no matter which of his cards he chooses on the first turn, Alice won't be able to play her card on the second turn, so she will lose.

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

let rec max_int_from_input max = function
    | 0 -> max
    | n ->
        let new_in = read_int () in
        if (max < new_in) then max_int_from_input new_in (n-1)
        else max_int_from_input max (n-1)
;;

let rec run_test_case = function
    | 0 -> 0
    | n ->
        let num_alice = read_int () in
        let max_alice = max_int_from_input 0 num_alice in
        let num_bob = read_int () in
        let max_bob = max_int_from_input 0 num_bob in
        if (max_alice > max_bob) then begin
            print_string "Alice\n";
            print_string "Alice\n";
            run_test_case (n-1)
        end
        else if (max_alice == max_bob) then begin
            print_string "Alice\n";
            print_string "Bob\n";
            run_test_case (n-1)
        end
        else begin
            print_string "Bob\n";
            print_string "Bob\n";
            run_test_case (n-1)
        end
;;

let num_cases = read_int () in
run_test_case num_cases;;

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 maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

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

  let cases = read_int()in
  for case = 1 to cases do
    let n = read_int() in
    let a = Array.init n read_int in
    let m = read_int() in
    let b = Array.init m read_int in
    let maxa = maxf 0 (n-1) (fun i -> a.(i)) in
    let maxb = maxf 0 (m-1) (fun i -> b.(i)) in
    printf "%s\n" (if maxa >= maxb then "Alice" else "Bob");
    printf "%s\n" (if maxb >= maxa then "Bob" else "Alice");
  done


Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.

Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).

NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".

let readString () = Scanf.scanf " %s" (fun s -> s)

let solve s =
  let open Bytes in
  let n = String.length s in
  let i = ref 0 in
  let j = ref (n-1) in
  let o = make n '\x00' in
  let olen = ref 0 in
  let write c = (*Printf.eprintf "%c %d\n" c !olen;*) set o !olen c; incr olen in
  while i <= j do
    (*Printf.eprintf "%d %d\n" !i !j;*)
    if i = j then (write s.[!i]; incr i)
    else if s.[!i] = s.[!j] then (write s.[!i]; incr i; write s.[!j]; decr j)
    else if !i+1 = !j then (write s.[!i]; i := !i+2)
    else if s.[!i] = s.[!j-1] then decr j
    else incr i
  done;
  let olen = !olen in
  let o' = Bytes.make olen '\x00' in
  for i=0 to olen/2-1 do
    let c = get o (2*i) in
    set o' i c;
    set o' (olen-1-i) c
  done;
  if olen mod 2 = 1 then get o (olen-1) |> set o' (olen/2);
  Bytes.to_string o'

let main () =
  let s = readString () in
  Printf.printf "%s\n" (solve s)

let () = main ()


Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point (i + 1, yi + 1). For any even i (2 ≤ i ≤ 2n) the following condition holds: yi - 1 < yi and yi > yi + 1. We shall call a vertex of a polyline with an even x coordinate a mountain peak.   The figure to the left shows the initial picture, the figure to the right shows what the picture looks like after Bolek's actions. The affected peaks are marked red, k = 2.  Bolek fancied a little mischief. He chose exactly k mountain peaks, rubbed out the segments that went through those peaks and increased each peak's height by one (that is, he increased the y coordinate of the corresponding points). Then he painted the missing segments to get a new picture of mountain peaks. Let us denote the points through which the new polyline passes on Bolek's new picture as (1, r1), (2, r2), ..., (2n + 1, r2n + 1).Given Bolek's final picture, restore the initial one.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100). The next line contains 2n + 1 space-separated integers r1, r2, ..., r2n + 1 (0 ≤ ri ≤ 100) — the y coordinates of the polyline vertices on Bolek's picture. It is guaranteed that we can obtain the given picture after performing the described actions on some picture of mountain peaks.

Print 2n + 1 integers y1, y2, ..., y2n + 1 — the y coordinates of the vertices of the polyline on the initial picture. If there are multiple answers, output any one of them.

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let k = ref (Scanf.scanf " %d" (fun x -> x)) in
  let a = Array.create (2*n+1) 0 in
  for i = 0 to 2 * n do
    a.(i) <- Scanf.scanf " %d" (fun x -> x)
  done;
  for i = 0 to n - 1 do
    let j = 2*i+1 in
    if !k > 0 && a.(j) > a.(j-1) + 1 && a.(j) > a.(j+1) + 1 then begin
      k := !k - 1;
      a.(j) <- a.(j) - 1
    end
  done;
  print_string (String.concat " " (List.map string_of_int (Array.to_list a)))
;;

open Scanf;;
open Printf;;

let rec head n ls =
  match (n, ls) with
    (0, _) -> []
  | (n, []) -> failwith ""
  | (n, x::xs) -> x :: (head (n - 1) xs)

let n, k = scanf "%d %d " (fun x y -> x, y);;
let arr = Array.make (2 * n + 1) 0;;

for i = 0 to 2 * n do
  arr.(i) <- (scanf "%d " (fun x -> x))
done;;

let main () =
  let rec loop i res =
    if i >= 2 * n then res
    else if arr.(i - 1) + 1 < arr.(i) && arr.(i) > arr.(i + 1) + 1 then
      loop (i + 2) (i :: res)
    else loop (i + 2) res in
  let res = head k (loop 1 []) in
  List.iter (fun i -> arr.(i) <- (arr.(i) - 1)) res;;

main ();;

for i = 0 to 2 * n do
  printf "%d " arr.(i)
done;;
printf "\n"

open Scanf;;
open Printf;;

let rec head n ls =
  match (n, ls) with
    (0, _) -> []
  | (n, []) -> failwith ""
  | (n, x::xs) -> x :: (head (n - 1) xs)

let n, k = scanf "%d %d " (fun x y -> x, y);;
let arr = Array.make (2 * n + 1) 0;;

for i = 0 to 2 * n do
  arr.(i) <- (scanf "%d " (fun x -> x))
done;;

let main () =
  let rec loop i res =
    if i >= 2 * n then res
    else if arr.(i - 1) + 1 < arr.(i) && arr.(i) > arr.(i - 1) + 1 then
      loop (i + 2) (i :: res)
    else loop (i + 2) res in
  let res = head k (loop 1 []) in
  List.iter (fun i -> arr.(i) <- (arr.(i) - 1)) res;;

main ();;

for i = 0 to 2 * n do
  printf "%d " arr.(i)
done;;
printf "\n"


God's Blessing on This PermutationForces!A Random PebbleYou are given a permutation $$$p_1,p_2,\ldots,p_n$$$ of length $$$n$$$ and a positive integer $$$k \le n$$$. In one operation you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i < j \le n$$$) and swap $$$p_i$$$ with $$$p_j$$$.Find the minimum number of operations needed to make the sum $$$p_1 + p_2 + \ldots + p_k$$$ as small as possible.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ integers $$$p_1,p_2,\ldots,p_n$$$ ($$$1 \le p_i \le n$$$). It is guaranteed that the given numbers form a permutation of length $$$n$$$.

For each test case print one integer — the minimum number of operations needed to make the sum $$$p_1 + p_2 + \ldots + p_k$$$ as small as possible.

NoteIn the first test case, the value of $$$p_1 + p_2 + \ldots + p_k$$$ is initially equal to $$$2$$$, but the smallest possible value is $$$1$$$. You can achieve it by swapping $$$p_1$$$ with $$$p_3$$$, resulting in the permutation $$$[1, 3, 2]$$$.In the second test case, the sum is already as small as possible, so the answer is $$$0$$$.

module A = Array
module L = List
module I = Int64

let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())

let () =
  let t = read_int () in

  for _ = 1 to t do
    let n = read_int () in
    let k = read_int () in
    let a = read_array read_int n in
    let ans = ref 0 in
    for i = 0 to k - 1 do
      if (a.(i) > k) then ans := !ans + 1;
    done;
    pf "%d\n" !ans;
  done

let get_num () =
  let rec f acc =
    try
      let c = input_byte stdin in
      if int_of_char '0' <= c && c <= int_of_char '9' then
        f ((acc * 10) + c - int_of_char '0')
      else if acc > 0 then Some acc
      else None
    with End_of_file -> if acc > 0 then Some acc else None
  in
  f 0

let solve_case () =
  match (get_num (), get_num ()) with
  | Some n, Some k ->
      let rec f i ans =
        let i = i + 1 in
        if i > n then print_int ans
        else
          match get_num () with
          | Some p ->
              let ans = if i <= k && p > k then ans + 1 else ans in
              f i ans
          | _ -> exit 1
      in
      f 0 0
  | _ -> ()

let () =
  match get_num () with
  | Some t ->
      let rec f i =
        if i = 0 then ()
        else
          let () = solve_case () in
          let () = print_newline () in
          f (i - 1)
      in
      f t
  | _ -> exit 1


Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that:           0        0 1 0      0 1 2 1 0    0 1 2 3 2 1 0  0 1 2 3 4 3 2 1 00 1 2 3 4 5 4 3 2 1 0  0 1 2 3 4 3 2 1 0    0 1 2 3 2 1 0      0 1 2 1 0        0 1 0          0Your task is to determine the way the handkerchief will look like by the given n.

The first line contains the single integer n (2 ≤ n ≤ 9).

Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.

let n = read_int();;

for i = n downto 0 do
	for t = 1 to i do print_string "  " done;
	for t = i to n do print_int (t-i); if i <> t || i <> n then print_char ' ' done;
	for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
	print_string "\n";
done;;

for i = 1 to n do
        for t = 1 to i do print_string "  " done;
        for t = i to n do print_int (t-i); if i <> t || i <> n then print_char ' ' done;
        for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
        print_string "\n";
done;;

let n = read_int();;

for i = n downto 0 do
	for t = 1 to i do print_string "  " done;
	for t = i to n do print_int (t-i); if i <> t then print_char ' ' done;
	for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
	print_string "\n";
done;;

for i = 1 to n do
        for t = 1 to i do print_string "  " done;
        for t = i to n do print_int (t-i); if i <> t then print_char ' ' done;
        for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
        print_string "\n";
done;;

let n = read_int();;

for i = n downto 0 do
	for t = 1 to i do print_string "  " done;
	for t = i to n do print_int (t-i); if t = i then print_char ' ' done;
	for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
	print_string "\n";
done;;

for i = 1 to n do
        for t = 1 to i do print_string "  " done;
        for t = i to n do print_int (t-i); if t = i then print_char ' ' done;
        for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
        print_string "\n";
done;;

let n = read_int();;

for i = n downto 0 do
	for t = 1 to i do print_string "  " done;
	for t = i to n do print_int (t-i); print_char ' ' done;
	for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
	print_string "\n";
done;;

for i = 1 to n do
        for t = 1 to i do print_string "  " done;
        for t = i to n do print_int (t-i); print_char ' ' done;
        for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
        print_string "\n";
done;;

let n = read_int();;

for i = n downto 0 do
	for t = 1 to i do print_string "  " done;
	for t = i to n do print_int (t-i); print_char ' ' done;
	for t = n to n*2-i-1 do print_int (n*2-i-1-t); print_char ' ' done;
	print_string "\n";
done;;

for i = 1 to n do
        for t = 1 to i do print_string "  " done;
        for t = i to n do print_int (t-i); print_char ' ' done;
        for t = n to n*2-i-1 do print_int (n*2-i-1-t); print_char ' ' done;
        print_string "\n";
done;;

let n = read_int();;

for i = n downto 0 do
	for t = 1 to i do print_string "  " done;
	for t = i to n do print_int (t-i); print_char ' ' done;
	for t = n to n*2-i-1 do print_int (n*2-i-1-t); if n*2-i-1-t <> 0 then print_char ' ' done;
	print_string "\n";
done;;

for i = 1 to n do
        for t = 1 to i do print_string "  " done;
        for t = i to n do print_int (t-i); print_char ' ' done;
        for t = n to n*2-i-1 do print_int (n*2-i-1-t); print_char ' ' done;
        print_string "\n";
done;;


You're given an integer $$$n$$$. For every integer $$$i$$$ from $$$2$$$ to $$$n$$$, assign a positive integer $$$a_i$$$ such that the following conditions hold:  For any pair of integers $$$(i,j)$$$, if $$$i$$$ and $$$j$$$ are coprime, $$$a_i \neq a_j$$$.  The maximal value of all $$$a_i$$$ should be minimized (that is, as small as possible). A pair of integers is called coprime if their greatest common divisor is $$$1$$$.

The only line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$).

Print $$$n-1$$$ integers, $$$a_2$$$, $$$a_3$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq n$$$).  If there are multiple solutions, print any of them.

NoteIn the first example, notice that $$$3$$$ and $$$4$$$ are coprime, so $$$a_3 \neq a_4$$$. Also, notice that $$$a=[1,2,3]$$$ satisfies the first condition, but it's not a correct answer because its maximal value is $$$3$$$.

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a = Array.make (n + 1) 0 in
  let x = ref 1 in
  for i = 2 to n do
    let idx = ref i in
    let p = ref false in
    while (!idx <= n) do
      if a.(!idx) = 0 then begin
        a.(!idx) <- !x;
        p := true;
      end;
      idx := !idx + i;
    done;
    if !p then incr x;
  done;
  for i = 2 to n do
    Printf.printf "%d " a.(i)
  done
;;


The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank.One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible.Vasya has just reached a new rank of a, but he dreams of holding the rank of b. Find for how many more years Vasya should serve in the army until he can finally realize his dream.

The first input line contains an integer n (2 ≤ n ≤ 100). The second line contains n - 1 integers di (1 ≤ di ≤ 100). The third input line contains two integers a and b (1 ≤ a < b ≤ n). The numbers on the lines are space-separated.

Print the single number which is the number of years that Vasya needs to rise from rank a to rank b.

(* Codeforces 248C Football Robot Electronic *)

open Big_int;;
open List;;

(* 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 rec readlist n acc = match n with
	| 0 -> List.rev acc
	| _ -> readlist (n -1) (gr() :: acc);;

let rec sumab a b l =
	if a>1 then (sumab (a-1) (b-1) (List.tl l))
	else if b>1 then ((List.hd l) + (sumab 0 (b-1) (List.tl l)))
	else 0;;

let debug = false;;

let main () =
	let n = gr() in
	let d = readlist (n-1) [] in
	let a = gr() in
	let b = gr() in
	let sab = sumab a b d in
	begin
		(* printlisti d;                   *)
		(* print_string "\n now result\n"; *)
	  print_int sab
	end;;

main();;

open Scanf;;

let n = Scanf.bscanf Scanf.Scanning.stdin "%d " (fun x -> x);;
let aa = Array.make (n-1) 0;;

for i = 0 to n - 2 do
  let x = Scanf.bscanf Scanf.Scanning.stdin "%d " (fun y->y) in
  aa.(i) <- x
done
;;

let (a,b) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " (fun x y->(x,y) );;
if b <= a then
  begin
    print_int 0; print_endline "";
    end
else
  let rslt=ref 0 in
  let () =
    for j = (a-1) to (b-2) do
      rslt := !rslt + aa.(j)
    done in print_int !rslt; print_endline ""
;;


Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into two pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece, and each piece contains positive integer amount of squares. Would you help Bob solve this problem?

The first input line contains integer n (1 ≤ n ≤ 105) — amount of squares in the stripe. The second line contains n space-separated numbers — they are the numbers written in the squares of the stripe. These numbers are integer and do not exceed 10000 in absolute value.

Output the amount of ways to cut the stripe into two non-empty pieces so that the sum of numbers from one piece is equal to the sum of numbers from the other piece. Don't forget that it's allowed to cut the stripe along the squares' borders only.

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

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let s = Array.fold_left (+) 0 a in
  let rec go c x i =
    if i >= n-1 then
      c
    else
      let x' = x+a.(i) in
      go (c + (if x'*2 == s then 1 else 0)) x' (i+1)
  in
  go 0 0 0 |> Printf.printf "%d\n"


Vika has an infinite sheet of squared paper. Initially all squares are white. She introduced a two-dimensional coordinate system on this sheet and drew n black horizontal and vertical segments parallel to the coordinate axes. All segments have width equal to 1 square, that means every segment occupy some set of neighbouring squares situated in one row or one column.Your task is to calculate the number of painted cells. If a cell was painted more than once, it should be calculated exactly once.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of segments drawn by Vika. Each of the next n lines contains four integers x1, y1, x2 and y2 ( - 109 ≤ x1, y1, x2, y2 ≤ 109) — the coordinates of the endpoints of the segments drawn by Vika. It is guaranteed that all the segments are parallel to coordinate axes. Segments may touch, overlap and even completely coincide.

Print the number of cells painted by Vika. If a cell was painted more than once, it should be calculated exactly once in the answer.

NoteIn the first sample Vika will paint squares (0, 1), (1, 1), (2, 1), (1, 2), (1, 3), (1, 4), (0, 3) and (2, 3).

open Printf
open Scanf

(* A segment tree that maintains a set of variables a0, a1, ... a(n-1),
   allowing you to assign to a variable, and also allowing you to sum
   a range of the variables ai+a(i+1)+...+aj.
*)

let parent v = v/2
let lc v = 2*v
let rc v = 2*v+1

let superceil n =
  let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in
  1 + (loop (n-1) 0)

let make_segtree n =
  let nn = superceil n in
  let a = Array.make (2*nn) 0 in
  (nn,a)

let assign (nn,a) v x =
  (* do a(v) <- x *)
  let x = x - a.(nn+v) in
  let rec loop j = if j > 0 then (
    a.(j) <- a.(j) + x;
    loop (parent j)
  ) in
  loop (nn+v)

let sum (nn,a) i j =
  let rec f v l r ql qr =
    let m = (l+r)/2 in
    if l=ql && r=qr then a.(v) else
      let t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0 in
      let t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0 in
      t1 + t2
  in
  f 1 0 (nn-1) i j

(*---------------------end segment tree----------------------*)

let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let long x = Int64.of_int x

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_four () = bscanf Scanning.stdib " %d %d %d %d " (fun a b c d -> (a,b,c,d))

let () =
  let n = read_int() in
  let r = Array.init n (fun i -> read_four()) in

  let rec classify vert horiz i = if i=n then (vert,horiz) else
      let (x1,y1,x2,y2) = r.(i) in
      let (x1,x2) = (min x1 x2, max x1 x2) in
      let (y1,y2) = (min y1 y2, max y1 y2) in
      r.(i) <- (x1,x2,y1,y2);

      if x1 < x2 then classify vert ((y1,x1,x2)::horiz) (i+1)
      else classify ((x1,y1,y2)::vert) horiz (i+1)
  in

  let (vert,horiz) = classify [] [] 0 in

  let clean_up rect =
    let h = Hashtbl.create 100 in

    let add_to_h (y,x1,x2) =
      let c = try Hashtbl.find h y with Not_found -> [] in
      Hashtbl.replace h y ((x1,x2)::c)
    in
    List.iter add_to_h rect;

    let fix_bucket li =
      let li = List.sort compare li in
      let rec loop (cx1,cx2) li ac =
	match li with
	  | [] -> (cx1,cx2)::ac
	  | (x1,x2)::tail ->
	    if x1 > cx2+1 then loop (x1,x2) tail ((cx1,cx2)::ac)
	    else loop (cx1,max x2 cx2) tail ac
      in
      List.rev (loop (List.hd li) (List.tl li) [])
    in

    Hashtbl.fold (fun y li ac -> (y,(fix_bucket li))::ac) h []
      (* [(y1,[(x1,x2);(x3,x4)...]); (y2,[...]);...] *)
  in

  let vert = clean_up vert in
  let horiz = clean_up horiz in

  let compy = Hashtbl.create 100 in  (* compress y table *)

  List.iter (fun (y,_) -> Hashtbl.replace compy y 0) horiz;

  List.iter (fun (_, li) ->
    List.iter (fun (y1,y2) ->
      Hashtbl.replace compy y1 0;
      Hashtbl.replace compy y2 0;
    ) li
  ) vert;

  let ys = Hashtbl.fold (fun y _ ac -> y::ac) compy [] in
  let ys = List.sort compare ys in
  List.iteri (fun i y -> Hashtbl.replace compy y i) ys;
  (* now Hashtbl.find compy y  returns the mapped value of y *)
  let map y = Hashtbl.find compy y in
  let ny = Hashtbl.length compy in  (* mapped ys are 0....ny-1 *)

  (* In the sweep-line algorithm there are three types of events
      (1) a horizontal segment enters
      (2) a vertical segment is processed
      (3) a horizontal segment leaves
     For each x coordinate we do the events in the this order.
  *)

  (* an event is (x, 1/2/3, (y1,y2)), where only y1 is used in cases
     (1) and (3)
  *)

  let rec build_horiz horiz ac =
    match horiz with
      | [] -> ac
      | (y, li)::tail ->
	let y = map y in
	let ac = List.fold_left (
	  fun ac (x1,x2) -> (x1,1,(y,0))::((x2,3,(y,0))::ac)
	) ac li in
	build_horiz tail ac
  in

  let rec build_vert vert ac =
    match vert with
      | [] -> ac
      | (x, li)::tail ->
	let ac = List.fold_left (
	  fun ac (y1,y2) -> (x,2,(map y1, map y2))::ac
	) ac li in
	build_vert tail ac
  in

  let event_list = build_vert vert (build_horiz horiz []) in
  let event_list = List.sort compare event_list in

  let st = make_segtree ny in

  let overlap =
    List.fold_left (fun ac (_,t,(y1,y2)) ->
      match t with
	| 1 -> assign st y1 1; ac
	| 2 -> ac ++ long (sum st y1 y2)
	| 3 -> assign st y1 0; ac
	| _ -> failwith "bad t"
      ) 0L event_list
  in

  let total_length lili =
    List.fold_left (fun ac (_,li) ->
      List.fold_left (fun ac (x1,x2) -> ac ++ (long x2) -- (long x1) ++ 1L
      ) ac li
    ) 0L lili
  in

  let answer = (total_length horiz) ++ (total_length vert) -- overlap in

  printf "%Ld\n" answer

open Printf
open Scanf

(* A segment tree that maintains a set of variables a0, a1, ... a(n-1),
   allowing you to assign to a variable, and also allowing you to sum
   a range of the variables ai+a(i+1)+...+aj.
*)

let parent v = v/2
let lc v = 2*v
let rc v = 2*v+1

let superceil n =
  let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in
  1 + (loop (n-1) 0)

let make_segtree n =
  let nn = superceil n in
  let a = Array.make (2*nn) 0 in
  (nn,a)

let assign (nn,a) v x =
  (* do a(v) <- x *)
  let x = x - a.(nn+v) in
  let rec loop j = if j > 0 then (
    a.(j) <- a.(j) + x;
    loop (parent j)
  ) in
  loop (nn+v)

let sum (nn,a) i j =
  let rec f v l r ql qr =
    let m = (l+r)/2 in
    if l=ql && r=qr then a.(v) else
      let t1 = if ql<=m then f (lc v) l m ql (min m qr) else 0 in
      let t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else 0 in
      t1 + t2
  in
  f 1 0 (nn-1) i j

(*---------------------end segment tree----------------------*)

let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let long x = Int64.of_int x

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_four () = bscanf Scanning.stdib " %d %d %d %d " (fun a b c d -> (a,b,c,d))

let () =
  let n = read_int() in
  let r = Array.init n (fun i -> read_four()) in

  let rec classify vert horiz i = if i=n then (vert,horiz) else
      let (x1,y1,x2,y2) = r.(i) in
      let (x1,x2) = (min x1 x2, max x1 x2) in
      let (y1,y2) = (min y1 y2, max y1 y2) in
      r.(i) <- (x1,x2,y1,y2);

      if x1 < x2 then classify vert ((y1,x1,x2)::horiz) (i+1)
      else classify ((x1,y1,y2)::vert) horiz (i+1)
  in

  let (vert,horiz) = classify [] [] 0 in

  let clean_up rect =
    let h = Hashtbl.create 100 in

    let add_to_h (y,x1,x2) =
      let c = try Hashtbl.find h y with Not_found -> [] in
      Hashtbl.replace h y ((x1,x2)::c)
    in
    List.iter add_to_h rect;

    let fix_bucket li =
      let li = List.sort compare li in
      let rec loop (cx1,cx2) li ac =
	match li with
	  | [] -> (cx1,cx2)::ac
	  | (x1,x2)::tail ->
	    if x1 > cx2+1 then loop (x1,x2) tail ((cx1,cx2)::ac)
	    else loop (cx1,x2) tail ac
      in
      List.rev (loop (List.hd li) (List.tl li) [])
    in

    Hashtbl.fold (fun y li ac -> (y,(fix_bucket li))::ac) h []
      (* [(y1,[(x1,x2);(x3,x4)...]); (y2,[...]);...] *)
  in

  let vert = clean_up vert in
  let horiz = clean_up horiz in

  let compy = Hashtbl.create 100 in  (* compress y table *)

  List.iter (fun (y,_) -> Hashtbl.replace compy y 0) horiz;

  List.iter (fun (_, li) ->
    List.iter (fun (y1,y2) ->
      Hashtbl.replace compy y1 0;
      Hashtbl.replace compy y2 0;
    ) li
  ) vert;

  let ys = Hashtbl.fold (fun y _ ac -> y::ac) compy [] in
  let ys = List.sort compare ys in
  List.iteri (fun i y -> Hashtbl.replace compy y i) ys;
  (* now Hashtbl.find compy y  returns the mapped value of y *)
  let map y = Hashtbl.find compy y in
  let ny = Hashtbl.length compy in  (* mapped ys are 0....ny-1 *)

  (* In the sweep-line algorithm there are three types of events
      (1) a horizontal segment enters
      (2) a vertical segment is processed
      (3) a horizontal segment leaves
     For each x coordinate we do the events in the this order.
  *)

  (* an event is (x, 1/2/3, (y1,y2)), where only y1 is used in cases
     (1) and (3)
  *)

  let rec build_horiz horiz ac =
    match horiz with
      | [] -> ac
      | (y, li)::tail ->
	let y = map y in
	let ac = List.fold_left (
	  fun ac (x1,x2) -> (x1,1,(y,0))::((x2,3,(y,0))::ac)
	) ac li in
	build_horiz tail ac
  in

  let rec build_vert vert ac =
    match vert with
      | [] -> ac
      | (x, li)::tail ->
	let ac = List.fold_left (
	  fun ac (y1,y2) -> (x,2,(map y1,map y2))::ac
	) ac li in
	build_vert tail ac
  in

  let event_list = build_vert vert (build_horiz horiz []) in
  let event_list = List.sort compare event_list in

  let st = make_segtree ny in

  let overlap =
    List.fold_left (fun ac (_,t,(y1,y2)) ->
      match t with
	| 1 -> assign st y1 1; ac
	| 2 -> ac ++ long (sum st y1 y2)
	| 3 -> assign st y1 0; ac
	| _ -> failwith "bad t"
      ) 0L event_list
  in

  let total_length lili =
    List.fold_left (fun ac (y,li) ->
      List.fold_left (fun ac (x1,x2) -> ac ++ (long x2) -- (long x1) ++ 1L
      ) ac li
    ) 0L lili
  in

  let answer = (total_length horiz) ++ (total_length vert) -- overlap in

  printf "%Ld\n" answer


There are n problems prepared for the next Codeforces round. They are arranged in ascending order by their difficulty, and no two problems have the same difficulty. Moreover, there are m pairs of similar problems. Authors want to split problems between two division according to the following rules:   Problemset of each division should be non-empty.  Each problem should be used in exactly one division (yes, it is unusual requirement).  Each problem used in division 1 should be harder than any problem used in division 2.  If two problems are similar, they should be used in different divisions. Your goal is count the number of ways to split problem between two divisions and satisfy all the rules. Two ways to split problems are considered to be different if there is at least one problem that belongs to division 1 in one of them and to division 2 in the other.Note, that the relation of similarity is not transitive. That is, if problem i is similar to problem j and problem j is similar to problem k, it doesn't follow that i is similar to k.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000) — the number of problems prepared for the round and the number of pairs of similar problems, respectively. Each of the following m lines contains a pair of similar problems ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi). It's guaranteed, that no pair of problems meets twice in the input.

Print one integer — the number of ways to split problems in two divisions.

NoteIn the first sample, problems 1 and 2 should be used in division 2, while problems 4 and 5 in division 1. Problem 3 may be used either in division 1 or in division 2.In the second sample, all pairs of problems are similar and there is no way to split problem between two divisions without breaking any rules.Third sample reminds you that the similarity relation is not transitive. Problem 3 is similar to both 1 and 2, but 1 is not similar to 2, so they may be used together.

open Printf
open Scanf

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

  let maxleft = ref 0 in
  let minright = ref (n+1) in

  for i=0 to m-1 do
    let u = read_int () in
    let v = read_int () in
    let (u,v) = (min u v, max u v) in
    maxleft := max !maxleft u;
    minright := min !minright v
  done;

  let answer = max (!minright - !maxleft) 0 in
  let answer = if m=0 then (n-1) else answer in

  printf "%d\n" answer


We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $$$s$$$ can transform to another superhero with name $$$t$$$ if $$$s$$$ can be made equal to $$$t$$$ by changing any vowel in $$$s$$$ to any other vowel and any consonant in $$$s$$$ to any other consonant. Multiple changes can be made.In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.Given the names of two superheroes, determine if the superhero with name $$$s$$$ can be transformed to the Superhero with name $$$t$$$.

The first line contains the string $$$s$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. The second line contains the string $$$t$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. Both strings $$$s$$$ and $$$t$$$ are guaranteed to be different and consist of lowercase English letters only.

Output "Yes" (without quotes) if the superhero with name $$$s$$$ can be transformed to the superhero with name $$$t$$$ and "No" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first sample, since both 'a' and 'u' are vowels, it is possible to convert string $$$s$$$ to $$$t$$$.In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string $$$s$$$ to $$$t$$$.

Array.(Scanf.scanf " %s %s" @@ fun s t ->
  let f s =
    init (String.length s) (fun i -> s.[i])
    |> map (function
    | 'a' | 'i' | 'u' | 'e' | 'o' -> 1
    | _ -> 0) in
  print_endline @@ if f s = f t then "Yes" else "No")

let is_vowel c = c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';;

let rec is_transformable a b i j na nb = na == nb && (if i < na && j < nb then (is_vowel (String.get a i)) == (is_vowel (String.get b j)) && (is_transformable a b (i + 1) (j + 1) na nb) else true);;

let a = read_line() in
let b = read_line() in
print_string (if is_transformable a b 0 0 (String.length a) (String.length b) then "Yes" else "No");;

open Printf
open Scanf

let read_str _ = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let s = read_str() in
  let t = read_str() in

  let isvowel c =
    c='a' || c='e' || c='i' || c='o' || c='u'
  in

  let f s =
    let n = String.length s in
    Array.init n (fun i -> isvowel s.[i])
  in

  if (f s) = (f t) then printf "Yes\n" else printf "No\n"

let is_vowel c = c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';;

let is_transformable a b i j na nb = na == nb && i < na && j < nb && (is_vowel (String.get a i)) == (is_vowel (String.get b j));;

let a = read_line() in
let b = read_line() in
print_string (if is_transformable a b 0 0 (String.length a) (String.length b) then "Yes" else "No");;

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let read_str _ = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let s = read_str() in
  let t = read_str() in

  let isvowel c =
    c='a' || c='e' || c='i' || c='o' || c='u'
  in

  let f s =
    let n = String.length s in
    Array.init n (fun i -> isvowel s.[i])
  in

  let alldiff s t =
    let n = String.length s in
    let m = String.length t in
    m = n && (forall 0 (n-1) (fun i -> s.[i] <> t.[i]))
  in

  if (f s) = (f t) && (alldiff s t) then printf "Yes\n" else printf "No\n"


This is an interactive problem. Refer to the Interaction section below for better understanding.Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game.Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.

The first line contains 3 integers n, m and c (,  means  rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process.

NoteIn the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round.The input format for hacking:   The first line contains 3 integers n, m and c;  The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.

open Printf
open String

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

let split_string s =
  let s = trim s in

  let n = String.length s in
  let li = fold 0 (n-1)
    (fun i ac -> if s.[i] = ' ' then i::ac else ac) []
  in

  let rec chop prev li ac =
    match li with [] -> List.rev ac
      | i::tail ->
	chop i tail ((sub s (prev+1) (i-prev-1))::ac)
  in

  chop (-1) (List.rev (n::li)) []

let () =
  let line1 = split_string (read_line()) in
  let n = int_of_string(List.nth line1 0) in
  let m = int_of_string(List.nth line1 1) in
  let c = int_of_string(List.nth line1 2) in
  let c = ((c+1)/2) * 2 in  (* next even number up *)

  let a = Array.make n 0 in

  let left_place p =
    let get i = if a.(i) = 0 then c+1 else a.(i) in
    let rec find i = if get i > p then i else find (i+1) in
    find 0
  in

  let right_place p =
    let rec find i = if a.(i) < p then i else find (i-1) in
    find (n-1)
  in

  let rec loop nblanks = if nblanks = 0 then () else (
    let p = int_of_string (read_line()) in
    let place = if p <= c/2 then left_place p else right_place p in
    Printf.printf "%d\n%!" (place+1);
    let nblanks = nblanks - if a.(place) = 0 then 1 else 0 in
    a.(place) <- p;
    loop nblanks
  ) in

  loop n