Fibonacci numbers are the sequence of integers: f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ..., fn = fn - 2 + fn - 1. So every next number is the sum of the previous two.Bajtek has developed a nice way to compute Fibonacci numbers on a blackboard. First, he writes a 0. Then, below it, he writes a 1. Then he performs the following two operations:  operation "T": replace the top number with the sum of both numbers;  operation "B": replace the bottom number with the sum of both numbers. If he performs n operations, starting with "T" and then choosing operations alternately (so that the sequence of operations looks like "TBTBTBTB..."), the last number written will be equal to fn + 1.Unfortunately, Bajtek sometimes makes mistakes and repeats an operation two or more times in a row. For example, if Bajtek wanted to compute f7, then he would want to do n = 6 operations: "TBTBTB". If he instead performs the sequence of operations "TTTBBT", then he will have made 3 mistakes, and he will incorrectly compute that the seventh Fibonacci number is 10. The number of mistakes in the sequence of operations is the number of neighbouring equal operations («TT» or «BB»).You are given the number n of operations that Bajtek has made in an attempt to compute fn + 1 and the number r that is the result of his computations (that is last written number). Find the minimum possible number of mistakes that Bajtek must have made and any possible sequence of n operations resulting in r with that number of mistakes.Assume that Bajtek always correctly starts with operation "T".

The first line contains the integers n and r (1 ≤ n, r ≤ 106).

The first line of the output should contain one number — the minimum possible number of mistakes made by Bajtek. The second line should contain n characters, starting with "T", describing one possible sequence of operations with that number of mistakes. Each character must be either "T" or "B". If the required sequence doesn't exist, output "IMPOSSIBLE" (without quotes).

open Printf;;
open Scanf;;

let input () = scanf "%d %d " (fun x y -> x, y)

type op = T | B

let rec add n op xs =
  match n with
    0 -> xs
  | n -> add (n - 1) op (op :: xs)

let rec gcd n m =
  let n, m = if n < m then m, n else n, m in
  if m = 0 then n
  else gcd m (n mod m)

let mistake ls =
  let rec iter prev_t acc = function
      [] -> acc
    | T :: ls ->
        if prev_t then iter true (acc + 1) ls else iter true acc ls
    | B :: ls ->
        if prev_t then iter false acc ls else iter false (acc + 1) ls in
  let x :: ls = ls in
  match x with
    T -> iter true 0 ls
  | B -> iter false 0 ls

let rec print_list a b =
  match a with
    [] -> ()
  | T :: ls ->
      if b then printf "T" else printf "B";
      print_list ls b
  | B :: ls ->
      if b then printf "B" else printf "T";
      print_list ls b

let print_res r a b =
  printf "%d\n" r;
  print_list a b

let solve (n, r) =
  let rec like_gcd a b res acc =
    if (res = 0) then
      if (a = 0 && b = 1) || (a = 1 && b = 0) then
        begin(*
          List.iter
            (function T -> printf "T;" | B -> printf "B;") acc;
          printf "\n";*)
          let _::ls = acc in
          let mis = mistake (T::ls) and
              mis' = mistake (B::ls) in
(*          printf "%d %d\n" mis mis';*)
          if mis < mis' then
            Some ((mis, T::ls, true))
          else
            Some ((mis', B::ls, false))
        end
      else
        None
    else if res < 0 || b = 0 || a = 0 then None
    else if a > b then
      let r = a mod b and
          q = a / b in
      let acc = add q T acc in
      like_gcd r b (res - q) acc
    else
      let r = b mod a and
          q = b / a in
      let acc = add q B acc in
      like_gcd a r (res - q) acc in
  let mn = ref (r + 1) and
      a = ref [] and
      bmn = ref false in
  for i = 1 to r do
    match like_gcd r i n [] with
      None -> ()
    | Some (res, acc, b) ->
(*        printf "%d=%d\n" i res;        *)
        if !mn > res then begin
          mn := res;
          a := acc;
          bmn := b
        end
  done;
  if !mn > r then
    printf "IMPOSSIBLE\n"
  else
    (print_res !mn !a !bmn;
     printf "\n";)

let () =
  let inp = input () in
  solve inp

open Printf;;
open Scanf;;

let input () = scanf "%d %d " (fun x y -> x, y)

type op = T | B

let rec add n op xs =
  match n with
    0 -> xs
  | n -> add (n - 1) op (op :: xs)

let rec gcd n m =
  let n, m = if n < m then m, n else n, m in
  if m = 0 then n
  else gcd m (n mod m)

let mistake ls =
  let rec iter i acc = function
      [] -> acc
    | T :: ls ->
        if (i mod 2) == 0 then iter (i + 1) acc ls else iter (i + 1) (acc + 1) ls
    | B :: ls ->
        if (i mod 2) == 1 then iter (i + 1) acc ls else iter (i + 1) (acc + 1) ls in
  iter 0 0 ls

let rec print_list a b =
  match a with
    [] -> ()
  | T :: ls ->
      if b then printf "T" else printf "B";
      print_list ls b
  | B :: ls ->
      if b then printf "B" else printf "T";
      print_list ls b

let print_res r a b =
  printf "%d\n" r;
  print_list a b

let solve (n, r) =
  let rec like_gcd a b res acc =
    if (res = 0) then
      if (a = 0 && b = 1) || (a = 1 && b = 0) then
        begin
(*
          List.iter
            (function T -> printf "T;" | B -> printf "B;") acc;
          printf "\n";*)
          let _::ls = acc in
          let mis = mistake (T::ls) and
              mis' = mistake (B::ls) in
(*          printf "%d %d\n" mis mis';*)
          if mis < n - mis' then
            Some ((mis, T::ls, true))
          else
            Some ((n - mis', B::ls, false))
        end
      else
        None
    else if res < 0 || b = 0 || a = 0 then None
    else if a > b then
      let r = a mod b and
          q = a / b in
      let acc = add q T acc in
      like_gcd r b (res - q) acc
    else
      let r = b mod a and
          q = b / a in
      let acc = add q B acc in
      like_gcd a r (res - q) acc in
  let mn = ref (r + 1) and
      a = ref [] and
      bmn = ref false in
  for i = 1 to r do
    match like_gcd r i n [] with
      None -> ()
    | Some (res, acc, b) ->
(*        printf "%d=%d\n" i res;        *)
        if !mn > res then begin
          mn := res;
          a := acc;
          bmn := b
        end
  done;
  if !mn > r then
    printf "IMPOSSIBLE\n"
  else
    (print_res !mn !a !bmn;
     printf "\n";)

let () =
  let inp = input () in
  solve inp


Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.Polycarp decided to store the hash of the password, generated by the following algorithm:  take the password $$$p$$$, consisting of lowercase Latin letters, and shuffle the letters randomly in it to obtain $$$p'$$$ ($$$p'$$$ can still be equal to $$$p$$$);  generate two random strings, consisting of lowercase Latin letters, $$$s_1$$$ and $$$s_2$$$ (any of these strings can be empty);  the resulting hash $$$h = s_1 + p' + s_2$$$, where addition is string concatenation. For example, let the password $$$p =$$$ "abacaba". Then $$$p'$$$ can be equal to "aabcaab". Random strings $$$s1 =$$$ "zyx" and $$$s2 =$$$ "kjh". Then $$$h =$$$ "zyxaabcaabkjh".Note that no letters could be deleted or added to $$$p$$$ to obtain $$$p'$$$, only the order could be changed.Now Polycarp asks you to help him to implement the password check module. Given the password $$$p$$$ and the hash $$$h$$$, check that $$$h$$$ can be the hash for the password $$$p$$$.Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a non-empty string $$$p$$$, consisting of lowercase Latin letters. The length of $$$p$$$ does not exceed $$$100$$$. The second line of each test case contains a non-empty string $$$h$$$, consisting of lowercase Latin letters. The length of $$$h$$$ does not exceed $$$100$$$.

For each test case print the answer to it — "YES" if the given hash $$$h$$$ could be obtained from the given password $$$p$$$ or "NO" otherwise.

5
abacaba
zyxaabcaabkjh
onetwothree
threetwoone
one
zzonneyy
one
none
twenty
ten

NoteThe first test case is explained in the statement.In the second test case both $$$s_1$$$ and $$$s_2$$$ are empty and $$$p'=$$$ "threetwoone" is $$$p$$$ shuffled.In the third test case the hash could not be obtained from the password.In the fourth test case $$$s_1=$$$ "n", $$$s_2$$$ is empty and $$$p'=$$$ "one" is $$$p$$$ shuffled (even thought it stayed the same). In the fifth test case the hash could not be obtained from the password.

let n = read_int();;
let a = Array.make n ("","");;

for i = 0 to (n-1) do
	let s1 = read_line() in
	let s2 = read_line() in
	a.(i) <- (s1,s2); done;;

let check a b =
	let b = "!"^b in

	let rec h s n =
		if n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in

	let to_a s =
		let a = Array.make (String.length s) 0 in

		let rec f n =
			if n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in
		f 0; a in

	let srt s = let a = to_a s in Array.sort compare a; a in

	let hs = h a 0 in
	let aa = srt a in

        let rec is_shuffled s = aa = srt s in

	let rec f n hash =
		if (String.length b - n) >= String.length a then
				let newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in
				if newhash = hs && is_shuffled (String.sub b n (String.length a)) then true else f (n+1) newhash
		else false in
	if String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;

(*Printf.printf "%b" (check "abc" "adfcdbaasjkdfhklasdfhklsj");; *)

(*let ans = Array.make n false;;
 *)
for i = 0 to (n-1) do
	let (a,b) = a.(i) in
	if check a b then
		print_string "YES\n"
	else print_string "NO\n" done;;

let n = read_int();;
let a = Array.make n ("","");;

for i = 0 to (n-1) do
	let s1 = read_line() in
	let s2 = read_line() in
	a.(i) <- (s1,s2); done;;

let check a b =
	let b = "!"^b in

	let rec h s n =
		if n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in

	let to_a s =
		let a = Array.make (String.length s) 0 in

		let rec f n =
			if n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in
		f 0; a in

	let srt s = let a = to_a s in Array.sort compare a; a in

	let hs = h a 0 in
	let aa = srt a in

        let rec is_shuffled s = aa = srt s in

	let rec f n hash =
		if (String.length b - n) >= String.length a then
				let newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in
				if newhash = hs then is_shuffled (String.sub b n (String.length a)) else f (n+1) newhash
		else false in
	if String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;

(*Printf.printf "%b" (check "abc" "adfcdbaasjkdfhklasdfhklsj");; *)

(*let ans = Array.make n false;;
 *)
for i = 0 to (n-1) do
	let (a,b) = a.(i) in
	if check a b then
		print_string "YES\n"
	else print_string "NO\n" done;;

let n = read_int();;
let a = Array.make n ("","");;

for i = 0 to (n-1) do
	let s1 = read_line() in
	let s2 = read_line() in
	a.(i) <- (s1,s2); done;;

let check a b =
	let b = "!"^b in

	let rec h s n =
		if n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in

	let to_a s =
		let a = Array.make (String.length s) 0 in

		let rec f n =
			if n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in
		f 0; a in

	let srt s = let a = to_a s in Array.sort compare a; a in

	let hs = h a 0 in
	let aa = srt a in

  let rec is_shuffled s =
let st = srt s in
              let rec f n = if n>=String.length s then true else if st.(n) = aa.(n) then f (n+1) else false in
		if Array.length st = Array.length aa then f 0 else false in

	let rec f n hash =
		if (String.length b - n) >= String.length a then
				let newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in
				if newhash = hs then is_shuffled (String.sub b n (String.length a)) else f (n+1) newhash
		else false in
	if String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;

(*Printf.printf "%b" (check "abc" "adfcdbaasjkdfhklasdfhklsj");; *)

(*let ans = Array.make n false;;
 *)
for i = 0 to (n-1) do
	let (a,b) = a.(i) in
	if check a b then
		print_string "YES\n"
	else print_string "NO\n" done;;

let n = read_int();;
let a = Array.make n ("","");;

for i = 0 to (n-1) do
	let s1 = read_line() in
	let s2 = read_line() in
	a.(i) <- (s1,s2); done;;

let check a b =
	let b = "!"^b in

	let rec h s n =
		if n >= String.length s then 0 else (Char.code s.[n])+(h s (n+1)) in

	let to_a s =
		let a = Array.make (String.length s) 0 in

		let rec f n =
			if n>= String.length s then () else (a.(n) <- Char.code (s.[n]); f (n+1)) in
		f 0; a in

	let srt s = Array.sort compare (to_a s) in

	let hs = h a 0 in
	let aa = srt a in

        let rec is_shuffled s =
		if aa = srt s then true else false in

	let rec f n hash =
		if (String.length b - n) >= String.length a then
				let newhash = hash - Char.code (b.[n-1]) + Char.code (b.[n-1 + (String.length a)]) in
				if newhash = hs then is_shuffled (String.sub b n (String.length a)) else f (n+1) newhash
		else false in
	if String.length b < String.length a then false else f 1 (h (String.sub b 0 (String.length a)) 0);;

(*Printf.printf "%b" (check "abc" "adfcdbaasjkdfhklasdfhklsj");; *)

(*let ans = Array.make n false;;
 *)
for i = 0 to (n-1) do
	let (a,b) = a.(i) in
	if check a b then
		print_string "YES\n"
	else print_string "NO\n" done;;


Today, Marin is at a cosplay exhibition and is preparing for a group photoshoot!For the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least $$$2$$$ cosplayers, the number of males does not exceed the number of females (obviously).Currently, the line has $$$n$$$ cosplayers which can be described by a binary string $$$s$$$. The $$$i$$$-th cosplayer is male if $$$s_i = 0$$$ and female if $$$s_i = 1$$$. To ensure that the line is beautiful, you can invite some additional cosplayers (possibly zero) to join the line at any position. You can't remove any cosplayer from the line.Marin wants to know the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful. She can't do this on her own, so she's asking you for help. Can you help her?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases.  The first line of each test case contains a positive integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of cosplayers in the initial line. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ — describing the cosplayers already in line. Each character of the string is either 0 describing a male, or 1 describing a female. Note that there is no limit on the sum of $$$n$$$.

For each test case, print the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful.

NoteIn the first test case, for each pair of adjacent cosplayers, you can invite two female cosplayers to stand in between them. Then, $$$000 \rightarrow 0110110$$$.In the third test case, you can invite one female cosplayer to stand next to the second cosplayer. Then, $$$010 \rightarrow 0110$$$.

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let num = int_of_string(input_line stdin) in
  let line = (input_line stdin) in
let tot = ref 0 in
let truc = ref false in
let temp = ref 0 in
for j = 0 to String.length line -1 do
  if line.[j] = '0' then
    begin (if !temp >1 || not(!truc) then () else tot := !tot + 2 - !temp); truc := true ; temp := 0 end
  else incr temp
done ;
print_endline (string_of_int(!tot))
done;
;;


Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules so that the event gets more interesting to watch.Each mushroom grower has a mushroom that he will grow on the competition. Under the new rules, the competition consists of two parts. The first part lasts t1 seconds and the second part lasts t2 seconds. The first and the second part are separated by a little break.After the starting whistle the first part of the contest starts, and all mushroom growers start growing mushrooms at once, each at his individual speed of vi meters per second. After t1 seconds, the mushroom growers stop growing mushrooms and go to have a break. During the break, for unexplained reasons, the growth of all mushrooms is reduced by k percent. After the break the second part of the contest starts and all mushrooms growers at the same time continue to grow mushrooms, each at his individual speed of ui meters per second. After a t2 seconds after the end of the break, the competition ends. Note that the speeds before and after the break may vary.Before the match dwarf Pasha learned from all participants, what two speeds they have chosen. However, the participants did not want to disclose to him all their strategy and therefore, did not say in what order they will be using these speeds. That is, if a participant chose speeds ai and bi, then there are two strategies: he either uses speed ai before the break and speed bi after it, or vice versa.Dwarf Pasha really wants to win the totalizer. He knows that each participant chooses the strategy that maximizes the height of the mushroom. Help Dwarf Pasha make the final table of competition results.The participants are sorted in the result table by the mushroom height (the participants with higher mushrooms follow earlier in the table). In case of equal mushroom heights, the participants are sorted by their numbers (the participants with a smaller number follow earlier).

The first input line contains four integer numbers n, t1, t2, k (1 ≤ n, t1, t2 ≤ 1000; 1 ≤ k ≤ 100) — the number of participants, the time before the break, the time after the break and the percentage, by which the mushroom growth drops during the break, correspondingly. Each of the following n lines contains two integers. The i-th (1 ≤ i ≤ n) line contains space-separated integers ai, bi (1 ≤ ai, bi ≤ 1000) — the speeds which the participant number i chose.

Print the final results' table: n lines, each line should contain the number of the corresponding dwarf and the final maximum height of his mushroom with exactly two digits after the decimal point. The answer will be considered correct if it is absolutely accurate.

Note  First example: for each contestant it is optimal to use firstly speed 2 and afterwards speed 4, because 2·3·0.5 + 4·3 > 4·3·0.5 + 2·3.

let ni () = Scanf.scanf " %d" (fun x -> x) in
let nf () = float_of_int (ni ()) in
let n = ni () in
let t1 = nf () in
let t2 = nf () in
let k = 1.0 -. nf () /. 100.0 in
let f a b = a *. t1 *. k +. b *. t2 in
let a = Array.init n (fun i ->
  let a, b = nf (), nf () in
  (-1. *. max (f a b) (f b a), i + 1)
) in
Array.sort compare a;
Array.iter (fun (e, i) ->
  Printf.printf "%d %.2f\n" i ~-.e
) a;;

open Array;;

let (|>) x f = f x

let calc t1 t2 k  = fun (a, b, i) ->
        let a = float a in
        let b = float b in
        let f a b = a *. t1 *. (1.0 -. k) +. b *. t2 in
                ( max (f a b) (f b a) , i)
(* (res, i) *)

let cmp' x =
        if x > 0.0
        then -1
        else if x < 0.0 then 1
        else 0

let cmp = fun (a, c) -> fun (b, d) ->
        if a = b
        then c - d
        else cmp' (a -. b)
let print a =
        Printf.printf "%d " (snd a + 1);
        (fst a)|> Printf.printf "%.2f\n"

let main _ =
        let f i = Scanf.scanf "%d %d\n" (fun a -> fun b -> a, b, i) in
        let n, t1, t2, k = Scanf.scanf "%d %d %d %d\n"
         (fun m -> fun p->fun k->fun l
         -> m,p,k,l) in
          let a =  init n f  |> map (calc (float t1) (float t2) ((float k)/. 100.0) ) in
                fast_sort cmp a;
                iter print a;;

main ();;

open Array;;

 let (|>) x f = f x

let calc t1 t2 k  = fun (a, b, i) ->
        let a = float a in
        let b = float b in
        let f a b = a *. t1 *. (1.0 -. k) +. b *. t2 in
                ( max (f a b) (f b a) , i)
(* (res, i) *)

let cmp' x =
        if x > 0.0
        then -1
        else if x < 0.0 then 1
        else 0

let cmp = fun (a, c) -> fun (b, d) ->
        if a = b
        then d - c
        else cmp' (a -. b)
let print a =
        Printf.printf "%d " (snd a + 1);
        (fst a)|> Printf.printf "%.2f\n"

let main _ =
        let f i = Scanf.scanf "%d %d\n" (fun a -> fun b -> a, b, i) in
        let n, t1, t2, k = Scanf.scanf "%d %d %d %d\n"
         (fun m -> fun p->fun k->fun l
         -> m,p,k,l) in
          let a =  init n f  |> map (calc (float t1) (float t2) ((float k)/. 100.0) ) in
                fast_sort cmp a;
                iter print a;;

main ();;


Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met:  i-th box is not put into another box;  j-th box doesn't contain any other boxes;  box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!

The first line contains one integer n (1 ≤ n ≤ 5000) — the number of boxes Mishka has got. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the side length of i-th box.

Print the minimum possible number of visible boxes.

NoteIn the first example it is possible to put box 1 into box 2, and 2 into 3.In the second example Mishka can put box 2 into box 3, and box 4 into box 1.

let input () =
  let getNumber () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
  in let n = getNumber ()
  in let a = Array.make n (max_int, false)
  in begin
    for i = 0 to n - 1 do
      a.(i) <- (getNumber (), false)
    done;
    a
  end

let bSearch i a =
  let n = Array.length a
  in let l = ref (i + 1)
  in let r = ref (n - 1)
  in let m = ref 0
  in let found = ref false
  in begin
    while l <= r do
      m := (!l + !r) / 2;
      if fst a.(!m) > fst a.(i) && snd a.(!m) = false then
        if fst a.(!m - 1) = fst a.(i) || snd a.(!m - 1) = true then
          (r := !l - 1;
           found := true)
        else
          r := !m - 1
      else
        l := !m + 1
    done;
    if !found then Some !m
    else None
  end

let eat a =
  let n = Array.length a
  in let count = ref n
  in begin
    for i = 0 to n - 1 do
      match bSearch i a with
      | Some x -> begin
          count := !count - 1;
          a.(x) <- (fst a.(x), true)
        end
      | None -> ()
    done;
    !count
  end

let main () =
  let a = input ()
  in let cmp (x, _) (y, _) = compare x y
  in begin
    Array.sort cmp a;
    Printf.printf "%d" (eat a)
  end
;;

main ();;

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = Array.init n read_int in

  Array.sort compare a;

  let rec run_length prev count best i = if i=n then best else (
    if a.(i) = prev then (
      let count = count + 1 in
      let best = max best count in
      run_length prev count best (i+1)
    ) else (
      run_length a.(i) 1 best (i+1)
    )
  ) in

  printf "%d\n" (run_length a.(0) 1 1 1)

let input () =
  let getNumber () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
  in let n = getNumber ()
  in let a = Array.make n (max_int, false)
  in begin
    for i = 0 to n - 1 do
      a.(i) <- (getNumber (), false)
    done;
    a
  end

let bSearch i a =
  let n = Array.length a
  in let l = ref (i + 1)
  in let r = ref (n - 1)
  in let m = ref 0
  in let found = ref false
  in begin
    while l <= r do
      m := (!l + !r) / 2;
      if fst a.(!m) > fst a.(i) && snd a.(!m) = false then
        if fst a.(!m - 1) = fst a.(i) || snd a.(!m - 1) = true then
          (r := !l - 1;
           found := true)
        else
          r := !m - 1
      else
        l := !m + 1
    done;
    if !found then Some !m
    else None
  end

let eat a =
  let n = Array.length a
  in let count = ref n
  in begin
    for i = 0 to n - 1 do
      match bSearch i a with
      | Some x -> begin
          count := !count - 1;
          a.(x) <- (fst a.(x), true)
        end
      | None -> ()
    done;
    !count
  end

let main () =
  let a = input ()
  in let cmp (x, _) (y, _) = compare x y
  in begin
    Array.sort cmp a;
    eat a
  end
;;

main ();;


Vasiliy is fond of solving different tasks. Today he found one he wasn't able to solve himself, so he asks you to help.Vasiliy is given n strings consisting of lowercase English letters. He wants them to be sorted in lexicographical order (as in the dictionary), but he is not allowed to swap any of them. The only operation he is allowed to do is to reverse any of them (first character becomes last, second becomes one before last and so on).To reverse the i-th string Vasiliy has to spent ci units of energy. He is interested in the minimum amount of energy he has to spent in order to have strings sorted in lexicographical order.String A is lexicographically smaller than string B if it is shorter than B (|A| < |B|) and is its prefix, or if none of them is a prefix of the other and at the first position where they differ character in A is smaller than the character in B.For the purpose of this problem, two equal strings nearby do not break the condition of sequence being sorted lexicographically.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of strings. The second line contains n integers ci (0 ≤ ci ≤ 109), the i-th of them is equal to the amount of energy Vasiliy has to spent in order to reverse the i-th string.  Then follow n lines, each containing a string consisting of lowercase English letters. The total length of these strings doesn't exceed 100 000.

If it is impossible to reverse some of the strings such that they will be located in lexicographical order, print  - 1. Otherwise, print the minimum total amount of energy Vasiliy has to spent.

NoteIn the second sample one has to reverse string 2 or string 3. To amount of energy required to reverse the string 3 is smaller.In the third sample, both strings do not change after reverse and they go in the wrong order, so the answer is  - 1.In the fourth sample, both strings consists of characters 'a' only, but in the sorted order string "aa" should go before string "aaa", thus the answer is  - 1.

open Printf
open String
open Int64

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

let e = Array.make n Int64.zero (*energy for reverse string*)
let s = Array.make n "" (*stores all the strings to be sorted*)
let rs = Array.make n ""

let d1 = Array.make n (Int64.max_int) (*flip*)

let d2 = Array.make n (Int64.max_int)

for i = 0 to n-1 do
  let jj = Scanf.bscanf Scanf.Scanning.stdin "%Ld " (fun x -> x) in
  e.(i) <- jj
done

let rev s =
  let len = String.length s in
  let rec rev_helper i s2 =
    if i >= len then s2
    else
      rev_helper (i+1) s2^(Char.escaped s.[i])
  in
  rev_helper 0 ""

for i = 0 to n - 1 do
  let jj = Scanf.bscanf Scanf.Scanning.stdin "%s " (fun x -> x) in
  s.(i) <- jj; rs.(i) <- (rev jj)
done

let () = d1.(0) <- of_int 0;;
let () = d2.(0) <- e.(0);;

(*printf "%Ld" max_int;;
*)

(*DEBUG*)
(*
 let () = print_endline (rev "abc")

for i = 0 to n - 1 do
  print_endline s.(i);
  print_endline rs.(i)
done
*)

let g s1 s2 =
  let x = String.compare s1 s2 in
  if (x<=0) then of_int 0
  else max_int

let f s1 s2 n =
  let x = String.compare s1 s2 in
  if (x<=0) then e.(n)
  else max_int

let my_add a b =
  if ( (compare a max_int == 0 ) || (compare b max_int == 0 ) ) then max_int
  else add a b

let () =
  for i = 1 to n - 1 do
    let x1 = my_add d1.(i-1)  (g s.(i-1) s.(i) ) in
    let x2 = my_add d2.(i-1) (g rs.(i-1) s.(i) ) in
    d1.(i) <- min x1 x2;
   let y1 = my_add d1.(i-1) (f s.(i-1) rs.(i) i ) in
   let y2 = my_add d2.(i-1)  (f rs.(i-1) rs.(i) i ) in
   d2.(i) <- min y1 y2
done

let () =
  let x = min d1.(n-1) d2.(n-1) in
  if (x==max_int) then printf "%d\n" (-1)
  else print_endline (to_string x)

open Printf
open Scanf

let reverse s =
  let n = String.length s in
  String.init n (fun i -> s.[n-i-1])

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b

let long x = Int64.of_int x
let short x = Int64.to_int x

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 c = Array.init n (fun _ -> long (read_int())) in
  let s = Array.init n (fun _ -> read_string ()) in
  let sr = Array.init n (fun i -> reverse s.(i)) in

  let nr_cost = Array.make n 0L in
  let r_cost = Array.make n 0L in

  nr_cost.(n-1) <- 0L;
  r_cost.(n-1) <- c.(n-1);

  let inf = (Int64.max_int) // 4L in

  for i=n-2 downto 0 do
    let test a b = if a > b then inf else 0L in
    nr_cost.(i) <- min
      (nr_cost.(i+1) ++ (test s.(i) s.(i+1)))
      (r_cost.(i+1) ++ (test s.(i) sr.(i+1)));
    r_cost.(i) <- c.(i) ++ min
      (nr_cost.(i+1) ++ (test sr.(i) s.(i+1)))
      (r_cost.(i+1) ++ (test sr.(i) sr.(i+1)));
    nr_cost.(i) <- min nr_cost.(i) inf;
    r_cost.(i) <- min r_cost.(i) inf;
  done;

  let total = min nr_cost.(0) r_cost.(0) in

  if total = inf then printf "-1\n" else printf "%Ld\n" total

open Printf
open String

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

let e = Array.make n (-1) (*energy for reverse string*)
let s = Array.make n "" (*stores all the strings to be sorted*)
let rs = Array.make n ""

let d1 = Array.make n (max_int) (*flip*)

let d2 = Array.make n (max_int)

for i = 0 to n-1 do
  let jj = Scanf.bscanf Scanf.Scanning.stdin "%d " (fun x -> x) in
  e.(i) <- jj
done

let rev s =
  let len = String.length s in
  let rec rev_helper i s2 =
    if i >= len then s2
    else
      rev_helper (i+1) s2^(Char.escaped s.[i])
  in
  rev_helper 0 ""

for i = 0 to n - 1 do
  let jj = Scanf.bscanf Scanf.Scanning.stdin "%s " (fun x -> x) in
  s.(i) <- jj; rs.(i) <- (rev jj)
done

let () = d1.(0) <- 0;;
let () = d2.(0) <- e.(0);;

(*DEBUG*)
(*
 let () = print_endline (rev "abc")

for i = 0 to n - 1 do
  print_endline s.(i);
  print_endline rs.(i)
done
*)

let g s1 s2 =
  let x = String.compare s1 s2 in
  if (x<=0) then 0
  else max_int

let f s1 s2 n =
  let x = String.compare s1 s2 in
  if (x<=0) then e.(n)
  else max_int

let my_add a b =
  if (a==max_int || b==max_int) then max_int
  else a + b

let () =
  for i = 1 to n - 1 do
    let x1 = my_add d1.(i-1)  (g s.(i-1) s.(i) ) in
    let x2 = my_add d2.(i-1) (g rs.(i-1) s.(i) ) in
    d1.(i) <- min x1 x2;
   let y1 = my_add d1.(i-1) (f s.(i-1) rs.(i) i ) in
   let y2 = my_add d2.(i-1)  (f rs.(i-1) rs.(i) i ) in
   d2.(i) <- min y1 y2
done

let () =
  let x = min d1.(n-1) d2.(n-1) in
  if (x==max_int) then
    begin
      print_int (-1); print_endline ""
    end
  else
    begin
      print_int x; print_endline ""
    end


Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is exactly the case today: because of technical issues, no flights were able to depart during the first k minutes of the day, so now the new departure schedule must be created.All n scheduled flights must now depart at different minutes between (k + 1)-th and (k + n)-th, inclusive. However, it's not mandatory for the flights to depart in the same order they were initially scheduled to do so — their order in the new schedule can be different. There is only one restriction: no flight is allowed to depart earlier than it was supposed to depart in the initial schedule.Helen knows that each minute of delay of the i-th flight costs airport ci burles. Help her find the order for flights to depart in the new schedule that minimizes the total cost for the airport.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 300 000), here n is the number of flights, and k is the number of minutes in the beginning of the day that the flights did not depart. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 107), here ci is the cost of delaying the i-th flight for one minute.

The first line must contain the minimum possible total cost of delaying the flights. The second line must contain n different integers t1, t2, ..., tn (k + 1 ≤ ti ≤ k + n), here ti is the minute when the i-th flight must depart. If there are several optimal schedules, print any of them.

NoteLet us consider sample test. If Helen just moves all flights 2 minutes later preserving the order, the total cost of delaying the flights would be (3 - 1)·4 + (4 - 2)·2 + (5 - 3)·1 + (6 - 4)·10 + (7 - 5)·2 = 38 burles. However, the better schedule is shown in the sample answer, its cost is (3 - 1)·4 + (6 - 2)·2 + (7 - 3)·1 + (4 - 4)·10 + (5 - 5)·2 = 20 burles.

open Printf
open Scanf

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let long x = Int64.of_int x
let short x = Int64.to_int x

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) 0L

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

let () =
  let n = read_int () in
  let k = read_int () in

  let original_cost = Array.init n (fun _ -> long (read_int())) in
  let c = Array.init n (fun i -> (original_cost.(i),i)) in

  let skip_to = Array.init (k+n) (fun i -> i+1) in
  let item = Array.make (k+n) (-1) in

  Array.sort (fun a b -> compare b a) c;

  for i=0 to n-1 do
    let (cost,index) = c.(i) in
    let place = max index k in
    let rec find_empty j =
      if item.(j) = -1 then j
      else find_empty skip_to.(j)
    in
    let place1 = find_empty place in
    item.(place1) <- index;
    let rec push j =
      if j = place1 then () else (
	let nj = skip_to.(j) in
	skip_to.(j) <- place1;
	push nj
      )
    in
    push place
  done;

  let total_cost = sum k (k+n-1) (fun j ->
(*    printf "j=%d " j;
    printf "item.(j) = %d\n" item.(j); *)
    let index = item.(j) in
    original_cost.(index) ** ((long j) -- (long index))
  ) in

  let times = Array.make n 0 in

  printf "%Ld\n" total_cost;

  for j = k to (k+n-1) do
    times.(item.(j)) <- j+1
  done;

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

  print_newline()


Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat.  There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ..., an and p1, ..., pn. In each day, he can buy arbitrary amount of meat, also he can keep some meat he has for the future.Malek is a little tired from cooking meat, so he asked for your help. Help him to minimize the total money he spends to keep Duff happy for n days.

The first line of input contains integer n (1 ≤ n ≤ 105), the number of days. In the next n lines, i-th line contains two integers ai and pi (1 ≤ ai, pi ≤ 100), the amount of meat Duff needs and the cost of meat in that day.

Print the minimum money needed to keep Duff happy for n days, in one line.

NoteIn the first sample case: An optimal way would be to buy 1 kg on the first day, 2 kg on the second day and 3 kg on the third day.In the second sample case: An optimal way would be to buy 1 kg on the first day and 5 kg (needed meat for the second and third day) on the second day.

open Str;;
open Array;;
let n = read_int () and ans = ref 0 and price = ref 101;;
for i = 1 to n do
    let ins = map (int_of_string) (of_list (split (regexp " ") (read_line ()))) in
    let a = ins.(0) and b = ins.(1) in
    begin
        price := min !price b;
        ans := !ans + !price * a;
    end;
done;;
print_int !ans;;

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

let input () =
    let n = read () in
    let rec loop i list =
        if i < n
        then
            let mass = read () in
            let price = read () in
            loop (i + 1) ((mass, price) :: list)
        else
            List.rev list
    in loop 0 []

let get_min price min =
    if price >= min
    then
        min
    else
        price

let get_sum sum min mass =
    sum + min * mass

let update_sum_min (mass, price) (sum, min) =
    let min_upd = get_min price min in
    let sum_upd = get_sum sum mass min_upd in
    (sum_upd, min_upd)

let solve list =
    let rec loop (sum, min) list =
        match list with
        | (head :: tail) -> loop (update_sum_min head (sum, min)) tail
        | [] -> sum
    in loop (0, 101) list

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

let () = Scanf.scanf "%d\n" (fun n ->
			     let a = Array.init n (fun _ ->
						   Scanf.scanf "%d %d\n"
							       (fun a w -> (a, w))) in
			     (* buy as much as we need to hit the next cheapest day *)
			     let rec calc cur acc =
			       if cur >= n then acc
			       else begin
				   let rec loop i s =
				     if i >= n || snd a.(i) < snd a.(cur)
				     then i, s
				     else loop (i + 1) (s + fst a.(i) * snd a.(cur)) in
				   let next, add = loop cur 0 in
				   calc next (acc + add)
				 end
			     in
			     Printf.printf "%d\n" (calc 0 0))

let () = Scanf.scanf "%d\n" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf "%d%_c%d%_c" (fun x y -> (x, y))) in

	let sum = ref 0 in

	let min = ref 2000000 in

	let rec loop i =
		if i < n then
		begin
			let (x, y) = a.(i) in
			if !min > y then begin min := y end;
			sum := !sum + x * !min;
			loop (i+1)
		end
	in
	loop 0;
	Printf.printf "%d\n" !sum);;

let () = Scanf.scanf "%d\n" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf "%d%_c%d%_c" (fun x y -> (x, y))) in

	let sum = ref 0 in

	let min = ref 2000000 in

	let rec loop i =
		if i < n then
		begin
			let (x, y) = a.(i) in
			if !min > x then begin min := x end;
			sum := !sum + y * !min;
			loop (i+1)
		end
	in
	loop 0;
	Printf.printf "%d\n" !sum);;


There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?

The first line contains a single integer n (1 ≤  n ≤ 100).  The next line contains an integer p (0 ≤ p ≤ n) at first, then follows p distinct integers a1, a2, ..., ap (1 ≤ ai ≤ n). These integers denote the indices of levels Little X can pass. The next line contains the levels Little Y can pass in the same format. It's assumed that levels are numbered from 1 to n.

If they can pass all the levels, print "I become the guy.". If it's impossible, print "Oh, my keyboard!" (without the quotes).

NoteIn the first sample, Little X can pass levels [1 2 3], and Little Y can pass level [2 4], so they can pass all the levels both.In the second sample, no one can pass level 4.

let rec get_uniques = function
    | head :: (middle :: _ as tail) ->
        if head = middle
        then
            get_uniques tail
        else
            (head :: get_uniques tail)
    | smaller -> smaller

let read () = List.map (fun n -> Pervasives.int_of_string n) (Str.split (Str.regexp " ") (Pervasives.read_line ()))

let n = Pervasives.read_int ()
let x_levels = read ()
let y_levels = read ()

let result =
    let len = List.length (get_uniques (List.sort (compare) (List.append (List.tl x_levels) (List.tl y_levels))))
    in
    if  len = n
    then
        "I become the guy."
    else
        "Oh, my keyboard!"

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

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

let rec get_uniques = function
    | head :: (middle :: _ as tail) ->
        if head = middle
        then
            get_uniques tail
        else
            (head :: get_uniques tail)
    | smaller -> smaller

let n = Scanf.scanf "%d " (fun n -> n)
let x_levels = read ()
let y_levels = read ()

let result =
    let len = List.length (get_uniques (List.sort (compare) (List.append x_levels y_levels)))
    in
    if  len = n
    then
        "I become the guy."
    else
        "Oh, my keyboard!"

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

let n = read_int () in
let tr = Array.make n false in

let g () =
let l = Scanf.Scanning.from_string (read_line ()) in
try
let tc = Scanf.bscanf l "%d " (fun x -> x) in
(for i = 1 to tc do
 let k = Scanf.bscanf l "%d " (fun x -> x) in
 tr.(k-1) <-  true
done)
with _ -> ()
in
g() ; g() ;

let f () =
 let result = ref true in
 for i = 0 to n-1 do
  if tr.(i) = false then result := false
 done;
 !result
in

if f () then
print_endline "I become the guy."
else
print_endline "Oh, my keyboard!";;

module IntSet = Set.Make(
  struct
    let compare = Pervasives.compare
    type t = int
  end ) ;;

let rec split s i acc =
begin
  if i > String.length s
  then List.rev acc
  else
      let first =
      if String.contains_from s i ' '
         then  String.index_from s i ' '
         else String.length s
    in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc)
end in

let from_list xs = List.fold_right IntSet.add xs IntSet.empty in
let alln =
    let len = int_of_string (read_line()) in
    Array.init len (fun a -> a+1)
        |> (fun xs -> Array.fold_right IntSet.add xs IntSet.empty)  in
let x = split (read_line ()) 0 [] |> List.tl |> from_list in
let y = split (read_line ()) 0 [] |> List.tl |> from_list in
print_string (if IntSet.equal alln (IntSet.union x y) then "I become the guy." else "Oh, my keyboard!")

let rec get_uniques = function
    | head :: (middle :: _ as tail) ->
        if head = middle
        then
            get_uniques tail
        else
            (head :: get_uniques tail)
    | smaller -> smaller

let read () = List.map (fun n -> Pervasives.int_of_string n) (Str.split (Str.regexp " ") (Pervasives.read_line ()))

let n = Pervasives.read_int ()
let x_levels = read ()
let y_levels = read ()

let result =
    let len = List.length (get_uniques (List.sort (compare) (List.append x_levels y_levels)))
    in
    if  len = n
    then
        "I become the guy."
    else
        "Oh, my keyboard!"

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

let n = read_int () in
let tr = Array.make n false in

let g () =
let l = Scanf.Scanning.from_string (read_line ()) in
try
(for i = 1 to n do
 let k = Scanf.bscanf l "%d " (fun x -> x) in
 tr.(k-1) <-  true
done)
with _ -> ()
in
g() ; g() ;

let f () =
 let result = ref true in
 for i = 0 to n-1 do
  if tr.(i) = false then result := false
 done;
 !result
in

if f () then
print_endline "I become the guy."
else
print_endline "Oh, my keyboard!";;

let n = read_int () in
let tr = Array.make n false in

let g () =
let l = Scanf.Scanning.from_string (read_line ()) in
try
(for i = 1 to n do
 let k = Scanf.bscanf l "%d " (fun x -> x) in
 tr.(k-1) <-  true
done)
with _ -> ()
in
g() ; g() ;

let f () =
 let result = ref true in
 for i = 0 to n-1 do
  if tr.(i) = false then result := false
 done;
 !result
in

if f () then
print_endline "I become the guy"
else
print_endline "Oh, my keyboard!";;

module IntSet = Set.Make(
  struct
    let compare = Pervasives.compare
    type t = int
  end ) ;;

let rec split s i acc =
begin
  if i == 1 + String.length s
  then acc
  else
      let first =
      if String.contains_from s i ' '
         then  String.index_from s i ' '
         else String.length s
    in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc)
end in

let from_list xs = List.fold_right IntSet.add xs IntSet.empty in
let alln =
    let len = int_of_string (read_line()) in
    Array.init len (fun a -> a+1)
        |> (fun xs -> Array.fold_right IntSet.add xs IntSet.empty)  in
let x = split (read_line ()) 0 [] |> List.tl |> from_list in
let y = split (read_line ()) 0 [] |> List.tl |> from_list in
print_string (if IntSet.equal alln (IntSet.union x y) then "I become the guy." else "Oh, my keyboard!")


PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?

The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest. The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id. It's guaranteed that the sequence p corresponds to some valid forest. Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows: 5 31 23 44 5

You should output the number of trees in the forest where PolandBall lives.

NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.

type t = {p : int array;
	  rank : int array}

let makeset set x =
  set.p.(x) <- x;
  set.rank.(x) <- 0

let rec find set x =
  if x <> set.p.(x) then set.p.(x) <- find set set.p.(x);
  set.p.(x)

let link set x y =
  if set.rank.(x) > set.rank.(y) then (
    set.p.(y) <- x;
    x
  ) else (
    if set.rank.(x) = set.rank.(y) then set.rank.(y) <- set.rank.(y) + 1;
    set.p.(x) <- y;
    y
  )

let newsets size =
  let set =
    {p = Array.make size (-1);
     rank = Array.make size 0
    }
  in
    for i = 0 to size-1 do
      makeset set i
    done;
    set

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let p = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      p.(i) <- Scanf.bscanf sb " %d" (fun s -> s) - 1
    done;
  in
  let ds = newsets n in
    for i = 0 to n - 1 do
      let u = find ds i in
      let v = find ds p.(i) in
	ignore (link ds u v)
    done;
    let res = ref 0 in
      for i = 0 to n - 1 do
	if find ds i = i
	then incr res
      done;
      Printf.printf "%d\n%!" !res


You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the corresponding square exists and is empty. The game ends as soon as the sheep are lined up, that is, there should be no empty cells between any sheep.For example, if $$$n=6$$$ and the level is described by the string "**.*..", then the following game scenario is possible:   the sheep at the $$$4$$$ position moves to the right, the state of the level: "**..*.";  the sheep at the $$$2$$$ position moves to the right, the state of the level: "*.*.*.";  the sheep at the $$$1$$$ position moves to the right, the state of the level: ".**.*.";  the sheep at the $$$3$$$ position moves to the right, the state of the level: ".*.**.";  the sheep at the $$$2$$$ position moves to the right, the state of the level: "..***.";  the sheep are lined up and the game ends. For a given level, determine the minimum number of moves you need to make to complete the level.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$). The second line of each test case contains a string of length $$$n$$$, consisting of the characters '.' (empty space) and '*' (sheep) — the description of the level. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$.

For each test case output the minimum number of moves you need to make to complete the level.

open Printf;;
open List;;
let n = read_int();;
let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []
let count_sheep sl =
  let counter = ref 0L in
    List.map (fun x -> if x == '*' then
        (counter := Int64.(add (!counter) 1L);
        0L) else
        !counter
      ) sl;;
let rec zip (l1, l2) =
  match (l1, l2) with
  | (_, []) -> []
  | ([], _) -> []
  | (h1::t1, h2::t2) -> (h1, h2) :: zip (t1, t2)
let solve sl =
  let left = count_sheep (explode sl) in
  let right = count_sheep (List.rev (explode sl)) in
  let counts = zip (left, (List.rev right)) in
  List.fold_right (fun (x, y) res -> Int64.(add (min x y) res)) counts 0L;;
for i = 0 to n - 1 do
  let _ = read_int() in
  let line = read_line() in
  printf "%Ld\n" (solve line)
done

open Printf;;
open List;;
let n = read_int();;
let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []
let count_sheep sl =
  let counter = ref 0 in
    List.map (fun x -> if x == '*' then
        (counter := (!counter) + 1;
        0) else
        !counter
      ) sl;;
let rec zip (l1, l2) =
  match (l1, l2) with
  | (_, []) -> []
  | ([], _) -> []
  | (h1::t1, h2::t2) -> (h1, h2) :: zip (t1, t2)
let solve sl =
  let left = count_sheep (explode sl) in
  let right = count_sheep (List.rev (explode sl)) in
  let counts = zip (left, (List.rev right)) in
  List.fold_right (fun (x, y) res -> (min x y) + res) counts 0;;
for i = 0 to n - 1 do
  let _ = read_int() in
  let line = read_line() in
  printf "%d\n" (solve line)
done


I wonder, does the falling rain Forever yearn for it's disdain?Effluvium of the MindYou are given a positive integer $$$n$$$.Find any permutation $$$p$$$ of length $$$n$$$ such that the sum $$$\operatorname{lcm}(1,p_1) + \operatorname{lcm}(2, p_2) + \ldots + \operatorname{lcm}(n, p_n)$$$ is as large as possible. Here $$$\operatorname{lcm}(x, y)$$$ denotes the least common multiple (LCM) of integers $$$x$$$ and $$$y$$$.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 1\,000$$$). Description of the test cases follows. The only line for each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ — the permutation with the maximum possible value of $$$\operatorname{lcm}(1,p_1) + \operatorname{lcm}(2, p_2) + \ldots + \operatorname{lcm}(n, p_n)$$$. If there are multiple answers, print any of them.

NoteFor $$$n = 1$$$, there is only one permutation, so the answer is $$$[1]$$$.For $$$n = 2$$$, there are two permutations:   $$$[1, 2]$$$ — the sum is $$$\operatorname{lcm}(1,1) + \operatorname{lcm}(2, 2) = 1 + 2 = 3$$$.  $$$[2, 1]$$$ — the sum is $$$\operatorname{lcm}(1,2) + \operatorname{lcm}(2, 1) = 2 + 2 = 4$$$.

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 () with
  | Some n ->
      let rec f i =
        if i > n then ()
        else
          let () = print_int (i + 1) in
          let () = print_char ' ' in
          let () = print_int i in
          let () = print_char ' ' in
          f (i + 2)
      in
      if n mod 2 = 0 then f 1
      else
        let () = print_char '1' in
        let () = print_char ' ' in
        f 2
  | _ -> ()

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

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 () with
  | Some n ->
      let rec f i =
        if i = n then print_string "1"
        else
          let i = i + 1 in
          let () = print_int i in
          let () = print_char ' ' in
          f i
      in
      f 1
  | _ -> ()

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


Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $$$n$$$ problems of distinct difficulty, the difficulties are numbered from $$$1$$$ to $$$n$$$.To hold a round Arkady needs $$$n$$$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $$$1$$$ to $$$n$$$ and puts it into the problems pool.At each moment when Arkady can choose a set of $$$n$$$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of difficulty levels and the number of problems Arkady created. The second line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le n$$$) — the problems' difficulties in the order Arkady created them.

Print a line containing $$$m$$$ digits. The $$$i$$$-th digit should be $$$1$$$ if Arkady held the round after creation of the $$$i$$$-th problem, and $$$0$$$ otherwise.

NoteIn the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem.

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

let () =
    let n = read_int () and m = read_int () in
    let a = Array.init m read_int
    and cnt = Array.make (n + 1) 0
    and ans = Array.make m 0
    and index = ref 1 in
    for i = 0 to m - 1 do
        cnt.(a.(i)) <- cnt.(a.(i)) + 1;
        while cnt.(!index) <> 0 do
            cnt.(!index) <- cnt.(!index) - 1;
            if !index = n then ans.(i) <- 1;
            index := !index mod n + 1
        done
    done;
    for i = 0 to m - 1 do
        printf "%d" ans.(i)
    done

Array.(Scanf.(
  scanf " %d %d" @@ fun n m ->
    let cnt,exist = make n 0, make m 0 in
    init m @@ fun _ -> scanf " %d" @@ fun v -> (
      let v = v - 1 in
      exist.(cnt.(v)) <- exist.(cnt.(v)) + 1;
      print_string (
        if exist.(cnt.(v)) = n then "1" else "0");
      cnt.(v) <- cnt.(v) + 1)))

module SegTree = struct
  module type S = sig
    type t
    val  op: t -> t -> t
    val ide: t
    val upd: t -> t -> t
  end
  module RMQ : S with type t = int64 =
    struct
      type t = int64 let op = min
      let ide = Int64.max_int let upd _ v = v
    end
  module RSQ : S with type t = int64 =
    struct
      type t = int64 let op = Int64.add
      let ide = 0L let upd prev v = op prev v
    end
  let par i = (i-1)/2
  let chl i = 2*i+1
  let chr i = 2*i+2
  module Make (X:S) = struct
    type t = SegTree of (X.t array * int)
    let raw (SegTree (a,_)) = a
    let make raw = (* O(n) *)
      let ln = Array.length raw in
      let n =
        let n = ref 1 in
        while !n<ln do n := !n*2 done; !n in
      let a = Array.make (2*n-1) X.ide in
      for i=0 to ln-1 do
        a.(i+n-1) <- raw.(i) done;
      for i=n-2 downto 0 do
        a.(i) <- X.op a.(chl i) a.(chr i) done;
      SegTree (a,n)
    let update_destructive (SegTree(a,n)) i v =
      let i = ref @@ i+(n-1) in
      a.(!i) <- X.upd a.(!i) v;
      while !i>0 do
        i := par !i;
        a.(!i) <- X.op a.(chl !i) a.(chr !i) done
    let get_half_open (SegTree(a,n)) l r = (* O(logn), [l,r) *)
      let rec f0 i p q =
        if q<=l || r<=p then X.ide
        else if l<=p && q<=r then a.(i)
        else
          let vl = f0 (2*i+1) p ((p+q)/2) in
          let vr = f0 (2*i+2) ((p+q)/2) q in
          X.op vl vr
      in f0 0 0 n
    let get_closed seg l r = get_half_open seg l (r+1) (* [l,r] *)
  end
end
let (++) = Int64.add
module S = SegTree.Make(SegTree.RMQ);;
Scanf.(Array.(scanf " %d %d" @@ fun n m ->
  let a = init m (fun _ -> scanf " %d" @@ fun v -> v) in
  let s = S.make @@ make (n+1) 0L in
  fold_left (fun k v ->
    S.update_destructive s v (S.get_closed s v v ++ 1L);
    if S.get_closed s 1 n = k then (
      print_int 1; k++1L
    ) else (
      print_int 0; k
    )
  ) 1L a |> ignore
))

module MultiSet_test = struct
  module Make (X:Map.OrderedType) = struct
    include Map.Make(X)
    let count v set =
      try find v set with Not_found -> 0
    let remove_each v set =
      let k = count v set in
      if k<=0 then raise Not_found
      else if k=1 then remove v set
      else add v (k-1) set
    let add_each v set =
      let k = count v set in
      if k=0 then add v 1 set
      else add v (k+1) set
    let iter_each f set =
      let rec f0 k = function
      | 0 -> ()
      | i -> let () = f k in f0 k (i-1)
      in iter f0 set
    let fold_each f set ac =
      let rec f0 k i ac = match i with
      | 0 -> ac
      | i -> f0 k (i-1) (f k ac)
      in fold f0 set ac
    let bindings_each set =
      fold_each (fun v ls -> v::ls) set []
      |> List.rev
    let min_binding_each set = fst @@ min_binding set
    let max_binding_each set = fst @@ max_binding set
    let exists_each f = exists (fun k _ -> f k)
    let cardinal_each set =
      (* O(#node). an aux variable might lead you to O(1) perf *)
      fold (fun _ v sum -> sum + v) set 0
  end
end
module S = MultiSet_test.Make (struct
  type t = int let compare = compare
end);;
Array.(Scanf.(
  scanf " %d %d" @@ fun n m ->
    let a = init m (fun _ -> scanf " %d" @@ fun v -> v) in
    let c = make n 0 in
    fold_left (fun (s,round) v ->
      let v = v-1 in
      let s = S.remove_each c.(v) s in
      let s = S.add_each (c.(v)+1) s in
      c.(v) <- c.(v) + 1;
      let p = S.min_binding_each s in
      print_char (
        if p > round then '1' else '0'
      ); (s,p)
    ) (S.singleton 0 n, 0) a |> ignore))

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

  (* let b = make (i32 n) 0L in
  let k = ref 1L in
  iter (fun v ->
    let i = i32 v -$ 1 in
    b.(i) <- b.(i) + 1L;
    if fold_left min max_i64 b = !k then (
      printf "1"; k += 1L
    ) else printf "0"
  ) a *)

(* module BIT = struct
  let lsb i = i land -i
  let sum i b = (* 0-indexed; Σa[0,i-1] *)
    fix (fun f i s -> if i>0 then f (i -$ lsb i) (s + b.(i)) else s) i 0L
  let sum_closed i = sum (i+$1) (* 0-indexed; Σa[0,i] *)
  let sum_interval l r b = (* 0-indexed; Σa[l,r] = Σa[0,r+1-1] - Σ[0,l-1] *)
    if l>r then 0L else sum (r+$1) b - sum l b
  let add i x b = (* 0-indexed; a[i]+=x. not b *)
    if i<0 then raise @@ Invalid_argument "index should be >= 1 (0-indexed a[i-1]+=x)";
    fix (fun f i -> if i<Array.length b then (
      b.(i) <- b.(i) + x; f (i +$ lsb i))) (i+$1)
  let of_array a = let b = Array.make (Array.length a +$ 1) 0L in
    Array.iteri (fun i v -> add (i+$1) v b) a; b
  let make n = Array.make (n+$1) 0L
  let reconst b = Array.init (Array.length b-$1) (fun i -> sum_interval i i b)
  (* initialization: http://hos.ac/slides/20140319_bit.pdf *)
end
let () =
  let n,m = g2 0 in
  let a = iia m in
  let b = BIT.make (i32 n+$1) in
  let k = ref 1L in
  iter (fun v ->
    BIT.add (i32 v) 1L b;
    if BIT.sum_closed (i32 n) b = !k then (
      printf "1";
      k += 1L
    ) else (
      printf "0"
    )
  ) a; *)

open Printf
open Scanf

module Pset = Set.Make (struct type t = int*int let compare = compare end)

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 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_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in
  let a = Array.init m (fun _ -> read_int() -1) in (*difficulty reduced by 1 *)

  let hist = Array.make n 0 in

  let rec insert i s = if i=n then s else insert (i+1) (Pset.add (0,i) s) in

  let set = insert 0 Pset.empty in

  let rec loop j s prev_low_freq = if j=m then () else (
    let old = (hist.(a.(j)), a.(j)) in
    hist.(a.(j)) <- hist.(a.(j)) + 1;
    let new_elt = (hist.(a.(j)), a.(j)) in
    let s = Pset.remove old s in
    let s = Pset.add new_elt s in
    let (freq,_) = Pset.min_elt s in
    if freq > prev_low_freq then printf "1" else printf "0";
    loop (j+1) s freq
  ) in

  let () = loop 0 set 0 in
  print_newline()


You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operation on it as many times as you want:  Pick two integers $$$i$$$ and $$$j$$$ $$$(1 \le i,j \le n)$$$ such that $$$a_i+a_j$$$ is odd, then swap $$$a_i$$$ and $$$a_j$$$. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$.

The only line contains $$$n$$$ space-separated integers, the lexicographically smallest array you can obtain.

NoteIn the first example, we can swap $$$1$$$ and $$$4$$$ since $$$1+4=5$$$, which is odd.

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a = Array.init n
      (fun _ ->
         Scanf.scanf "%d " (fun x -> x))
  in
  let b = Array.map (fun x -> x mod 2 = 0) a in
  let pair, unpair =
    Array.fold_left
      (fun (acc1, acc2) x ->
         if x mod 2 = 0 then x::acc1, acc2
         else acc1, x:: acc2
      ) ([], []) a
  in
  match pair, unpair with
  | [], _ | _, [] ->
      Array.iter (fun x -> Printf.printf "%d " x) a
  | _ -> let a = Array.to_list a |> List.sort compare in
      List.iter (fun x -> Printf.printf "%d " x) a
;;


Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold:  Two segments have common endpoint (lets call these segments first and second), while the third segment connects two points on the different segments.  The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees.  The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4).

The first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.

Output one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.

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

open Int64

let det (x,y) (xx,yy) = sub (mul x yy) (mul y xx)
let dot (x,y) (xx,yy) = add (mul x xx) (mul y yy)
let (++) (x,y) (xx,yy) = add x xx, add y yy
let (--) (x,y) (xx,yy) = sub x xx, sub y yy
let ( ** ) d (x,y) = mul d x, mul d y

let () =
  let a = Array.make_matrix 3 2 (0L,0L) in
  for cc = 1 to read_int 0 do
    for i = 0 to 2 do
      for j = 0 to 1 do
        let x = read_int64 0 in
        let y = read_int64 0 in
        a.(i).(j) <- x,y
      done
    done;
    let swap i =
      let t = a.(i).(0) in
      a.(i).(0) <- a.(i).(1);
      a.(i).(1) <- t
    in
    let arm p q =
      let u = dot p q and v = dot q q in
      det p q = 0L && v <= mul 5L u && mul 5L u <= mul 4L v
    in
    let g (ma,mb) (la,lb) (ra,rb) =
      let lb = lb -- la in
      let rb = rb -- ra in
      la = ra && det lb rb <> 0L && dot lb rb >= 0L && arm (ma--la) lb && arm (mb--ra) rb
    in
    let f i j k =
      g (a.(i).(0),a.(i).(1)) (a.(j).(0),a.(j).(1)) (a.(k).(0),a.(k).(1))
    in
    let rec enum i =
      if i >= 8 then
        false
      else if f 0 1 2 || f 1 2 0 || f 2 0 1 then
        true
      else (
        if i land 1 <> 0 then
          swap 0
        else if i land 2 <> 0 then
          swap 1
        else
          swap 2;
        enum (i+1)
      )
    in
    print_endline (if enum 0 then "YES" else "NO")
  done

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

open Int64

let det (x,y) (xx,yy) = sub (mul x yy) (mul y xx)
let dot (x,y) (xx,yy) = add (mul x xx) (mul y yy)
let (++) (x,y) (xx,yy) = add x xx, add y yy
let (--) (x,y) (xx,yy) = sub x xx, sub y yy
let ( ** ) d (x,y) = mul d x, mul d y

let () =
  let a = Array.make_matrix 3 2 (0L,0L) in
  for cc = 1 to read_int 0 do
    for i = 0 to 2 do
      for j = 0 to 1 do
        let x = read_int64 0 in
        let y = read_int64 0 in
        a.(i).(j) <- x,y
      done
    done;
    let swap i =
      let t = a.(i).(0) in
      a.(i).(0) <- a.(i).(1);
      a.(i).(1) <- t
    in
    let h p q =
      let u = dot p q and v = dot q q in
      det p q = 0L && v <= mul 5L u && mul 5L u <= mul 4L v
    in
    let g (ma,mb) (la,lb) (ra,rb) =
      let lb = lb -- la in
      let rb = rb -- ra in
      la = ra && det lb rb <> 0L && dot lb rb >= 0L && h (ma--la) lb && h (mb--ra) rb
    in
    let f i j k =
      g (a.(i).(0),a.(i).(1)) (a.(j).(0),a.(j).(1)) (a.(k).(0),a.(k).(1))
    in
    let rec enum i =
      if i >= 6 then
        false
      else if f 0 1 2 || f 1 2 0 || f 2 0 1 then
        true
      else (
        if i land 1 <> 0 then
          swap 0
        else if i land 2 <> 0 then
          swap 1
        else
          swap 2;
        enum (i+1)
      )
    in
    print_endline (if enum 0 then "YES" else "NO")
  done


Vlad has $$$n$$$ friends, for each of whom he wants to buy one gift for the New Year.There are $$$m$$$ shops in the city, in each of which he can buy a gift for any of his friends. If the $$$j$$$-th friend ($$$1 \le j \le n$$$) receives a gift bought in the shop with the number $$$i$$$ ($$$1 \le i \le m$$$), then the friend receives $$$p_{ij}$$$ units of joy. The rectangular table $$$p_{ij}$$$ is given in the input.Vlad has time to visit at most $$$n-1$$$ shops (where $$$n$$$ is the number of friends). He chooses which shops he will visit and for which friends he will buy gifts in each of them.Let the $$$j$$$-th friend receive $$$a_j$$$ units of joy from Vlad's gift. Let's find the value $$$\alpha=\min\{a_1, a_2, \dots, a_n\}$$$. Vlad's goal is to buy gifts so that the value of $$$\alpha$$$ is as large as possible. In other words, Vlad wants to maximize the minimum of the joys of his friends.For example, let $$$m = 2$$$, $$$n = 2$$$. Let the joy from the gifts that we can buy in the first shop: $$$p_{11} = 1$$$, $$$p_{12}=2$$$, in the second shop: $$$p_{21} = 3$$$, $$$p_{22}=4$$$.Then it is enough for Vlad to go only to the second shop and buy a gift for the first friend, bringing joy $$$3$$$, and for the second — bringing joy $$$4$$$. In this case, the value $$$\alpha$$$ will be equal to $$$\min\{3, 4\} = 3$$$Help Vlad choose gifts for his friends so that the value of $$$\alpha$$$ is as high as possible. Please note that each friend must receive one gift. Vlad can visit at most $$$n-1$$$ shops (where $$$n$$$ is the number of friends). In the shop, he can buy any number of gifts.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. An empty line is written before each test case. Then there is a line containing integers $$$m$$$ and $$$n$$$ ($$$2 \le n$$$, $$$2 \le n \cdot m \le 10^5$$$) separated by a space — the number of shops and the number of friends, where $$$n \cdot m$$$ is the product of $$$n$$$ and $$$m$$$. Then $$$m$$$ lines follow, each containing $$$n$$$ numbers. The number in the $$$i$$$-th row of the $$$j$$$-th column $$$p_{ij}$$$ ($$$1 \le p_{ij} \le 10^9$$$) is the joy of the product intended for friend number $$$j$$$ in shop number $$$i$$$. It is guaranteed that the sum of the values $$$n \cdot m$$$ over all test cases in the test does not exceed $$$10^5$$$.

Print $$$t$$$ lines, each line must contain the answer to the corresponding test case — the maximum possible value of $$$\alpha$$$, where $$$\alpha$$$ is the minimum of the joys from a gift for all of Vlad's friends.

(* This problem was solved by alphacode here:
   https://codeforces.com/contest/1619/submission/144332384  *)

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 rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

open Printf
open Scanf

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 (m,n) = read_pair () in
    let p = Array.make_matrix m n 0 in
    let li = ref [] in
    for i=0 to m-1 do
      for j=0 to n-1 do
	let x = read_int() in
	p.(i).(j) <- x;
	li := x :: !li
      done
    done;

    let svals = Array.of_list (List.sort_uniq compare !li) in

    let viable a =
      let ok i j = if p.(i).(j) >= a then 1 else 0 in
      if forall 0 (n-1) (fun j -> exists 0 (m-1) (fun i -> ok i j > 0)) then (
      (* there's a 1 in every column *)
	exists 0 (m-1) (fun i -> (sum 0 (n-1) (fun j -> ok i j)) >= 2)
      ) else false
    in

    let rec bsearch lo hi =
      if lo = hi-1 then lo else
	(* lo is viable hi is not *)
	let mid = (lo+hi)/2 in
	if viable svals.(mid) then bsearch mid hi else bsearch lo mid
    in
    printf "%d\n" svals.(bsearch 0 (Array.length svals))
  done


We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — length of array $$$a$$$. The second line contains $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print:   YES if the such a partition exists,  NO otherwise.  The letters in the words YES and NO can be displayed in any case.

NoteThe first test case was explained in the statement.In the second test case, the two given numbers are not similar.In the third test case, any partition is suitable.

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

let rec loop n = function
  | [] -> false
  | x :: xs -> n + 1 = x || loop x xs

let () =
  for _ = 1 to t do
    let _ = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n in
    let a = read_line () |> split_string ~pattern:" " |> List.map int_of_string |> List.sort compare in
    let (ox, ex) = List.fold_left (fun (ox, ex) a -> if a mod 2 = 0 then (ox, a :: ex) else (a :: ox, ex)) ([], []) a in
    if List.length ox mod 2 <> List.length ex mod 2 then print_endline "NO"
    else if List.length ox mod 2 = 0 then print_endline "YES"
    else print_endline @@ if loop (List.hd a) (List.tl a) then "YES" else "NO"
  done


You are given an angle $$$\text{ang}$$$. The Jury asks You to find such regular $$$n$$$-gon (regular polygon with $$$n$$$ vertices) that it has three vertices $$$a$$$, $$$b$$$ and $$$c$$$ (they can be non-consecutive) with $$$\angle{abc} = \text{ang}$$$ or report that there is no such $$$n$$$-gon.  If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed $$$998244353$$$.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 180$$$) — the number of queries.  Each of the next $$$T$$$ lines contains one integer $$$\text{ang}$$$ ($$$1 \le \text{ang} < 180$$$) — the angle measured in degrees.

For each query print single integer $$$n$$$ ($$$3 \le n \le 998244353$$$) — minimal possible number of vertices in the regular $$$n$$$-gon or $$$-1$$$ if there is no such $$$n$$$.

NoteThe answer for the first query is on the picture above.The answer for the second query is reached on a regular $$$18$$$-gon. For example, $$$\angle{v_2 v_1 v_6} = 50^{\circ}$$$.The example angle for the third query is $$$\angle{v_{11} v_{10} v_{12}} = 2^{\circ}$$$.In the fourth query, minimal possible $$$n$$$ is $$$180$$$ (not $$$90$$$).

let rec fix f x = f (fix f) x
let gcd = fix (fun f m n ->
  if n=0 then m else f n (m mod n));;
Scanf.(Array.(
  let t = scanf " %d" @@ fun v -> v in
  init t (fun _ ->
    let d = scanf " %d" @@ fun v -> v in
    let g = gcd 180 (180-d) in
    let p,q = 180/g,(180-d)/g in
    Printf.printf "%d\n" @@
      if q=1 then p*2 else p)))

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

let () =
  let t = gi 0 in
  rep 1L t (fun _ ->
    let d = gi 0 in
    let g = gcd 180L (180L-d) in
    let p,q = 180L/g, (180L-d)/g in
    (* n=pi,k=qi *)
    let f = ref false in
    rep 1L 180L (fun i ->
      let n1,k1 = p*i,q*i in
      if not !f && k1 < n1 && k1 >= 2L then (
        f := true;
        (* printf "  %Ld; %Ld\n" n1 k1; *)
        printf "%Ld\n" n1;
      )
    )
  )

open Printf
open Scanf

let rec gcd a b = if a=0 then b else gcd (b mod a) a

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 ang = read_int () in
    let num = 2*ang in
    let den = 360 in
    let g = gcd num den in
    let (num,den) = (num/g, den/g) in
    let (num,den) = if num+1 = den then (2*num,2*den) else (num,den) in
    printf "%d\n" den
  done

let rec fix f x = f (fix f) x
let gcd = fix (fun f m n ->
  if n=0 then m else f n (m mod n));;
Scanf.(Array.(
  let t = scanf " %d" @@ fun v -> v in
  init t (fun _ ->
    let d = scanf " %d" @@ fun v -> v in
    let g = gcd 180 (180-d) in
    let p,q = 180/g,(180-d)/g in
    Printf.printf "%d\n" @@ p*2)))

let rec fix f x = f (fix f) x
let gcd = fix (fun f m n ->
  if n=0 then m else f n (m mod n));;
Scanf.(Array.(
  let t = scanf " %d" @@ fun v -> v in
  init t (fun _ ->
    let d = scanf " %d" @@ fun v -> v in
    let g = gcd 180 (180-d) in
    let p,q = 180/g,(180-d)/g in
    Printf.printf "%d\n" @@
      if q=1 then p else p*2
  )
))


You are given an array a1, a2, ..., an consisting of n integers, and an integer k. You have to split the array into exactly k non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the k obtained minimums. What is the maximum possible integer you can get?Definitions of subsegment and array splitting are given in notes.

The first line contains two integers n and k (1 ≤ k ≤ n ≤  105) — the size of the array a and the number of subsegments you have to split the array to. The second line contains n integers a1,  a2,  ...,  an ( - 109  ≤  ai ≤  109).

Print single integer — the maximum possible integer you can get if you split the array into k non-empty subsegments and take maximum of minimums on the subsegments.

NoteA subsegment [l,  r] (l ≤ r) of array a is the sequence al,  al + 1,  ...,  ar.Splitting of array a of n elements into k subsegments [l1, r1], [l2, r2], ..., [lk, rk] (l1 = 1, rk = n, li = ri - 1 + 1 for all i > 1) is k sequences (al1, ..., ar1), ..., (alk, ..., ark).In the first example you should split the array into subsegments [1, 4] and [5, 5] that results in sequences (1, 2, 3, 4) and (5). The minimums are min(1, 2, 3, 4) = 1 and min(5) = 5. The resulting maximum is max(1, 5) = 5. It is obvious that you can't reach greater result.In the second example the only option you have is to split the array into one subsegment [1, 5], that results in one sequence ( - 4,  - 5,  - 3,  - 2,  - 1). The only minimum is min( - 4,  - 5,  - 3,  - 2,  - 1) =  - 5. The resulting maximum is  - 5.

let main () =
  let getNumber () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
  in let n = getNumber ()
  in let m = getNumber ()
  in if m = 1 then
    let min = ref max_int
    in begin
      for i = 0 to n - 1 do
        let gn = getNumber ()
        in if gn < !min then
          min := gn
      done;
      Printf.printf "%d" !min
    end
  else if m >= 3 then
    let max = ref min_int
    in begin
      for i = 0 to n - 1 do
        let gn = getNumber ()
        in if gn > !max then
          max := gn
      done;
      Printf.printf "%d" !max
    end
  else
    let lmin = Array.make n max_int
    in let ar = Array.init n (fun x ->
        let gn = getNumber ()
        in begin
          if x = 0 || gn < lmin.(x - 1) then
            lmin.(x) <- gn
          else
            lmin.(x) <- lmin.(x - 1);
          gn
        end)
    in let rMinRef = ref ar.(n - 1)
    in let mx = ref ar.(n - 1)
    in begin
      for i = n - 2 downto 0 do
        if ar.(i) < !rMinRef then
          rMinRef := ar.(i);
        mx := max !mx (max lmin.(i) !rMinRef)
      done;
      Printf.printf "%d" !mx
    end

;;

main ();;

let main () =
  let getNumber () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
  in let n = getNumber ()
  in let m = getNumber ()
  in if m = 1 then
    let min = ref max_int
    in begin
      for i = 0 to n - 1 do
        let gn = getNumber ()
        in if gn < !min then
          min := gn
      done;
      Printf.printf "%d" !min
    end
  else
    let max = ref min_int
    in begin
      for i = 0 to n - 1 do
        let gn = getNumber ()
        in if gn > !max then
          max := gn
      done;
      Printf.printf "%d" !max
    end
;;

main ();;


Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started to put the chocolates on the cake. The value of Famil Door's happiness will be equal to the number of pairs of cells with chocolates that are in the same row or in the same column of the cake. Famil Doors's family is wondering what is the amount of happiness of Famil going to be?Please, note that any pair can be counted no more than once, as two different cells can't share both the same row and the same column.

In the first line of the input, you are given a single integer n (1 ≤ n ≤ 100) — the length of the side of the cake. Then follow n lines, each containing n characters. Empty cells are denoted with '.', while cells that contain chocolates are denoted by 'C'.

Print the value of Famil Door's happiness, i.e. the number of pairs of chocolate pieces that share the same row or the same column.

NoteIf we number rows from top to bottom and columns from left to right, then, pieces that share the same row in the first sample are:   (1, 2) and (1, 3)  (3, 1) and (3, 3)  Pieces that share the same column are:   (2, 1) and (3, 1)  (1, 3) and (3, 3)

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

  let rc = Array.make n 0 in
  let cc = Array.make n 0 in

  for i=0 to n-1 do
    for j=0 to n-1 do
      rc.(i) <- rc.(i) + (if c.(i).[j] = 'C' then 1 else 0)
    done;
  done;

  for j=0 to n-1 do
    for i=0 to n-1 do
      cc.(j) <- cc.(j) + (if c.(i).[j] = 'C' then 1 else 0)
    done;
  done;

  let rcount = sum 0 (n-1) (fun i -> (rc.(i) * (rc.(i) - 1)) /2) 0 in

  let ccount = sum 0 (n-1) (fun j -> (cc.(j) * (cc.(j) - 1)) /2) 0 in

  printf "%d\n" (rcount + ccount)