Given an array $$$a$$$ of $$$n$$$ elements, print any value that appears at least three times or print -1 if there is no such value.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print any value that appears at least three times or print -1 if there is no such value.

NoteIn the first test case there is just a single element, so it can't occur at least three times and the answer is -1.In the second test case, all three elements of the array are equal to $$$2$$$, so $$$2$$$ occurs three times, and so the answer is $$$2$$$.For the third test case, $$$2$$$ occurs four times, so the answer is $$$2$$$.For the fourth test case, $$$4$$$ occurs three times, so the answer is $$$4$$$.For the fifth test case, $$$1$$$, $$$2$$$ and $$$3$$$ all occur at least three times, so they are all valid outputs.For the sixth test case, all elements are distinct, so none of them occurs at least three times and the answer is -1.

let testcases_str = read_line ()
let testcases = int_of_string testcases_str

let rec split str len n acc =
  if n = len then [ int_of_string acc ]
  else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) ""
  else split str len (n + 1) (acc ^ String.make 1 str.[n])

let solve () =
  let len = read_line () in
  let nums_string = read_line () in
  let counter_arr = Array.make ((int_of_string len) + 1) 0 in
  let splitted = split nums_string (String.length nums_string) 0 "" in
  let rec loop lst counter =
    match lst with
    | [] -> print_string "-1\n"
    | h :: t ->
        counter.(h) <- counter.(h) + 1;
        if counter.(h) >= 3 then print_string (string_of_int h ^ "\n")
        else loop t counter
  in
  loop splitted counter_arr
;;

for i = 0 to testcases - 1 do
  solve ()
done

(* print any value that appears atleast three times or print -1
   1<=ai<=n, so can have a count array size n? Or sort and see if adjacent next to each other?
    comparsion sort is atleast O(nlgn)
    counting is atmost O(n)
*)

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

let rec fill_count_arr = function
| (count_arr, 0) -> count_arr
| (count_arr, i) ->
  let x = read_int () in
  count_arr.(x-1) <- (count_arr.(x-1)+1);
  fill_count_arr (count_arr, (i-1))
;;

let rec consume_count_arr = function
| (n, count_arr, k, i) ->
  if (i=n) then -1
  else begin
    if (count_arr.(i)>=k) then i+1
    else consume_count_arr (n, count_arr, k, (i+1))
  end
;;
let run_case = function
| () ->
  let n = read_int () in
  let count_arr = Array.make n 0 in
  let filled_arr = fill_count_arr (count_arr, n) in
  let x = consume_count_arr (n, filled_arr, 3, 0) in
  Printf.printf "%d\n" x
;;

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

let getInt () = Scanf.scanf " %d" (fun i -> i);;

let getList(n): int list =
  let rec getList2 ((n: int), (acc: int list)) = match n with
	  | 0 -> List.rev acc
	  | _ -> getList2 (n-1, getInt() :: acc)
  in getList2(n, [])

let getLine() = Scanf.scanf " %s" (fun i -> i);;

let cmp((x: int), (y:int)) = x - y;;

let rec solve((arr: int list), (last: int), (ct: int)) =
match arr with
  | [] -> -1
  | x::xs ->
    if x = last then (
      if (ct + 1) = 3 then x else solve(xs, last, ct + 1))
    else solve(xs, x, 1);;

let main() =
  let t = getInt() in
  for i = 1 to t do
    let n = getInt() in let x = getList(n) in let arr = List.sort (compare) x
  in let ans = solve(arr, -1, 0) in
  print_endline(string_of_int(ans))
  done;;

main();;

let id x = x

module S = struct
  open String

  let split_on_char sep s =
    let r = ref [] in
    let j = ref (String.length s) in
    for i = length s - 1 downto 0 do
      if unsafe_get s i = sep then begin
        r := sub s (i + 1) (!j - i - 1) :: !r;
        j := i
      end
    done;
    sub s 0 !j :: !r
end

let read_ints_line () =
  Scanf.scanf "%s@\n" (fun x -> x)
  |> S.split_on_char ' '
  |> List.filter (fun x -> x <> "")
  |> List.map int_of_string

let solve () =
  let n = Scanf.scanf "%d\n" id in
  let xs = read_ints_line () in
  let counts = Array.make (n + 1) 0 in
  let () = List.iter (fun a -> counts.(a) <- counts.(a) + 1) xs in
  let counts = Array.mapi (fun i c -> (i, c)) counts |> Array.to_list in
  let counts = List.filter (fun (i, c) -> c >= 3) counts in
  match counts with
  | [] -> print_endline "-1"
  | (i, _) :: _ -> Printf.printf "%d\n" i

let () =
  let t = Scanf.scanf "%d\n" id in
  for i = 1 to t do
    solve ()
  done


Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.

The single line contains four integers a1, a2, a3 and a4 (1 ≤ a1, a2, a3, a4 ≤ 106).

On the single line print without leading zeroes the answer to the problem — the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).

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

let expand s a1 a2 = (* a1, a2 are the number of additional 4s and 7s we need to add *)
  let n = String.length s in
    if a1<0 || a2<0 then None else
      let m = n+a1+a2 in
      let t = String.make m 'x' in
      let rec find_last7  i = if i<0 then -1 else if s.[i]='7' then i else find_last7  (i-1) in
      let rec find_first4 i = if i=n then -1 else if s.[i]='4' then i else find_first4 (i+1) in
      let l7 = find_last7 (n-1) in
      let f4 = find_first4 0 in
	if f4<0 && a1>0 then None
	else if l7<0 && a2>0 then None
	else
	  let rec fill i p j k = (* i=pos in s, j=4s left, k=7s left *)
	    if p=m then () else (
	      t.[p] <- s.[i];
	      if i=f4 && j>0 then fill i (p+1) (j-1) k
	      else if i=l7 && k>0 then fill i (p+1) j (k-1)
	      else fill (i+1) (p+1) j k
	    )
	  in
	    fill 0 0 a1 a2;
	    Some t

let alter n a b =
  let t = String.make n 'x' in
    for i=0 to n-1 do
      t.[i] <- if i mod 2 = 0 then a else b
    done;
    t

let () =
  let a1 = read_int() in
  let a2 = read_int() in
  let a3 = read_int() in
  let a4 = read_int() in
  let answer =
    match a3-a4 with
      | 0 ->   (* 4747...4 or 7474...7 *)
	  let op1 = expand (alter (2*a3+1) '4' '7') (a1-a3-1) (a2-a3) in
	  let op2 = expand (alter (2*a3+1) '7' '4') (a1-a3) (a2-a3-1) in
	    begin
	      match (op1,op2) with
		| (None,None) -> None
		| (None,x) | (x,None) -> x
		| _ -> min op1 op2
	    end
      | 1 ->   (* 4747...47 *)
	  expand (alter (2*a3) '4' '7') (a1-a3) (a2-a3)
      | -1 ->  (* 7474...74 *)
	  expand (alter (2*a4) '7' '4') (a1-a4) (a2-a4)
      | _ ->
	  None
  in
    match answer with None -> Printf.printf "-1\n" | Some a -> Printf.printf "%s\n" a


Imagine that your city is an infinite 2D plane with Cartesian coordinate system. The only crime-affected road of your city is the x-axis. Currently, there are n criminals along the road. No police station has been built on this road yet, so the mayor wants to build one.As you are going to be in charge of this new police station, the mayor has asked you to choose a suitable position (some integer point) for building it. You should choose the best position for the police station, so that you could minimize the total time of your criminal catching mission. Your mission of catching the criminals will operate only from this station. The new station will have only one patrol car. You will go to the criminals by this car, carry them on the car, bring them back to the police station and put them in prison. The patrol car can carry at most m criminals at a time. Note that, the criminals don't know about your mission. So, they will stay where they are instead of running away.Your task is to find the position for the police station, so that total distance you need to cover to catch all the criminals will be minimum possible. Note that, you also can built the police station on the positions where one or more criminals already exist. In such a case all these criminals are arrested instantly.

The first line of the input will have two integers n (1 ≤ n ≤ 106) and m (1 ≤ m ≤ 106) separated by spaces. The next line will contain n integers separated by spaces. The ith integer is the position of the ith criminal on the x-axis. Absolute value of positions will not exceed 109. If a criminal has position x, he/she is located in the point (x, 0) of the plane.  The positions of the criminals will be given in non-decreasing order. Note, that there can be more than one criminal standing at some point of the plane. Note: since the size of the input/output could be very large, don't use slow input/output techniques in your language. For example, do not use input/output streams (cin, cout) in C++.

Print a single integer, that means the minimum possible distance you need to cover to catch all the criminals.

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)

open Printf
open Scanf
open Array
;;

(* misc *)
let neg_compare x y = - compare x y
(* Array *)
let range a b = if b < a then [||] else Array.init (b-a+1) (fun x -> a+x)
let rec span i up_bnd cond =
  if i = up_bnd || cond i then i else
  span (i+1) up_bnd cond
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let rec repeat n f = if n <= 0 then () else (f (); repeat (n-1) f)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
let is_digit c =
  let i = int_of_char c in
  let lo = int_of_char '0' in
  let up = int_of_char '9' in
  lo <= i && i <= up
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let option x = function
  | Some y -> y
  | None   -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
(* Arithmetic *)
let negate x = -x
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
(* IO *)
let peek_char () = scanf "%0c" id
let read_char () = scanf "%c" id
let read_line () = scanf "%s@\n" id
let read_int () = scanf " %d" id
let read_int64 () = scanf " %Ld" id
let read_float () = scanf " %f" id
let read_word () = scanf " %s" id
let is_eof () = try scanf "%0c" (const false) with End_of_file -> true
let clear_newline () = scanf "%[\n]" (const ())
let newline () = print_newline()
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  let n = read_int() in
  let m = read_int() in
  let arr = init n (fun i -> read_int64()) in
  fast_sort compare arr;

  let open Int64 in

  let rec run i j =
    if j <= i then 0L else
    add (mul 2L (sub arr.(j) arr.(i)))  (run (i+m) (j-m))
  in
  printf "%Ld\n" (run 0 (n-1))

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)

open Printf
open Scanf
open Array
;;

(* misc *)
let neg_compare x y = - compare x y
(* Array *)
let range a b = if b < a then [||] else Array.init (b-a+1) (fun x -> a+x)
let rec span i up_bnd cond =
  if i = up_bnd || cond i then i else
  span (i+1) up_bnd cond
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let rec repeat n f = if n <= 0 then () else (f (); repeat (n-1) f)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
let is_digit c =
  let i = int_of_char c in
  let lo = int_of_char '0' in
  let up = int_of_char '9' in
  lo <= i && i <= up
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let option x = function
  | Some y -> y
  | None   -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
(* Arithmetic *)
let negate x = -x
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
(* IO *)
let peek_char () = scanf "%0c" id
let read_char () = scanf "%c" id
let read_line () = scanf "%s@\n" id
let read_int () = scanf " %d" id
let read_float () = scanf " %f" id
let read_word () = scanf " %s" id
let is_eof () = try scanf "%0c" (const false) with End_of_file -> true
let clear_newline () = scanf "%[\n]" (const ())
let newline () = print_newline()
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  let n = read_int() in
  let m = read_int() in
  let arr = init n (fun i -> read_int()) in
  fast_sort compare arr;

  let rec run i j =
    if j <= i then 0 else(
    2*(arr.(j) - arr.(i)) + run (i+m) (j-m) )
  in
  printf "%d\n" (run 0 (n-1))

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)
Gc.set {Gc.get() with
  Gc.minor_heap_size=512*1024;
  Gc.major_heap_increment=1024*1024;
  Gc.stack_limit=8*1024*1024;
}

open Printf
open Scanf
open Array

module S = String
module Q = Queue
module T = Stack
module L = List

module Integer = struct
  let (+) a b = Big_int.add_big_int a b
  let (-) a b = Big_int.sub_big_int a b
  let ( * ) a b = Big_int.mult_big_int a b
  let sqrt a = Big_int.sqrt_big_int a
  let divmod a b = Big_int.quomod_big_int a b
  let div a b = Big_int.div_big_int a b
  let (mod) a b = Big_int.mod_big_int a b
  let gcd a b = Big_int.gcd_big_int a b
  let pow a b = Big_int.power_big_int_positive_big_int a b
  let zero = Big_int.zero_big_int
  let one = Big_int.unit_big_int
  let to_string a = Big_int.string_of_big_int a
  let to_float a = Big_int.float_of_big_int a
  let of_string a = Big_int.big_int_of_string a
  let of_int a = Big_int.big_int_of_int a
  let compare a b = Big_int.compare_big_int a b
  let (=) a b = Big_int.eq_big_int a b
  let (>) a b = Big_int.gt_big_int a b
  let (<) a b = Big_int.lt_big_int a b
  let (>=) a b = Big_int.ge_big_int a b
  let (<=) a b = Big_int.le_big_int a b
  let max a b = Big_int.max_big_int a b
  let min a b = Big_int.min_big_int a b
  let (land) a b = Big_int.and_big_int a b
  let (lor) a b = Big_int.or_big_int a b
end

(* misc *)
let neg_compare x y = - compare x y
let min3 a b c = min a (min b c)
let mid3 a b c = if a < b then max a (min b c) else max b (min a c)
let max3 a b c = max a (max b c)
let min4 a b c d = min (min a b) (min c d)
let max4 a b c d = max (max a b) (max c d)
let bti b = if b then 1 else 0
(* float *)
let round f = truncate (f +. 0.5)
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let (@@) a b = a b
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
let rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let option x = function Some y -> y | None -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
let swap arr i j =
  let t = arr.(i) in
  arr.(i) <- arr.(j);
  arr.(j) <- t
(* Arithmetic *)
let negate x = -x
let (+:) (a,b) (c,d) = (a+c,b+d)
let (-:) (a,b) (c,d) = (a-c,b-d)
let rec factorial n = if n = 0 then 1 else n * factorial (n-1)
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
let rec modpow m x n =
  if n = 0 then 1 else
  let n' = n/2 in
  let p = modpow m x n' in
  if is_even n then (p*p mod m) else
  (x*(p*p mod m) mod m)
(* IO *)
let is_digit c =
  let i = int_of_char c in
  48 <= i && i < 58
let is_space c = c = ' ' || c = '\n' || c = '\t' || c = '\r'
let read_char () = try input_char stdin with End_of_file -> '\000'
let rec read_letter () =
  let c = read_char() in
  if is_space c then read_letter() else c
let read_int () =
  let digit c = int_of_char c - 48 in
  let rec read n =
    let c = read_char() in
    if is_digit c then read (10*n + (digit c)) else
    n
  in
  let rec run c =
    if is_digit c then read (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -read (digit c) else run c
    end else
    if c = '\000' then 0 else
    run (read_char())
  in
  run (read_char())
let read_float () =
  let digit c = float (int_of_char c - 48) in
  let rec read_decimial m f =
    let c = read_char () in
    if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f
  in
  let rec read_integral n =
    let c = read_char () in
    if is_digit c then read_integral (10. *. n +. digit c) else
    if c = '.' then n +. read_decimial 0.1 0.0 else
    n
  in
  let rec run c = begin
    if is_digit c then read_integral (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -. read_integral (digit c) else
      run c
    end else
    if c = '.' then read_decimial 0.1 0.0 else
    if c = '\000' then 0.0 else
    run (read_char())
  end in
  run (read_char())
let read_word () =
  let open Buffer in
  let buf = create 1_000_000 in
  let rec read c =
    if is_space c || c = '\000' then contents buf else begin
      add_char buf c;
      read (read_char())
    end
  in
  let rec run c =
    if is_space c then run (read_char()) else
    if c = '\000' then "" else
    read c
  in
  run (read_char())
let read_line () =
  let open Buffer in
  let buf = create 1_000_000 in
  let rec run c =
    if c = '\n' || c = '\000' then contents buf else begin
      add_char buf c;
      run (read_char())
    end
  in
  run (read_char())
let newline () = print_newline()
let print_tuple s (x,y) = printf s x y
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  printf "%d\n" (factorial 15)


You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.For each vertex v find the sum of all dominating colours in the subtree of vertex v.

The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree. The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex. Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.

Print n integers — the sums of dominating colours for each vertex.

let (+|) = Int64.add
let (-|) = Int64.sub
let ( *| ) = Int64.mul
let ( /| ) = Int64.div

module IntMap = Map.Make(
  struct
    type t = int
    let compare (x : int) y =
      if x < y
      then -1
      else if x > y
      then 1
      else 0
  end
)

type counter =
    {map : int IntMap.t;
     v : int;
     s : int64;
     size : int;
    }

let new_counter () =
  {map = IntMap.empty;
   v = -1;
   s = 0L;
   size = 0;
  }

let add counter x d =
  let (y, ds) =
    try
      (IntMap.find x counter.map, 0)
    with
      | Not_found -> (0, 1)
  in
  let y = y + d in
  let map = IntMap.add x y counter.map in
    if counter.v < y
    then {map;
	  v = y;
	  s = Int64.of_int x;
	  size = counter.size + ds}
    else if counter.v = y
    then {counter with
	    map;
	    s = counter.s +| Int64.of_int x;
	    size = counter.size + ds}
    else {counter with
	    map;
	    size = counter.size + ds}

let rec merge c1 c2 =
  if c1.size > c2.size
  then merge c2 c1
  else (
    IntMap.fold
      (fun x y c2 ->
	 add c2 x y
      ) c1.map c2
  )

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n (new_counter ()) in
  let c = Array.make n 0 in
  let es = Array.make n [] in
    for i = 0 to n - 1 do
      c.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    for i = 1 to n - 1 do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(u) <- v :: es.(u);
	es.(v) <- u :: es.(v);
    done;
    let es = Array.map Array.of_list es in
    let rec dfs u prev =
      let cnt = ref (new_counter ()) in
	cnt := add !cnt c.(u) 1;
	for i = 0 to Array.length es.(u) - 1 do
	  let v = es.(u).(i) in
	    if v <> prev then (
	      dfs v u;
	      cnt := merge !cnt a.(v);
	    )
	done;
	a.(u) <- !cnt;
    in
      dfs 0 (-1);
      for i = 0 to n - 1 do
	Printf.printf "%Ld " a.(i).s;
      done;
      Printf.printf "\n"

module IntMap = Map.Make(
  struct
    type t = int
    let compare (x : int) y =
      if x < y
      then -1
      else if x > y
      then 1
      else 0
  end
)

type counter =
    {map : int IntMap.t;
     v : int;
     s : int;
     size : int;
    }

let new_counter () =
  {map = IntMap.empty;
   v = -1;
   s = 0;
   size = 0;
  }

let add counter x d =
  let (y, ds) =
    try
      (IntMap.find x counter.map, 0)
    with
      | Not_found -> (0, 1)
  in
  let y = y + d in
  let map = IntMap.add x y counter.map in
    if counter.v < y
    then {map;
	  v = y;
	  s = x;
	  size = counter.size + ds}
    else if counter.v = y
    then {counter with
	    map;
	    s = counter.s + x;
	    size = counter.size + ds}
    else {counter with
	    map;
	    size = counter.size + ds}

let rec merge c1 c2 =
  if c1.size > c2.size
  then merge c2 c1
  else (
    IntMap.fold
      (fun x y c2 ->
	 add c2 x y
      ) c1.map c2
  )

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n (new_counter ()) in
  let c = Array.make n 0 in
  let es = Array.make n [] in
    for i = 0 to n - 1 do
      c.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    for i = 1 to n - 1 do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(u) <- v :: es.(u);
	es.(v) <- u :: es.(v);
    done;
    let es = Array.map Array.of_list es in
    let rec dfs u prev =
      let cnt = ref (new_counter ()) in
	cnt := add !cnt c.(u) 1;
	for i = 0 to Array.length es.(u) - 1 do
	  let v = es.(u).(i) in
	    if v <> prev then (
	      dfs v u;
	      cnt := merge !cnt a.(v);
	    )
	done;
	a.(u) <- !cnt;
    in
      dfs 0 (-1);
      for i = 0 to n - 1 do
	Printf.printf "%d " a.(i).s;
      done;
      Printf.printf "\n"


During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.Each participant is identified by some unique positive integer k, and each sent solution A is characterized by two numbers: x — the number of different solutions that are sent before the first solution identical to A, and k — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same x.It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number x (x > 0) of the participant with number k, then the testing system has a solution with number x - 1 of the same participant stored somewhere before.During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the number of solutions. Each of the following n lines contains two integers separated by space x and k (0 ≤ x ≤ 105; 1 ≤ k ≤ 105) — the number of previous unique solutions and the identifier of the participant.

A single line of the output should contain «YES» if the data is in chronological order, and «NO» otherwise.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make 100001 (-1);;
let b=ref true;;
for i=1 to n do
   let x=read_int() and k=read_int() in
   begin
   if x>tab.(k)+1 then b:=false;
   if x=tab.(k)+1 then tab.(k)<-x
   end
done;;
if !b then print_string "YES" else print_string "NO";;


Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 × 2 square consisting of black pixels is formed. Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 × 2 square consisting of black pixels is formed.

The first line of the input contains three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 105) — the number of rows, the number of columns and the number of moves that Pasha is going to perform.  The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 ≤ i ≤ n, 1 ≤ j ≤ m), representing the row number and column number of the pixel that was painted during a move.

If Pasha loses, print the number of the move when the 2 × 2 square consisting of black pixels is formed. If Pasha doesn't lose, that is, no 2 × 2 square consisting of black pixels is formed during the given k moves, print 0.

let carre a b mat =
	(mat.(a).(b)) && (mat.(a-1).(b)) && (mat.(a).(b-1)) && (mat.(a-1).(b-1));;

let rec f mat = function
	|[]		-> -100000
	|(a,b)::q 	-> begin
				mat.(a).(b) <- true;
				if (carre a b mat) || (carre (a+1) b mat) || (carre a (b+1) mat) || (carre (a+1) (b+1) mat)
					then 1
					else 1 + f mat q
				end;;

let final () =
	let (n,m,k) = Scanf.scanf "%d %d %d " (fun i j k -> (i,j,k)) and l = ref [] in
		for i=1 to k do
			l := (Scanf.scanf "%d %d " (fun i j -> (i,j)))::!l;
		done;
	let mat = Array.make_matrix (n+2) (m+2) false in
	let a = f mat (List.rev !l) in
		if a < 0
			then Printf.printf "0"
			else Printf.printf "%d" a;;

final ();;

(* square colours *)
type col = White | Black

let (++) (x, y) (z, w) = (x + z, y + w)

let get a (x, y) =
  try a.(x).(y)
  with Invalid_argument _ -> White

let deltas = [
  [(-1, -1); (0, -1); (-1, 0)]; (* north-west *)
  [( 1, -1); (0, -1); ( 1, 0)]; (* north-east *)
  [(-1,  1); (0,  1); (-1, 0)]; (* south-west *)
  [( 1,  1); (0,  1); ( 1, 0)]; (* south-east *)
]

let () =
  Scanf.scanf "%d %d %d\n" (fun n m k ->
    let board = Array.make_matrix n m White in
    let get = get board in

    let check_square p = List.fold_left (fun b d ->
      b || (List.fold_left (fun i d ->
        i + match get (d ++ p) with | White -> 0 | Black -> 1) 0 d) = 3)
      false deltas
    in

    let rec loop i =
      if i > k then 0
      else begin
        let x, y = Scanf.scanf "%d %d\n" (fun x y -> (x-1, y-1)) in
        board.(x).(y) <- Black;
        if check_square (x, y) then i else loop (i + 1)
      end
    in
    Printf.printf "%d\n" (loop 1)
  )


Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves — from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j — Place a book at position j at shelf i if there is no book at it. 2 i j — Remove the book from position j at shelf i if there is a book at it. 3 i — Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k — Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 103, 1 ≤ q ≤ 105) — the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order — i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0.

For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order.

NoteThis image illustrates the second sample case.

type segtree =
  | Leaf of bool
  | Node of segtree * segtree * bool * int * int

let size tree = match tree with
  | Leaf _ -> 1
  | Node(_, _, _, size, _) -> size

let count tree = match tree with
  | Leaf b -> if b then 1 else 0
  | Node(_, _, inv, size, count) ->
      if inv then
        size - count
      else
        count

let create left right inv =
  Node(left, right, inv, size left + size right, count left + count right)

let invert_one tree = match tree with
  | Leaf b -> Leaf(not b)
  | Node(left, right, inv, _, _) -> create left right (not inv)

let push tree = match tree with
  | Leaf _ -> tree
  | Node(left, right, inv, _, _) ->
      if inv then
        create (invert_one left) (invert_one right) false
      else
        tree

let rec update tree i value = match tree with
  | Leaf _ -> Leaf value
  | Node _ ->
      match push tree with
      | Leaf _ -> exit 1
      | Node(left, right, _, _, _) ->
          if i < size left then
            create (update left i value) right false
          else
            create left (update right (i - size left) value) false

let rec invert tree l r = match tree with
  | Leaf _ -> invert_one tree
  | Node(_, _, inv, sz, _) ->
      if l == 0 && r == sz then
        invert_one tree
      else match push tree with
        | Leaf _ -> exit 1
        | Node(left, right, _, _, _) ->
            let mid = size left in
            let new_left = if l >= mid then left else invert left l (min mid r)
            and new_right = if r <= mid then right else invert right (max (l - mid) 0) (r - mid) in
            create new_left new_right false

let rec construct n =
  if n == 1 then
    Leaf false
  else
    let half = n lsr 1 in
    create (construct half) (construct(n - half)) false

let () =
  Scanf.bscanf Scanf.Scanning.stdin " %d %d %d" (fun n m q ->
    let roots = Array.make (q + 1) (construct(n * m)) in
    for i = 1 to q do
      Scanf.bscanf Scanf.Scanning.stdin " %c %d" (fun c a ->
        match c with
          | '1' | '2' ->
              Scanf.bscanf Scanf.Scanning.stdin " %d" (fun b ->
                roots.(i) <- update roots.(i - 1) ((a - 1) * m + b - 1) (c == '1')
              )
          | '3' -> roots.(i) <- invert roots.(i - 1) ((a - 1) * m) (a * m)
          | '4' -> roots.(i) <- roots.(a)
          | _ -> exit 1
      );
      print_int(count roots.(i));
      print_string "\n"
    done
  )


You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled:   All pixels in each column are of the same color.  The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y.

The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#".

In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists.

NoteIn the first test sample the picture after changing some colors can looks as follows:  .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows:  .#.#..#.#.

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

let () =
    let n = read_int () and m = read_int () and x = read_int () and y = read_int () in
    let a = Array.make_matrix (n + 1) (m + 1) ' '
    and cnt = Array.make_matrix (m + 1) 2 0
    and best = Array.make_matrix (m + 1) 2 1000000
    and dp = Array.init (m + 1) (fun _ -> Array.init 2 (fun _ -> Array.make (y + 1) 1000000)) in
    best.(0).(0) <- 0;
    best.(0).(1) <- 0;
    let interval a b color =
        cnt.(b).(color) - cnt.(a - 1).(color) in
    for i = 1 to n do
        for j = 1 to m do
            a.(i).(j) <- read_char ()
        done
    done;
    for i = 1 to m do
        let white = ref 0 and black = ref 0 in
        for j = 1 to n do
            if a.(j).(i) = '.' then incr white
            else incr black
        done;
        cnt.(i).(0) <- cnt.(i - 1).(0) + !white;
        cnt.(i).(1) <- cnt.(i - 1).(1) + !black
    done;
    for i = 1 to m do
        for color = 0 to 1 do
            let other_color = (color + 1) mod 2 in
            for length = x to min y i do
                dp.(i).(color).(length) <- best.(i - length).(other_color) + (interval (i - length + 1) i other_color);
                best.(i).(color) <- min best.(i).(color) dp.(i).(color).(length)
            done
        done
    done;
    printf "%d\n" (min best.(m).(0) best.(m).(1))

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

let n = scan_int() and m = scan_int() and x = scan_int() and y = scan_int();;
let cnt = Array.make (m + 1) 0;; (*liczba zer w i-tej kolumnie*)

for i = 0 to n - 1 do
  let s = scan_string () in
  for j = 0 to m - 1 do
    cnt.(j + 1) <- cnt.(j + 1) + b2i(s.[j] = '.');
  done;
done;;

let duzo = 998244353;;

let dp = Array.make_matrix (m + 1) 2 duzo;;
dp.(0).(0) <- 0;; dp.(0).(1) <- 0;; (* warunki poczatkowe *)

let zer = ref 0 and jed = ref 0;;
for i = 1 to x do
  zer := !zer + (n - cnt.(i));
  jed := !jed + cnt.(i);
done;;

for i = x to m do
  let pZer = ref !zer and pJed = ref !jed in
  for j = i - x + 1 downto max 1 (i - y + 1) do
    dp.(i).(0) <- min (dp.(i).(0)) (dp.(j - 1).(1) + !pZer);
    dp.(i).(1) <- min (dp.(i).(1)) (dp.(j - 1).(0) + !pJed);
    pZer := !pZer + (n - cnt.(j - 1));
    pJed := !pJed + cnt.(j - 1);
  done;
  if i <> m then begin
    zer := !zer + (n - cnt.(i + 1)) - (n - cnt.(i - x + 1));
    jed := !jed + cnt.(i + 1) - cnt.(i - x + 1);
  end;
done;;

print_int (min dp.(m).(0) dp.(m).(1));;

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

let n = scan_int() and m = scan_int() and x = scan_int() and y = scan_int();;
let cnt = Array.make (m + 1) 0;; (*liczba zer w i-tej kolumnie*)

for i = 0 to n - 1 do
  let s = scan_string () in
  for j = 0 to m - 1 do
    cnt.(j + 1) <- cnt.(j + 1) + b2i(s.[j] = '.');
  done;
done;;

let duzo = 998244353;;

let dp = Array.make_matrix (m + 1) 2 duzo;;
dp.(0).(0) <- 0;; dp.(0).(1) <- 0;; (* warunki poczatkowe *)

let zer = ref 0 and jed = ref 0;;
for i = 1 to x - 1 do
  zer := !zer + (n - cnt.(i));
  jed := !jed + cnt.(i);
done;;

for i = x to m do
  let pZer = ref !zer and pJed = ref !jed in
  for j = i - x + 1 downto max 1 (i - y + 1) do
    pZer := !pZer + (n - cnt.(j));
    pJed := !pJed + cnt.(j);
    dp.(i).(0) <- min (dp.(i).(0)) (dp.(j - 1).(1) + !pZer);
    dp.(i).(1) <- min (dp.(i).(1)) (dp.(j - 1).(0) + !pJed);
  done;
  if i <> m then begin
    zer := !zer + (n - cnt.(i)) - (n - cnt.(i - x + 1));
    jed := !jed + cnt.(i) - cnt.(i - x + 1);
  end;
done;;

print_int (min dp.(m).(0) dp.(m).(1));;


Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it.

The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding.

NoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.

let () =
  Scanf.scanf "%d %s" @@ fun n s ->
  let b = Bytes.create n in
  for i = 0 to n / 2 - 1 do
    Bytes.set b i s.[n - 2 * i - 2]
  done;
  for i = n - 1 downto n / 2 do
    Bytes.set b i s.[2 * i - n + 1]
  done;
  Printf.printf "%s\n" b

let decode (s : string) : string =
  let n = String.length s in
  let bs = Bytes.create n in
    begin
      if n mod 2 = 0
      then
        for i = 0 to n/2-1 do
          Bytes.set bs (n/2-1 - i) s.[2*i];
          Bytes.set bs (n/2 + i) s.[2*i+1]
        done
      else begin
        for i = 0 to (n-3)/2 do
          Bytes.set bs ((n-1)/2 + i) s.[2*i];
          Bytes.set bs ((n-3)/2 - i) s.[2*i+1]
        done;
        Bytes.set bs (n-1) s.[n-1]
      end
    end;
    Bytes.unsafe_to_string bs

let main () =
  let n = read_int () in
  let encoded_str = really_input_string stdin n in
    print_string (decode encoded_str)

let _ = main ()


Not to be confused with chessboard.

The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and its type. The name is a string of lowercase English letters between 1 and 10 characters long. The type is either "soft" or "hard. All cheese names are distinct.

9
brie soft
camembert soft
feta soft
goat soft
muenster soft
asiago hard
cheddar hard
gouda hard
swiss hard

6
parmesan hard
emmental hard
edam hard
colby hard
gruyere hard
asiago hard

open String

let split_on_char sep s =
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if unsafe_get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
sub s 0 !j :: !r

let soft = ref 0

let hard = ref 0

let level b cheese i =
  let shift = if b then 1 else 0 in
  cheese  <= (i * i + shift) / 2

let _ =
  let n = read_int () in
  for i = 0 to n - 1 do
    let s = read_line () in
    let l = split_on_char ' ' s in
    if List.nth l 1 = "soft" then
      incr soft
    else
      incr hard
  done;
  let a,b = if !soft < !hard then !soft, !hard else !hard, !soft in
  for i = 0 to 100 do
    if level true b i && level false a i then
      begin
        Format.printf "%d@." i;
        exit 0
      end
  done;

open String

let split_on_char sep s =
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if unsafe_get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
sub s 0 !j :: !r

let soft = ref 0

let hard = ref 0

let level b cheese i =
  let shift = if b then 1 else 0 in
  cheese * 2 + shift <= i * i

let _ =
  let n = read_int () in
  for i = 0 to n - 1 do
    let s = read_line () in
    let l = split_on_char ' ' s in
    if List.nth l 1 = "soft " then
      incr soft
    else
      incr hard
  done;
  let a,b = if !soft < !hard then !soft, !hard else !hard, !soft in
  for i = 0 to 100 do
    if level true b i && level false a i then
      begin
        Format.printf "%d@." i;
        exit 0
      end
  done;

open String

let split_on_char sep s =
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if unsafe_get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
sub s 0 !j :: !r

let soft = ref 0

let hard = ref 0

let level b cheese i =
  let shift = if b then 1 else 0 in
  cheese  <= (i * i + shift) / 2

let _ =
  let n = read_int () in
  for i = 0 to n - 1 do
    let s = read_line () in
    let l = split_on_char ' ' s in
    if List.nth l 1 = "soft " then
      incr soft
    else
      incr hard
  done;
  let a,b = if !soft < !hard then !soft, !hard else !hard, !soft in
  for i = 0 to 100 do
    if level true b i && level false a i then
      begin
        Format.printf "%d@." i;
        exit 0
      end
  done;


There are $$$n$$$ points on a coordinate axis $$$OX$$$. The $$$i$$$-th point is located at the integer point $$$x_i$$$ and has a speed $$$v_i$$$. It is guaranteed that no two points occupy the same coordinate. All $$$n$$$ points move with the constant speed, the coordinate of the $$$i$$$-th point at the moment $$$t$$$ ($$$t$$$ can be non-integer) is calculated as $$$x_i + t \cdot v_i$$$.Consider two points $$$i$$$ and $$$j$$$. Let $$$d(i, j)$$$ be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points $$$i$$$ and $$$j$$$ coincide at some moment, the value $$$d(i, j)$$$ will be $$$0$$$.Your task is to calculate the value $$$\sum\limits_{1 \le i < j \le n}$$$ $$$d(i, j)$$$ (the sum of minimum distances over all pairs of points).

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of points. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^8$$$), where $$$x_i$$$ is the initial coordinate of the $$$i$$$-th point. It is guaranteed that all $$$x_i$$$ are distinct. The third line of the input contains $$$n$$$ integers $$$v_1, v_2, \dots, v_n$$$ ($$$-10^8 \le v_i \le 10^8$$$), where $$$v_i$$$ is the speed of the $$$i$$$-th point.

Print one integer — the value $$$\sum\limits_{1 \le i < j \le n}$$$ $$$d(i, j)$$$ (the sum of minimum distances over all pairs of points).

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

let sum f i =
  let z = ref 0L in
  let x = ref i in
  while !x > 0 do
    z := Int64.add !z f.(!x);
    x := !x - (!x land -(!x))
  done;
  !z

let add f i d =
  let x = ref i in
  while !x <= ((Array.length f)-1) do
    f.(!x) <- Int64.add f.(!x) d;
    x := !x + (!x land -(!x))
  done

let rec binary_search a ?(l=0) ?(u=Array.length a - 1) k =
    if l > u then raise Not_found;
    let m = l + (u - l) / 2 in
    match compare k a.(m) with
    | -1 -> binary_search a ~l ~u:(m - 1) k
    | 1 -> binary_search a ~l:(m + 1) ~u k
    | _ -> m;;

let () =
  let n = read_int() in
  let x = Array.init n read_int in
  let v = Array.init n read_int in
  let xx = Array.init n (fun i -> (x.(i), v.(i))) in
  Array.sort (fun x y -> compare x y) v;
  Array.sort (fun x y -> compare x y) xx;
  let cc = ref (Array.make (n+1) 0L) in
  let ss = ref (Array.make (n+1) 0L) in

  let z = ref 0L in
  for i=0 to n-1 do
    let (x, key) = xx.(i) in
    let xx = Int64.of_int(x) in
    let vv = (binary_search v key)+1 in
    z := Int64.add !z (Int64.sub (Int64.mul (sum !cc vv) xx) (sum !ss vv));
    add !cc vv 1L;
    add !ss vv xx;
  done;

  printf "%Ld\n" !z;
  (*printf "%d %d %d %Ld\n" x key vv !z;
  let a = List.map (fun s -> int_of_string s) c in*)

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

let sum f i =
  let z = ref 0 in
  let x = ref i in
  while !x > 0 do
    z := !z + f.(!x);
    x := !x - (!x land -(!x))
  done;
  Int64.of_int(!z)

let add f i v =
  let x = ref i in
  while !x <= ((Array.length f)-1) do
    f.(!x) <- f.(!x) + v;
    x := !x + (!x land -(!x))
  done

let rec binary_search a ?(l=0) ?(u=Array.length a - 1) k =
    if l > u then raise Not_found;
    let m = l + (u - l) / 2 in
    match compare k a.(m) with
    | -1 -> binary_search a ~l ~u:(m - 1) k
    | 1 -> binary_search a ~l:(m + 1) ~u k
    | _ -> m;;

let () =
  let n = read_int() in
  let x = Array.init n read_int in
  let v = Array.init n read_int in
  let xx = Array.init n (fun i -> (x.(i), v.(i))) in
  Array.sort (fun x y -> compare x y) v;
  Array.sort (fun x y -> compare x y) xx;
  let cc = Array.make (n+1) 0 in
  let ss = Array.make (n+1) 0 in

  let z = ref 0L in
  for i=0 to n-1 do
    let (x, key) = xx.(i) in
    let xx = Int64.of_int(x) in
    let vv = (binary_search v key)+1 in
    z := Int64.add !z (Int64.sub (Int64.mul (sum cc vv) xx) (sum ss vv));
    add cc vv 1;
    add ss vv x;

  done;

  printf "%Ld\n" !z;
  (*printf "%d %d %d %Ld\n" x key vv !z;
  let a = List.map (fun s -> int_of_string s) c in*)


Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day — exactly $$$2$$$ problems, during the third day — exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of contests. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) — the number of problems in the $$$i$$$-th contest.

Print one integer — the maximum number of days Polycarp can train if he chooses the contests optimally.

let mergesort l =
    let rec helper l =
        match l with
        | [] -> []
        | hd::[] -> hd::[]
        | hd::tl ->
            let (l1, l2) =
                let f (l1, l2) hd = (l2, hd::l1) in
                List.fold_left f ([], []) l
            in
            let l1_sorted = helper l1
            and l2_sorted = helper l2
            in
            let rec merge l1 l2 res =
                match l1, l2 with
                | [], [] -> res
                | hd::tl, [] -> merge tl l2 (hd::res)
                | [], hd::tl -> merge l1 tl (hd::res)
                | h1::t1, h2::t2 ->
                    if h1 < h2 then
                        merge t1 l2 (h1::res)
                    else
                        merge l1 t2 (h2::res)
            in
            merge l1_sorted l2_sorted [] |> List.rev
    in helper l

(* l is sorted *)
let result l =
    let f acc hd =
        if acc < hd then
            acc + 1
        else acc
    in List.fold_left f 0 l
;;

let len = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> x)
let build_list len =
    let rec helper len acc =
        if len = 0 then acc
        else
            let improved = Scanf.scanf " %d " (fun x -> x::acc)
            in helper (len-1) improved
    in
    helper len []

let list = build_list len
let sorted_list = mergesort list;;

let res = result sorted_list;;

Printf.printf "%d\n" res;


There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n + 1) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?   The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses.

The first line contains integer t (1 ≤ t ≤ 104) — the number of test cases.  The second line contains t space-separated integers ni (1 ≤ ni ≤ 109) — the sides of the square for each test sample.

For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

let _ =
  let ni () = Scanf.scanf " %d" (fun x -> x) in
  let re = ni () in
  for ri = 1 to re do
    let n = ni () in
    let n' = float_of_int n in
    Printf.printf "%.0f\n" (1.0 +. match (n + 1) mod 4 with
      | 0 -> n'
      | 2 -> 2.0 *. n'
      | _ -> 4.0 *. n'
    )
  done
;;

open Big_int

let next_token =
  let buffer = ref "" in
  let first = ref 0 in
  let rec omit_spaces s from =
    try
      (match s.[from] with
        | ' ' -> omit_spaces s (from + 1)
        | _ -> from)
    with
      | Invalid_argument _ -> String.length s
  in
  (fun () ->
    first := omit_spaces !buffer !first;
    while !first > String.length !buffer - 1 do
      buffer := read_line ();
      first := omit_spaces !buffer 0
    done;
    let last = try String.index_from !buffer !first ' '
               with Not_found -> String.length !buffer
    in
    let result = String.sub !buffer !first (last - !first) in
    first := last;
    result)

let next_int () = int_of_string (next_token ())

let ( *$ ) a b = mult_big_int a b
let ( /$ ) a b = div_big_int a b
let ( +$ ) a b = add_big_int a b
let ( ~$ ) a = big_int_of_int a
let ( %$ ) a b = mod_big_int a b
let ( <$ ) a b = lt_big_int a b
let ( >$ ) a b = gt_big_int a b
let ( =$ ) a b = eq_big_int a b

let rec gcd a b =
  if a <$ b then gcd b a
  else if b =$ (~$ 0) then a
  else gcd b (a %$ b)

let lcm a b = (a *$ b) /$ (gcd a b)

let () =
  let t = next_int () in
  for k = 1 to t do
    let n = ~$ (next_int ()) in
    let
        result = (lcm ((~$ 4) *$ n) (n +$ (~$ 1))) /$ ((n +$ (~$ 1))) +$ (~$ 1)
    in
    print_endline (string_of_big_int result)
  done

open Big_int

let next_token =
  let buffer = ref "" in
  let first = ref 0 in
  let rec omit_spaces s from =
    try
      (match s.[from] with
        | ' ' -> omit_spaces s (from + 1)
        | _ -> from)
    with
      | Invalid_argument _ -> String.length s
  in
  (fun () ->
    first := omit_spaces !buffer !first;
    while !first > String.length !buffer - 1 do
      buffer := read_line ();
      first := omit_spaces !buffer 0
    done;
    let last = try String.index_from !buffer !first ' '
               with Not_found -> String.length !buffer
    in
    let result = String.sub !buffer !first (last - !first) in
    first := last;
    result)

let next_int () = int_of_string (next_token ())

let ( + ) a b = add_big_int a b
let ( - ) a b = sub_big_int a b
let ( * ) a b = mult_big_int a b
let ( / ) a b = div_big_int a b
let ( % ) a b = mod_big_int a b
let ( < ) a b = lt_big_int a b
let ( > ) a b = gt_big_int a b
let ( = ) a b = eq_big_int a b

let zero = big_int_of_int 0
let one = big_int_of_int 1
let two = big_int_of_int 2
let four = big_int_of_int 4

let rec gcd a b =
  if a < b then gcd b a
  else if b = zero then a
  else gcd b (a % b)

let lcm a b = (a * b) / (gcd a b)

let () =
  let t = next_int () in
  for k = 1 to t do
    let n = big_int_of_int (next_int ()) in
    let result = (lcm (four * n) (n + one)) / (n + one) + one in
    print_endline (string_of_big_int result)
  done

open Big_int

let sieve n =
  let nums = Array.make (n + 1) false in
  let delete m =
    if not nums.(m) then
      for k = 2 to n / m do
        nums.(k * m) <- true
      done
  in
  let result = ref [] in
  nums.(0) <- true;
  nums.(1) <- true;
  for i = 2 to int_of_float(sqrt(float_of_int(n))) + 1 do
    delete i
  done;
  Array.iteri (fun i composite ->
    if not composite then result := i :: !result) nums;
  List.rev !result

let rec factorization ?(result=[]) primes n =
  let add x (* lst *)= function
    | [] -> [(x, 1)]
    | (y, ky) :: ys when y = x -> (x, ky + 1) :: ys
    | ys -> (x, 1) :: ys
  in
  let p = try List.hd primes with Failure _ -> n in
  match n with
    | 1 -> List.rev result
    | _ when n mod p = 0 -> factorization ~result:(add p result) primes (n / p)
    | _ (* <> 0 *)       -> factorization ~result (List.tl primes) n

let rec insert_factor ?(acc=[]) (x, kx) = function
  | [] -> List.rev ((x, kx) :: acc)
  | (y, ky) :: ys when y < x -> insert_factor ~acc:((y, ky) :: acc) (x, kx) ys
  | (y, ky) :: ys when y = x -> List.rev ((x, kx + ky) :: acc) @ ys
  | (y, ky) :: ys (* y > x *) -> List.rev ((x, kx) :: acc) @ ((y, ky) :: ys)

let rec lcm_fact ?(result=[]) lesser greater = match (lesser, greater) with
  | (_, []) -> List.rev result
  | ([], y :: ys) -> lcm_fact ~result:(y :: result) [] ys
  | ((x, kx) :: xs, (y, ky) :: ys) when x = y && kx < ky ->
    lcm_fact ~result:((x, ky - kx) :: result) xs ys
  | ((x, _) :: xs, (y, _) :: ys) when x = y (* kx >= ky *) ->
    lcm_fact ~result xs ys
  | ((x, _) :: xs, (y, _) :: _) when x < y ->
    lcm_fact ~result xs greater
  | (_, y :: ys) (* x > y *) ->
    lcm_fact ~result:(y :: result) lesser ys

let ( *.. ) a b = mult_big_int a b
let ( +.. ) a b = add_big_int a b
let ( ~.. ) a = big_int_of_int a

let rec product ?(result=unit_big_int) = function
  | [] -> result
  | (p, 0) :: ps -> product ~result ps
  | (p, n) :: ps -> product ~result:((~.. p) *.. result) ((p, n - 1) :: ps)

let next_token =
  let buffer = ref "" in
  let first = ref 0 in
  let rec omit_spaces s from =
    try
      (match s.[from] with
        | ' ' -> omit_spaces s (from + 1)
        | _ -> from)
    with
      | Invalid_argument _ -> String.length s
  in
  (fun () ->
    first := omit_spaces !buffer !first;
    while !first > String.length !buffer - 1 do
      buffer := read_line ();
      first := omit_spaces !buffer 0
    done;
    let last = try String.index_from !buffer !first ' '
               with Not_found -> String.length !buffer
    in
    let result = String.sub !buffer !first (last - !first) in
    first := last;
    result)

let next_int () = int_of_string (next_token ())

let () =
  let primes = sieve 31623 in
  let t = next_int () in
  for k = 1 to t do
    let n = next_int () in
    let greater_factors = insert_factor (2, 2) (factorization primes n) in
    let lesser_factors = factorization primes (n + 1) in
    let
        result = (product (lcm_fact lesser_factors greater_factors)) +.. (~.. 1)
    in
    print_endline (string_of_big_int result)
  done

let rec gao n =
  if n = 1 then 2
  else if n mod 2 = 0 then 4 * n
  else gao (n / 2 + 1)
;;

let _ =
  let ni () = Scanf.scanf " %d" (fun x -> x) in
  let re = ni () in
  for ri = 1 to re do
    let n = ni () in
    Printf.printf "%d\n" (1 + gao n)
  done
;;

let sieve n =
  let nums = Array.make (n + 1) false in
  let delete m =
    if not nums.(m) then
      for k = 2 to n / m do
        nums.(k * m) <- true
      done
  in
  let result = ref [] in
  nums.(0) <- true;
  nums.(1) <- true;
  for i = 2 to int_of_float(sqrt(float_of_int(n))) + 1 do
    delete i
  done;
  Array.iteri (fun i composite ->
    if not composite then result := i :: !result) nums;
  List.rev !result

let rec factorization ?(result=[]) primes n =
  let add x (* lst *)= function
    | [] -> [(x, 1)]
    | (y, ky) :: ys when y = x -> (x, ky + 1) :: ys
    | ys -> (x, 1) :: ys
  in
  let p = try List.hd primes with Failure _ -> n in
  match n with
    | 1 -> List.rev result
    | _ when n mod p = 0 -> factorization ~result:(add p result) primes (n / p)
    | _ (* <> 0 *)       -> factorization ~result (List.tl primes) n

let rec insert_factor ?(acc=[]) (x, kx) = function
  | [] -> List.rev ((x, kx) :: acc)
  | (y, ky) :: ys when y < x -> insert_factor ~acc:((y, ky) :: acc) (x, kx) ys
  | (y, ky) :: ys when y = x -> List.rev ((x, kx + ky) :: acc) @ ys
  | (y, ky) :: ys (* y > x *) -> List.rev ((x, kx) :: acc) @ ((y, ky) :: ys)

let rec lcm_fact ?(result=[]) lesser greater = match (lesser, greater) with
  | (_, []) -> List.rev result
  | ([], y :: ys) -> lcm_fact ~result:(y :: result) [] ys
  | ((x, kx) :: xs, (y, ky) :: ys) when x = y && kx < ky->
    lcm_fact ~result:((x, ky - kx) :: result) xs ys
  | ((x, _) :: xs, (y, _) :: ys) when x = y ->
    lcm_fact ~result xs ys
  | ((x, _) :: xs, (y, _) :: _) when x < y ->
    lcm_fact ~result xs greater
  | ((x, _) :: _, (y, ky) :: ys) (* x > y *) ->
    lcm_fact ~result:((y, ky) :: result) lesser ys

let rec product ?(result=1) = function
  | [] -> result
  | (p, 0) :: ps -> product ~result ps
  | (p, n) :: ps -> product ~result:(p * result) ((p, n - 1) :: ps)

let next_token =
  let buffer = ref "" in
  let first = ref 0 in
  let rec omit_spaces s from =
    try
      (match s.[from] with
        | ' ' -> omit_spaces s (from + 1)
        | _ -> from)
    with
      | Invalid_argument _ -> String.length s
  in
  (fun () ->
    first := omit_spaces !buffer !first;
    while !first > String.length !buffer - 1 do
      buffer := read_line ();
      first := omit_spaces !buffer 0
    done;
    let last = try String.index_from !buffer !first ' '
               with Not_found -> String.length !buffer
    in
    let result = String.sub !buffer !first (last - !first) in
    first := last;
    result)

let next_int () = int_of_string (next_token ())

let () =
  let primes = sieve 31623 in
  let t = next_int () in
  for k = 1 to t do
    let n = next_int () in
    let greater_factors = insert_factor (2, 2) (factorization primes n) in
    let lesser_factors = factorization primes (n + 1) in
    let result = (product (lcm_fact lesser_factors greater_factors)) + 1 in
    print_endline (string_of_int result)
  done

let sieve n =
  let nums = Array.make (n + 1) false in
  let delete m =
    if not nums.(m) then
      for k = 2 to n / m do
        nums.(k * m) <- true
      done
  in
  let result = ref [] in
  nums.(0) <- true;
  nums.(1) <- true;
  for i = 2 to int_of_float(sqrt(float_of_int(n))) do
    delete i
  done;
  Array.iteri (fun i composite ->
    if not composite then result := i :: !result) nums;
  List.rev !result

let rec factorization ?(result=[]) primes n =
  let add x (* lst *)= function
    | [] -> [(x, 1)]
    | (y, ky) :: ys when y = x -> (x, ky + 1) :: ys
    | ys -> (x, 1) :: ys
  in
  let p = try List.hd primes with Failure _ -> n in
  match n with
    | 1 -> List.rev result
    | _ when n mod p = 0 -> factorization ~result:(add p result) primes (n / p)
    | _ (* <> 0 *)       -> factorization ~result (List.tl primes) n

let rec insert_factor ?(acc=[]) (x, kx) = function
  | [] -> List.rev ((x, kx) :: acc)
  | (y, ky) :: ys when y < x -> insert_factor ~acc:((y, ky) :: acc) (x, kx) ys
  | (y, ky) :: ys when y = x -> List.rev ((x, kx + ky) :: acc) @ ys
  | (y, ky) :: ys (* y > x *) -> List.rev ((x, kx) :: acc) @ ((y, ky) :: ys)

let rec lcm_fact ?(result=[]) lesser greater = match (lesser, greater) with
  | (_, []) -> List.rev result
  | ([], y :: ys) -> lcm_fact ~result:(y :: result) [] ys
  | ((x, kx) :: xs, (y, ky) :: ys) when x = y && kx < ky->
    lcm_fact ~result:((x, ky - kx) :: result) xs ys
  | ((x, _) :: xs, (y, _) :: ys) when x = y ->
    lcm_fact ~result xs ys
  | ((x, _) :: xs, (y, _) :: _) when x < y ->
    lcm_fact ~result xs greater
  | ((x, _) :: _, (y, ky) :: ys) (* x > y *) ->
    lcm_fact ~result:((y, ky) :: result) lesser ys

let rec product ?(result=1) = function
  | [] -> result
  | (p, 0) :: ps -> product ~result ps
  | (p, n) :: ps -> product ~result:(p * result) ((p, n - 1) :: ps)

let next_token =
  let buffer = ref "" in
  let first = ref 0 in
  let rec omit_spaces s from =
    try
      (match s.[from] with
        | ' ' -> omit_spaces s (from + 1)
        | _ -> from)
    with
      | Invalid_argument _ -> String.length s
  in
  (fun () ->
    first := omit_spaces !buffer !first;
    while !first > String.length !buffer - 1 do
      buffer := read_line ();
      first := omit_spaces !buffer 0
    done;
    let last = try String.index_from !buffer !first ' '
               with Not_found -> String.length !buffer
    in
    let result = String.sub !buffer !first (last - !first) in
    first := last;
    result)

let next_int () = int_of_string (next_token ())

let () =
  let primes = sieve 10000 in
  let t = next_int () in
  for k = 1 to t do
    let n = next_int () in
    let greater_factors = insert_factor (2, 2) (factorization primes n) in
    let lesser_factors = factorization primes (n + 1) in
    let result = (product (lcm_fact lesser_factors greater_factors)) + 1 in
    print_endline (string_of_int result)
  done


All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket. The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 3·105) — the number of coupons Fedor has, and the number of coupons he wants to choose. Each of the next n lines contains two integers li and ri ( - 109 ≤ li ≤ ri ≤ 109) — the description of the i-th coupon. The coupons can be equal.

In the first line print single integer — the maximum number of products with which all the chosen coupons can be used. The products with which at least one coupon cannot be used shouldn't be counted. In the second line print k distinct integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the ids of the coupons which Fedor should choose. If there are multiple answers, print any of them.

NoteIn the first example if we take the first two coupons then all the products with ids in range [40, 70] can be bought with both coupons. There are 31 products in total.In the second example, no product can be bought with two coupons, that is why the answer is 0. Fedor can choose any two coupons in this example.

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

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

open Printf
open Scanf

let read_long () = bscanf Scanning.stdib " %Ld " (fun x -> x)
let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,k) = read_pair () in
  let seg = Array.init n (fun i -> let l = read_long () in let r = read_long() in (l,r,i)) in

  Array.sort compare seg;

  let rec loop i size set best_score best_set =
    if i=n then (best_score,best_set) else
      let (l,r,j) = seg.(i) in
      let set = Pset.add (r,j) set in
      let (r',_) = Pset.min_elt set in
      let size = size+1 in
      let (best_score, best_set) =
	if size = k && best_score < (r' -- l) then (r' -- l, set) else (best_score, best_set)
      in
      let (size,set) = if size<k then (size,set) else
	  (size-1, Pset.remove (Pset.min_elt set) set)
      in
      loop (i+1) size set best_score best_set
  in

  let (best_score, best_set) = loop 0 0 Pset.empty (-1L) Pset.empty in

  printf "%Ld\n" (best_score ++ 1L);

  if best_score = -1L then (
    for i=0 to k-1 do
      let (_,_,j) = seg.(i) in
      printf "%d " (j+1)
    done;
    print_newline()
  ) else (
    Pset.iter (fun (_,i) -> printf "%d " (i+1)) best_set;
    print_newline()
  )


You've got an undirected graph, consisting of n vertices and m edges. We will consider the graph's vertices numbered with integers from 1 to n. Each vertex of the graph has a color. The color of the i-th vertex is an integer ci.Let's consider all vertices of the graph, that are painted some color k. Let's denote a set of such as V(k). Let's denote the value of the neighbouring color diversity for color k as the cardinality of the set Q(k) = {cu :  cu ≠ k and there is vertex v belonging to set V(k) such that nodes v and u are connected by an edge of the graph}.Your task is to find such color k, which makes the cardinality of set Q(k) maximum. In other words, you want to find the color that has the most diverse neighbours. Please note, that you want to find such color k, that the graph has at least one vertex with such color.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of vertices end edges of the graph, correspondingly. The second line contains a sequence of integers c1, c2, ..., cn (1 ≤ ci ≤ 105) — the colors of the graph vertices. The numbers on the line are separated by spaces. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the numbers of the vertices, connected by the i-th edge.  It is guaranteed that the given graph has no self-loops or multiple edges.

Print the number of the color which has the set of neighbours with the maximum cardinality. It there are multiple optimal colors, print the color with the minimum number. Please note, that you want to find such color, that the graph has at least one vertex with such color.

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

let solve (n, m, c, e0) =
  let open Hashtbl in
  let adjC : ((int, (int, unit) t) t) = create 10 in
  Array.iter
    (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))
    c;
  Array.iter
    (fun (u, v) ->
      if c.(u) = c.(v) then ()
      else begin
        replace (find adjC c.(u)) c.(v) ();
        replace (find adjC c.(v)) c.(u) ()
      end)
    e0;
  fold
    (fun c' h (c, q) ->
      let q' = length h in
      if q' > q || q' = q && c' < c
      then (c', q')
      else (c, q))
    adjC
    (-1, -1)
  |> fst

let main () =
  let n = readInt () in
  let m = readInt () in
  let c = Array.init n (fun _ -> readInt ()) in
  let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in
  Printf.printf "%d\n" (solve (n, m, c, e0))

let () = main ()

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

let solve (n, m, c, e0) =
  let open Hashtbl in
  let adjC : ((int, (int, unit) t) t) = create (n/10) in
  Array.iter
    (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))
    c;
  Array.iter
    (fun (u, v) ->
      if c.(u) = c.(v) then ()
      else begin
        replace (find adjC c.(u)) c.(v) ();
        replace (find adjC c.(v)) c.(u) ()
      end)
    e0;
  fold
    (fun c' h (c, q) ->
      let q' = length h in
      if q' > q || q' = q && c' < c
      then (c', q')
      else (c, q))
    adjC
    (-1, -1)
  |> fst

let main () =
  let n = readInt () in
  let m = readInt () in
  let c = Array.init n (fun _ -> readInt ()) in
  let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in
  Printf.printf "%d\n" (solve (n, m, c, e0))

let () = main ()

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

let solve (n, m, c, e0) =
  let open Hashtbl in
  let adjC : ((int, (int, unit) t) t) = create 10 in
  Array.iter
    (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))
    c;
  Array.iter
    (fun (u, v) ->
      if c.(u) = c.(v) then ()
      else begin
        replace (find adjC c.(u)) c.(v) ();
        replace (find adjC c.(v)) c.(u) ()
      end)
    e0;
  (* -(snd Seq.(to_seq adjC |> map (fun (c, h) -> (length h, -c)) |> fold_left max (-1, -1))) *)
  -(snd (fold (fun c' h cur -> max (length h, -c') cur) adjC (-1, -1)))

let main () =
  let n = readInt () in
  let m = readInt () in
  let c = Array.init n (fun _ -> readInt ()) in
  let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in
  Printf.printf "%d\n" (solve (n, m, c, e0))

let () = main ()

let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> 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) 0
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

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

  let c = Array.init n (fun _ -> read_int()) in (* colors of the vertices *)

  let mc = maxf 0 (n-1) (fun i -> c.(i)) in (* maximum color *)

  let carray = Array.init (mc+1) (fun _-> Hashtbl.create 5) in

  let add_edge a b =
    if (c.(a) <> c.(b)) then (
      Hashtbl.replace carray.(c.(a)) c.(b) true;
      Hashtbl.replace carray.(c.(b)) c.(a) true;
    )
  in

  let () =
    for i=0 to m-1 do
      let a = read_int() in
      let b = read_int() in
	add_edge (a-1) (b-1);
    done
  in

  let ccount c = Hashtbl.length carray.(c) in
  let div = maxf 0 mc ccount in
  let i = minf 0 (n-1) (fun j -> if ccount c.(j) = div then c.(j) else (mc+1)) in
    Printf.printf "%d\n" i

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

let solve (n, m, c, e0) =
  let open Hashtbl in
  let adjC : ((int, (int, unit) t) t) = create (n/10) in
  Array.iter
    (fun c -> try let _ = find adjC c in () with Not_found -> add adjC c (create 10))
    c;
  Array.iter
    (fun (u, v) ->
      replace (find adjC c.(u)) c.(v) ();
      replace (find adjC c.(v)) c.(u) ())
    e0;
  fst (fold (fun c' h (c, q) -> let q' = length h in if q' > q then (c', q') else (c, q)) adjC (-1, -1) )

let main () =
  let n = readInt () in
  let m = readInt () in
  let c = Array.init n (fun _ -> readInt ()) in
  let e0 = Array.init m (fun _ -> (readInt () - 1, readInt () - 1)) in
  Printf.printf "%d\n" (solve (n, m, c, e0))

let () = main ()

let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> 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) 0
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let argmax i j f = fold (i+1) j (fun k (y,j) -> let x = f k in if x > y then (x,k) else (y,j)) ((f i),i)

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

  let c = Array.init n (fun _ -> read_int()) in (* colors of the vertices *)

  let mc = maxf 0 (n-1) (fun i -> c.(i)) in (* maximum color *)

  let carray = Array.init (mc+1) (fun _-> Hashtbl.create 5) in

  let add_edge a b =
    if (c.(a) <> c.(b)) then (
      Hashtbl.replace carray.(c.(a)) c.(b) true;
      Hashtbl.replace carray.(c.(b)) c.(a) true;
    )
  in

  let () =
    for i=0 to m-1 do
      let a = read_int() in
      let b = read_int() in
	add_edge (a-1) (b-1);
    done
  in

  let ccount c = Hashtbl.length carray.(c) in
  let (div,i) = argmax 0 mc ccount in
  let i = if div = 0 then c.(0) else i in
    Printf.printf "%d\n" i

let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> 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) 0
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

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

  let c = Array.init n (fun _ -> read_int()) in (* colors of the vertices *)

  let mc = maxf 0 (n-1) (fun i -> c.(i)) in (* maximum color *)

  let carray = Array.init (mc+1) (fun _-> Hashtbl.create 5) in

  let add_edge a b =
    if (c.(a) <> c.(b)) then (
      Hashtbl.replace carray.(c.(a)) c.(b) true;
      Hashtbl.replace carray.(c.(b)) c.(a) true;
    )
  in

  let () =
    for i=0 to m-1 do
      let a = read_int() in
      let b = read_int() in
	add_edge (a-1) (b-1);
    done
  in

  let ccount c = Hashtbl.length carray.(c) in
  let div = maxf 0 mc ccount in
  let i = minf 0 (n-1) (fun j -> if ccount c.(j) = div then c.(j) else -1) in
    Printf.printf "%d\n" i


After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements:  There is at least one digit in the string,  There is at least one lowercase (small) letter of the Latin alphabet in the string,  There is at least one of three listed symbols in the string: '#', '*', '&'.   Considering that these are programming classes it is not easy to write the password.For each character of the password we have a fixed string of length m, on each of these n strings there is a pointer on some character. The i-th character displayed on the screen is the pointed character in the i-th string. Initially, all pointers are on characters with indexes 1 in the corresponding strings (all positions are numbered starting from one).During one operation Dasha can move a pointer in one string one character to the left or to the right. Strings are cyclic, it means that when we move the pointer which is on the character with index 1 to the left, it moves to the character with the index m, and when we move it to the right from the position m it moves to the position 1.You need to determine the minimum number of operations necessary to make the string displayed on the screen a valid password.

The first line contains two integers n, m (3 ≤ n ≤ 50, 1 ≤ m ≤ 50) — the length of the password and the length of strings which are assigned to password symbols.  Each of the next n lines contains the string which is assigned to the i-th symbol of the password string. Its length is m, it consists of digits, lowercase English letters, and characters '#', '*' or '&'. You have such input data that you can always get a valid password.

Print one integer — the minimum number of operations which is necessary to make the string, which is displayed on the screen, a valid password.

NoteIn the first test it is necessary to move the pointer of the third string to one left to get the optimal answer.   In the second test one of possible algorithms will be:   to move the pointer of the second symbol once to the right.  to move the pointer of the third symbol twice to the right.

let search m f s =
  let rec loop i =
    if i <= m / 2 then
      if f s.[i] || (i > 0 && f s.[m - i]) then
        i
      else
        loop (i + 1)
    else max_int in
  loop 0

let is_digit c =
  let code = Char.code c in
  code >= 48 && code <= 57

let is_letter c =
  let code = Char.code c in
  code >= 97 && code <= 122

let is_symbol c =
  c = '#' || c = '*' || c = '&'

let fst (x, _, _) = x
let snd (_, x, _) = x
let trd (_, _, x) = x

let () =
  Scanf.scanf "%d %d " @@ fun n m ->
  let read_word s =
    (search m is_digit s, search m is_letter s, search m is_symbol s) in
  let ds = Array.init n (fun _ -> Scanf.scanf "%s " read_word) in
  let rec loop_digit mind i =
    if i < n then
      let d = fst ds.(i) in
      if d >= mind then
        loop_digit mind (i + 1)
      else
        let d = d + loop_letter (mind - d) 0 i in
        loop_digit (min d mind) (i + 1)
    else mind
  and loop_letter mind i x =
    if i = x then
      loop_letter mind (i + 1) x
    else if i < n then
      let d = snd ds.(i) in
      if d >= mind then
        loop_letter mind (i + 1) x
      else
        let d = d + loop_symbol (mind - d) 0 i x in
        loop_letter (min d mind) (i + 1) x
    else mind
  and loop_symbol mind i x xx =
    if i = x || i = xx then
      loop_symbol mind (i + 1) x xx
    else if i < n then
      let d = trd ds.(i) in
      loop_symbol (min d mind) (i + 1) x xx
    else mind in
  loop_digit max_int 0 |> Printf.printf "%d\n"


Seryozha has a very changeable character. This time he refused to leave the room to Dima and his girlfriend (her hame is Inna, by the way). However, the two lovebirds can always find a way to communicate. Today they are writing text messages to each other.Dima and Inna are using a secret code in their text messages. When Dima wants to send Inna some sentence, he writes out all words, inserting a heart before each word and after the last word. A heart is a sequence of two characters: the "less" characters (<) and the digit three (3). After applying the code, a test message looks like that: <3word1<3word2<3 ... wordn<3.Encoding doesn't end here. Then Dima inserts a random number of small English characters, digits, signs "more" and "less" into any places of the message.Inna knows Dima perfectly well, so she knows what phrase Dima is going to send her beforehand. Inna has just got a text message. Help her find out if Dima encoded the message correctly. In other words, find out if a text message could have been received by encoding in the manner that is described above.

The first line contains integer n (1 ≤ n ≤ 105) — the number of words in Dima's message. Next n lines contain non-empty words, one word per line. The words only consist of small English letters. The total length of all words doesn't exceed 105.  The last line contains non-empty text message that Inna has got. The number of characters in the text message doesn't exceed 105. A text message can contain only small English letters, digits and signs more and less.

In a single line, print "yes" (without the quotes), if Dima decoded the text message correctly, and "no" (without the quotes) otherwise.

7
i
am
not
main
in
the
family
<3i<>3am<3the<3<main<3in<3the<3><3family<3

NotePlease note that Dima got a good old kick in the pants for the second sample from the statement.

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

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

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

module List = struct
  include ListLabels ;;

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

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

module Array = struct
  include ArrayLabels ;;

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

module String = struct
  include StringLabels ;;

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

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

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

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

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

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

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

let () =
  let n = Scanf.scanf "%d " ident in
  let ss = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%s " ident  :: acc) |> List.rev in
  let text = Scanf.scanf "%s " ident in
  let len = String.length text in
  try
    let start = List.fold_left ss ~init:0 ~f:(fun start s ->
      let u = "<3" ^ s in
      let cur = ref start in
      iter_for 0 (String.length u) ~f:(fun i ->
        while u.[i] <> text.[!cur] do
          cur := !cur + 1;
          if !cur >= len then raise Not_found;
        done; cur := !cur + 1);
      !cur) in
    Str.search_forward (Str.regexp "[a-z0-9<>]*<[a-z0-9<>]*3[a-z0-9<>]*") text start |> ignore;
    print_endline "yes";
  with
  | _ -> print_endline "no"
;;

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

let () =
  let n = Scanf.scanf "%d " id in
  let rec loop n acc =
    if n = 0 then acc else
    let s = Scanf.scanf "%s " id in
    loop (n-1) ("<3" :: s :: acc)
  in
  let orig = loop n ["<3"] |> List.rev |> String.concat "" in
  let msg = Scanf.scanf "%s " id in
  let i = ref 0 in
  String.iter (fun s ->
    if !i < String.length orig && s = orig.[!i] then incr i
  ) msg;
  print_endline @@ if !i = String.length orig then "yes" else "no";

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

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

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

module List = struct
  include ListLabels ;;

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

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

module Array = struct
  include ArrayLabels ;;

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

module String = struct
  include StringLabels ;;

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

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

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

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

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

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

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

let () =
  let n = Scanf.scanf "%d " ident in
  let ss = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%s " ident  :: acc) |> List.rev in
  let text = Scanf.scanf "%s " ident in
  let len = String.length text in
  try
    let start = List.fold_left ss ~init:0 ~f:(fun start s ->
      let u = "<3" ^ s in
      let cur = ref start in
      iter_for 0 (String.length u) ~f:(fun i ->
        while u.[i] <> text.[!cur] do
          cur := !cur + 1;
          if !cur >= len then raise Not_found;
        done);
      !cur) in
    Str.search_forward (Str.regexp "[a-z0-9<>]*<[a-z0-9<>]*3[a-z0-9<>]*") text start |> ignore;
    print_endline "yes";
  with
  | _ -> print_endline "no"
;;