Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a1, a2, ..., an of n integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:  Each pencil belongs to exactly one box;  Each non-empty box has at least k pencils in it;  If pencils i and j belong to the same box, then |ai - aj| ≤ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |ai - aj| ≤ d and they belong to different boxes. Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".

The first line contains three integer numbers n, k and d (1 ≤ k ≤ n ≤ 5·105, 0 ≤ d ≤ 109) — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — saturation of color of each pencil.

Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".

NoteIn the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box.

(* codeforces.com/contest/985/problem/E *)

module type Seg_tree_T = sig
  type t
  val mappend: t -> t -> t
  val to_string: t -> string
end

module type Seg_tree_S = sig
  type t
  type elt

  val create: int -> elt -> t
  val size: t -> int
  val set: t -> int -> elt -> unit
  val query: t -> int * int -> elt
end

module Seg_tree (T: Seg_tree_T): Seg_tree_S with type elt = T.t = struct
  type elt = T.t
  type t = int * elt array

  let rec pow a = function
  | 0 -> 1
  | 1 -> a
  | n ->
    let b = pow a (n / 2) in
    b * b * (if n mod 2 = 0 then 1 else a)

  let log2 a = log a /. log 2.

  let create size init =
    let power = size |> float_of_int |> log2 |> ceil |> int_of_float in
    let length = pow 2 (power + 1) in
    size, Array.make (length + 1) init

  let size = fst

  let set (len, tree) idx value =
    let rec f i l r =
      (*Printf.printf "set f: %d %d %d\n" i l r;*)
      if idx < l || idx >= r
      then tree.(i)
      else
        if r - l = 1
        then begin tree.(i) <- value; value end
        else
          let lv = f (2 * i) l ((l + r) / 2) in
          let rv = f (2 * i + 1) ((l + r) / 2) r in
          let v = T.mappend lv rv in
          tree.(i) <- v; v
    in
    f 1 0 len |> ignore

  let query (len, tree) (lr, rr): T.t =
    let rec f i l r: T.t =
      if l >= lr && r <= rr
      then tree.(i)
      else
        let m = (l + r) / 2 in
        if m <= lr
        then f (i * 2 + 1) m r
        else if m >= rr
        then f (i * 2) l m
        else T.mappend
               (f (i * 2) l m)
               (f (i * 2 + 1) m r)
    in
    f 1 0 len

end

module Monoid_bool: Seg_tree_T with type t = bool = struct
  type t = bool
  let mappend = (||)
  let to_string = string_of_bool
end

module ST = Seg_tree(Monoid_bool)

(* github.com/janestreet/base/blob/master/src/binary_search.ml *)
let bisearch (data: int array) ((lr, rr): int * int) (min_value: int): int option =
  let rec f l r =
    if l > r
    then None
    else
      if l = r
      then if data.(l) >= min_value then Some l else None
      else
        let m = l + (r - l) / 2 in
        if data.(m) >= min_value
        then f l m
        else f (m + 1) r
  in
  f lr (rr - 1)

let _ =
  Printexc.record_backtrace true;
  let n, k, d = Scanf.scanf " %d %d %d" (fun a b c -> a, b, c) in
  let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i)) in
  Array.sort compare a;

  let dp = ST.create (n + 1) false in
  ST.set dp 0 true;
  let rec f i =
    if i > n
    then ()
    else
      if i < k
      then f (i + 1)
      else
        let j = bisearch a (0, (i - k + 1)) (a.(i - 1) - d) in
        match j with
        | Some j ->
          (if i - k + 1 > j
          then
            ST.set dp i (ST.query dp (j, (i - k + 1)))
          else ());
          f (i + 1)
          | _ -> f (i + 1)
  in
  f 0;
  (if ST.query dp (n, n + 1) then "YES" else "NO") |> print_endline


In the pet store on sale there are:  $$$a$$$ packs of dog food;  $$$b$$$ packs of cat food;  $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.

The first line of input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ lines are given, each containing a description of one test case. Each description consists of five integers $$$a, b, c, x$$$ and $$$y$$$ ($$$0 \le a,b,c,x,y \le 10^8$$$).

For each test case in a separate line, output:   YES, if suitable food can be bought for each of $$$x$$$ dogs and for each of $$$y$$$ cats;  NO else.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

let nextInt () = Scanf.scanf " %d" (fun x->x);;
let nextTestCase () =
        let a=nextInt () in
        let b=nextInt () in
        let c=nextInt () in
        let x=nextInt () in
        let y=nextInt () in
        a, b, c, x, y
;;
let rec enoughFood = function
    | a,b,c,0,y->
        if (b+c>=y) then true
        else false
    | a,b,c,x,y->
        if (a>=x) then enoughFood ((a-x),b,c,0,y)
        else if (a+c>=x) then enoughFood (0,b,(a+c-x),0,y)
        else false
;;
let rec getResults = function
 | 0 -> 0
 | n ->
        let hasEnough=enoughFood (nextTestCase ()) in
        if (hasEnough) then begin
            print_string "YES\n";
            getResults (n-1)
        end
        else begin
            print_string "NO\n";
            getResults (n-1)
        end
;;
let test_cases = nextInt() in
getResults test_cases
;;


There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.

The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct.

Print two integer numbers — the minimal distance and the quantity of pairs with this distance.

NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0L in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
    Array.sort compare a;
  in
  let md = ref 2000000001L in
  let mc = ref 0 in
    for i = 0 to n - 2 do
      let d = Int64.abs (a.(i) -| a.(i + 1)) in
	if d < !md then (
	  md := d;
	  mc := 1;
	) else if d = !md then (
	  incr mc
	)
    done;
    Printf.printf "%Ld %d\n" !md !mc


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. 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.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

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

let (--) debut fin =
  let rec range aux start en =
    if start > en then aux
    else range (en::aux) start (en-1)
  in range [] debut fin;;

let res = Array.make 6 Int64.zero;;

type lot = {
  index: int;
  value: int64;
}

let best_index tabl money =
  List.find (fun el -> el.value <= money) tabl;;

let rec process_data lots arr money =
  match best_index lots money with
  | {index = 5; value = _} -> begin
      match arr with
      | [] -> money
      | head :: tail ->
        process_data lots tail (Int64.add money head)
    end
  | won ->
    res.(won.index) <- Int64.add res.(won.index) (Int64.div money won.value);
    process_data lots arr (Int64.rem money won.value);;

(*#trace process_data;;*)

let taille = read_int () in
let input = (1 -- taille)
            |> List.map (fun _ -> Int64.of_int (read_int ())) in
let lots = ({index = 5; value = Int64.zero} ::
            ((0 -- 4)
             |> List.map (fun i -> {index = i; value = Int64.of_int (read_int ())})))
           |> List.sort (fun x y -> compare y.value x.value) in
let money_left = process_data lots input Int64.zero in
for i = 0 to 4 do
  Printf.printf "%s " (Int64.to_string res.(i))
done;
Printf.printf "\n%s\n" (Int64.to_string money_left);;

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

let (--) debut fin =
  let rec range aux start en =
    if start > en then aux
    else range (en::aux) start (en-1)
  in range [] debut fin;;

let res = Array.make 6 0;;

type lot = {
  index: int;
  value: int;
}

let best_index tabl money =
  List.find (fun el -> el.value <= money) tabl;;

let rec process_data lots arr money =
  match best_index lots money with
  | {index = 5; value = _} -> begin
      match arr with
      | [] -> money
      | head :: tail ->
        process_data lots tail (money + head)
    end
  | won ->
    res.(won.index) <- res.(won.index) + (money / won.value);
    process_data lots arr (money mod won.value);;

(*#trace process_data;;*)

let taille = read_int () in
let input = (1 -- taille)
            |> List.map (fun _ -> read_int ()) in
let lots = ({index = 5; value = 0} ::
            ((0 -- 4)
             |> List.map (fun i -> {index = i; value = read_int ()})))
           |> List.sort (fun x y -> compare y.value x.value) in
let money_left = process_data lots input 0 in
for i = 0 to 4 do
  Printf.printf "%d " res.(i)
done;
Printf.printf "\n%d\n" money_left;;


NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles:  It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles $$$n$$$ and the radius of the inner circle $$$r$$$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $$$R$$$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.

The first and the only line of the input file contains two numbers $$$n$$$ and $$$r$$$ ($$$3 \leq n \leq 100$$$, $$$1 \leq r \leq 100$$$) — the number of the outer circles and the radius of the inner circle respectively.

Output a single number $$$R$$$ — the radius of the outer circle required for building the required picture.  Your answer will be accepted if its relative or absolute error does not exceed $$$10^{-6}$$$. Formally, if your answer is $$$a$$$ and the jury's answer is $$$b$$$. Your answer is accepted if and only when $$$\frac{|a-b|}{max(1, |b|)} \le 10^{-6}$$$.

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

let () =
    let n = read_float () and r = read_float () in
    let pi = acos (-1.) in
    let x = sin (pi /. n) in
    let ans = r *. x /. (1. -. x) in
    printf "%f\n" ans

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

let pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328
let () =
  let n,r = g2 0 in
  let u = (pi /. (2.*.(Int64.to_float n))) in
  let q = (sin u -. cos u) ** 2. in
  let p = (Int64.to_float r) *. sin (pi /. (Int64.to_float n))
  in
  printf "%.18f" @@ p /. q

open Printf
open Scanf

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

let pi = 2.0 *. (atan2 1.0 0.0)

let () =
  let n = read_int() in
  let r0 = read_float() in

  let alpha = pi /. (float n) in
  let salpha = sin alpha in

  let r = salpha /. (1.0 -. salpha) in

  printf "%.8f\n" (r0 *. r)


In some country live wizards. They love playing with numbers. The blackboard has two numbers written on it — a and b. The order of the numbers is not important. Let's consider a ≤ b for the sake of definiteness. The players can cast one of the two spells in turns:  Replace b with b - ak. Number k can be chosen by the player, considering the limitations that k > 0 and b - ak ≥ 0. Number k is chosen independently each time an active player casts a spell.  Replace b with b mod a. If a > b, similar moves are possible.If at least one of the numbers equals zero, a player can't make a move, because taking a remainder modulo zero is considered somewhat uncivilized, and it is far too boring to subtract a zero. The player who cannot make a move, loses.To perform well in the magic totalizator, you need to learn to quickly determine which player wins, if both wizards play optimally: the one that moves first or the one that moves second.

The first line contains a single integer t — the number of input data sets (1 ≤ t ≤ 104). Each of the next t lines contains two integers a, b (0 ≤ a, b ≤ 1018). The numbers are separated by a space. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

For any of the t input sets print "First" (without the quotes) if the player who moves first wins. Print "Second" (without the quotes) if the player who moves second wins. Print the answers to different data sets on different lines in the order in which they are given in the input.

NoteIn the first sample, the first player should go to (11,10). Then, after a single move of the second player to (1,10), he will take 10 modulo 1 and win.In the second sample the first player has two moves to (1,10) and (21,10). After both moves the second player can win.In the third sample, the first player has no moves.In the fourth sample, the first player wins in one move, taking 30 modulo 10.

let _ =
  let sb = Scanf.Scanning.stdib in
  let cases = Scanf.bscanf sb "%d " (fun s -> s) in
    for ca = 1 to cases do
      let a = Scanf.bscanf sb "%Ld " (fun s -> s) in
      let b = Scanf.bscanf sb "%Ld " (fun s -> s) in
      let a = max a b
      and b = min a b in
      let rec solve a b =
	if b = 0L
	then false
	else if b = 1L
	then true
	else (
	  let s = solve b (Int64.rem a b) in
	    if not s
	    then true
	    else (
	      let a = Int64.div a b in
		Int64.rem (Int64.rem a (Int64.add b 1L)) 2L = 0L
	    )
	)
      in
	if solve a b
	then Printf.printf "First\n"
	else Printf.printf "Second\n"
    done

let _ =
  let sb = Scanf.Scanning.stdib in
  let cases = Scanf.bscanf sb "%d " (fun s -> s) in
    for ca = 1 to cases do
      let a = Scanf.bscanf sb "%Ld " (fun s -> s) in
      let b = Scanf.bscanf sb "%Ld " (fun s -> s) in
      let a = max a b
      and b = min a b in
      let rec solve a b =
	if b = 0L
	then false
	else if b = 1L
	then true
	else (
	  let s = solve b (Int64.rem a b) in
	    if not s
	    then true
	    else (
	      let a = ref (Int64.div a b) in
	      let sum = ref 0 in
		while !a > 0L do
		  if Int64.rem (Int64.rem !a b) 2L <> 0L
		  then incr sum;
		  a := Int64.div !a b
		done;
		if !sum mod 2 <> 0
		then false
		else true
	    )
	)
      in
	if solve a b
	then Printf.printf "First\n"
	else Printf.printf "Second\n"
    done


As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!The sequence of round brackets is called valid if and only if:   the total number of opening brackets is equal to the total number of closing brackets;  for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109 + 7.

First line contains n and m (1 ≤ m ≤ n ≤ 100 000, n - m ≤ 2000) — the desired length of the string and the length of the string bought by Gabi, respectively. The second line contains string s of length m consisting of characters '(' and ')' only.

Print the number of pairs of string p and q such that p + s + q is a valid sequence of round brackets modulo 109 + 7.

NoteIn the first sample there are four different valid pairs:   p = "(", q = "))"  p = "()", q = ")"  p = "", q = "())"  p = "", q = ")()" In the second sample the only way to obtain a desired string is choose empty p and q.In the third sample there is no way to get a valid sequence of brackets.

open Printf
open Scanf

let p = 1_000_000_007L
let long x = Int64.of_int x
let ( %% ) a b = Int64.rem a b
let ( ** ) a b = (Int64.mul a b) %% p
let ( ++ ) a b = let x = Int64.add a b in if x<p then x else Int64.sub x p
let ( -- ) a b = let x = Int64.sub a b in if x<0L then Int64.add x p else x

let long x = Int64.of_int x

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

  let len = n-m in
  let offs = n-m in
  let count = Array.make_matrix (len+1) (offs+1) 0L in

  count.(0).(0) <- 1L;
  for i=0 to offs-1 do
    for j = 0 to offs do
      let c = count.(i).(j) in
      if j+1 <= offs then count.(i+1).(j+1) <- count.(i+1).(j+1) ++ c;
      if j-1 >= 0 then count.(i+1).(j-1) <- count.(i+1).(j-1) ++ c;
    done
  done;

  let rec counts i delta depth = if i = m then (delta,depth) else
      let delta = delta + (if s.[i] = '(' then 1 else -1) in
      let depth = max depth (-delta) in
      counts (i+1) delta depth
  in

  let (delta, dlr) = counts 0 0 0 in
  let drl = max 0 (dlr + delta) in

  let lo = max (max 0 (drl - delta)) (max (-delta) dlr) in
  let hi = min offs (offs - delta) in

  let answer = sum 0 len (fun i ->
    sum lo hi (fun p -> count.(i).(p) ** count.(len-i).(p+delta)) 0L
  ) 0L in

  printf "%Ld\n" answer


Let $$$n$$$ be an integer. Consider all permutations on integers $$$1$$$ to $$$n$$$ in lexicographic order, and concatenate them into one big sequence $$$p$$$. For example, if $$$n = 3$$$, then $$$p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$$$. The length of this sequence will be $$$n \cdot n!$$$.Let $$$1 \leq i \leq j \leq n \cdot n!$$$ be a pair of indices. We call the sequence $$$(p_i, p_{i+1}, \dots, p_{j-1}, p_j)$$$ a subarray of $$$p$$$. Its length is defined as the number of its elements, i.e., $$$j - i + 1$$$. Its sum is the sum of all its elements, i.e., $$$\sum_{k=i}^j p_k$$$. You are given $$$n$$$. Find the number of subarrays of $$$p$$$ of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$. Since this number may be large, output it modulo $$$998244353$$$ (a prime number).

The only line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$), as described in the problem statement.

Output a single integer — the number of subarrays of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$, modulo $$$998244353$$$.

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 a = make 1000010 0L
let b = make 1000010 0L
let md = 998244353L
let () =
  let n = gi 0 in
  if n<=2L then printf "%Ld\n" n
  else (
    a.(1) <- n;
    a.(2) <- (n*(n-2L)) mod md;
    repi 3 (i32 n) (fun i ->
      b.(i) <- (i64 i * i64 (i-$2)) mod md
    );
    let pw = ref 1L in
    repi 3 (i32 n) (fun i ->
      pw := (!pw * (n-i64 i+3L)) mod md;
      a.(i) <- (!pw * b.(i32 n -$ i +$ 2)) mod md;
    );
    let s = ref 0L in
    repi 1 (2+$i32 n) (fun i ->
      s := ((!s + (i64 i * a.(i)) mod md) mod md);
    );
    printf "%Ld\n" !s;
  )


A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.

The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di < di + 1.

If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).

NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let n = read_int () in
  let m = read_int () in
  let dh = Array.init m (fun _ -> read_pair()) in

  let rec checkpairs i best = if i=m-1 then best else (
    (* check dh.(i) and dh.(i+1) *)
    let (t1,h1) = dh.(i) in
    let (t2,h2) = dh.(i+1) in
    let (h1, h2) = (min h1 h2, max h1 h2) in
    let dt = t2 - t1 in
    let dh = h2 - h1 in
    if dh > dt then -1 else (
      let e = dt - dh in
      let this_height = h2 + (e/2) in
      checkpairs (i+1) (max best this_height)
    )
  )
  in

  let best = checkpairs 0 0 in

  if best = -1 then printf "IMPOSSIBLE\n" else (
    let (t0,h0) = dh.(0) in
    let (tl,hl) = dh.(m-1) in

    let opt0 = h0 + (t0-1) in
    let opt1 = hl + (n-tl) in

    printf "%d\n" (max best (max opt0 opt1))
  )


All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of M people, who come to watch a movie, want necessarily to occupy M successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for M seats comes, the program should determine the row number x and the segment [yl, yr] of the seats numbers in this row, where yr - yl + 1 = M. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say,  — the row and the seat numbers of the most "central" seat. Then the function value of seats remoteness from the hall center is . If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number x is lower). If the variants are still multiple, it should choose the one with the minimum yl. If you did not get yet, your task is to simulate the work of this program.

The first line contains two integers N and K (1 ≤ N ≤ 1000, 1 ≤ K ≤ 99) — the amount of requests and the hall size respectively. The second line contains N space-separated integers Mi from the range [1, K] — requests to the program.

Output N lines. In the i-th line output «-1» (without quotes), if it is impossible to find Mi successive seats in one row, otherwise output three numbers x, yl, yr. Separate the numbers with a space.

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

let () =
  let n = read_int 0 in
  let m = read_int 0 in
  let a = Array.make_matrix m m false in
  for cc = 1 to n do
    let x = read_int 0 in
    let rec go i j (anss,ansi,ansj as ans) =
      if i = m then
        ans
      else if j > m-x then
        go (i+1) 0 ans
      else
        let rec go2 jj s =
          if jj-j = x then
            true,s+(abs (m/2-i) * x)
          else if a.(i).(jj) then
            false,0
          else
            go2 (jj+1) (s + abs (m/2-jj))
        in
        let ok,s = go2 j 0 in
        if ok then
          go i (j+1) (min (s,i,j) ans)
        else
          go i (j+1) ans
    in
    let anss,ansi,ansj = go 0 0 (max_int,-1,-1) in
    if anss = max_int then
      print_endline "-1"
    else (
      for j = ansj to ansj+x-1 do
        a.(ansi).(j) <- true
      done;
      Printf.printf "%d %d %d\n" (ansi+1) (ansj+1) (ansj+x)
    )
  done


In Aramic language words can only represent objects.Words in Aramic have special properties:   A word is a root if it does not contain the same letter more than once.  A root and all its permutations represent the same object.  The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".  Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.

Output one integer — the number of different objects mentioned in the given ancient Aramic script.

NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".

module SetChar = Set.Make(struct
    type t = char
    let compare = Char.compare
  end)

module SetRoot = Set.Make(SetChar)

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

let string_to_list (src: string): char list =
  let ret = ref [] in
  String.iter (fun c -> ret := c :: !ret) src;
  !ret

let rootize word =
  string_to_list word |> SetChar.of_list

let () =
  let n = Scanf.scanf "%d " (fun i -> i) in
  let words = list_init n (fun i -> Scanf.scanf " %s" (fun i -> i)) in
  let roots = List.map rootize words in
  let set_roots = SetRoot.of_list roots in
  SetRoot.cardinal set_roots |> string_of_int |> print_endline


Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.

The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home. The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby.  The i-th of the following n lines contains three integers xi, yi and vi ( - 100 ≤ xi, yi ≤ 100, 1 ≤ vi ≤ 100) — the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.

Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously.

let expon
= fun x1 x2 ->
  let foi = float_of_int in
  (foi (x1 - x2)) ** 2.0

let distance
= fun (x1, y1) (x2, y2) ->
  sqrt ((expon x1 x2) +. (expon y1 y2))

let _
= let a, b = Scanf.scanf "%d %d\n" (fun x y -> (x, y)) in
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let oneCase : unit -> float
  = fun () ->
    let x, y, v = Scanf.scanf "%d %d %d\n" (fun x y z -> (x, y, z)) in
    (distance (a, b) (x, y)) /. (float_of_int v)
  in
  let firstCase = oneCase () in
  let rec minmin : int -> float -> float
  = fun i m ->
    if i <= 0 then m
    else(
      let mm = min m (oneCase ()) in
      minmin (i - 1) mm
    )
  in
  let mmmm = (minmin (n - 1) firstCase) in
  Printf.printf "%.9f" mmmm

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

let ( -- ) (x1,y1) (x2,y2) = (x1-.x2, y1-.y2)
let ( ++ ) (x1,y1) (x2,y2) = (x1+.x2, y1+.y2)
let len (x,y) = sqrt(x*.x +. y*.y)

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let a = float (read_int()) in
  let b = float (read_int()) in
  let n = read_int () in
  let data = Array.init n (fun _ ->
    let x = float (read_int()) in
    let y = float (read_int()) in
    let v = float (read_int()) in
    ((x,y),v)
  ) in

  let answer = minf 0 (n-1) (fun i ->
    let (p,v) = data.(i) in
    let d = len (p -- (a,b)) in
    d /. v
  ) in

  printf "%.20f\n" answer

type point = (int * int)

let taxi_distance : point -> point -> int
= fun (x1, y1) (x2, y2) -> (abs (x1 - x2)) + (abs (y1 - y2))

let _
= let a, b = Scanf.scanf "%d %d\n" (fun x y -> (x, y)) in
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let oneCase : unit -> float
  = fun () ->
    let x, y, v = Scanf.scanf "%d %d %d\n" (fun x y z -> (x, y, z)) in
    (taxi_distance (a, b) (x, y) |> float_of_int) /. (float_of_int v)
  in
  let firstCase = oneCase () in
  let rec minmin : int -> float -> float
  = fun i m ->
    if i <= 0 then m
    else(
      let mm = min m (oneCase ()) in
      minmin (i - 1) mm
    )
  in
  let mmmm = (minmin (n - 1) firstCase) in
  Printf.printf "%.9f" mmmm

type point = (int * int)

let taxi_distance : point -> point -> int
= fun (x1, y1) (x2, y2) -> (abs (x1 - x2)) + (abs (y1 - y2))

let _
= let a, b = Scanf.scanf "%d %d\n" (fun x y -> (x, y)) in
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let oneCase : unit -> float
  = fun () ->
    let x, y, v = Scanf.scanf "%d %d %d\n" (fun x y z -> (x, y, z)) in
    (taxi_distance (a, b) (x, y) |> float_of_int) /. (float_of_int v)
  in
  let firstCase = oneCase () in
  let rec minmin : int -> float -> float
  = fun i m ->
    if i <= 0 then m
    else(
      let mm = min m (oneCase ()) in
      minmin (i - 1) mm
    )
  in
  let mmmm = (minmin (n - 1) firstCase) in
  Printf.printf "%.12f" mmmm


Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be «-1».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!

The first line contains two integers n, d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) —the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≤ ai ≤ 104), where ai represents the transaction in i-th day.

Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
type 'a pri_queue =
Node of 'a * 'a pri_queue * 'a pri_queue * int |
Null
exception Empty_Queue
let empty_queue = Null
let is_empty q = q = Null
let size q =
match q with
Null ->0 |
Node (_,_,_,n) ->n
let getmax h =
match h with
Null ->raise Empty_Queue |
Node (r,_,_,_) -> r
let set_root h r =
match h with

Null ->Node (r,Null,Null,1) |
Node (_,l,p,n) ->Node (r,l,p,n)
let rec put h x =
match h with
Null ->Node (x,Null,Null,1) |
Node (r,l,p,n) ->
if size l <= size p then
Node((max x r),(put l (min x r)),p,(n+1))
else
Node((max x r),l,(put p (min x r)),(n+1))
let rec removemax h =
match h with
Null ->raise Empty_Queue |
Node (_,Null,Null,_) ->Null |
Node (_,l,Null,_) ->l |
Node (_,Null,p,_) ->p |
Node (_,(Node (rl,_,_,_) as l),
(Node (rp,_,_,_) as p),n) ->
if rl >= rp then
Node (rl,removemax l,p,n - 1)
else
Node (rp,l,removemax p,n - 1);;
let n = scan_int() and d= scan_int()  and czy = ref 1 and dodaj = ref 0 and wyn = ref 0 and sum = ref 0 and q = ref empty_queue in
let tb = Array.make (n+1) 0 in
begin
  for i=1 to n do
    tb.(i) <- scan_int();
    sum := !sum + tb.(i);
    q := put !q (!sum, i)
  done;
  sum := 0;
  for i=1 to n do
    if tb.(i) <> 0 then sum := !sum + tb.(i)
    else if !sum < 0 then begin
      let a = ref (getmax !q) in
        while (snd(!a)) < i do q := removemax !q; a := getmax !q done;
      wyn := !wyn +1;
      sum := !sum + (d - (fst(!a)) - !dodaj);
      dodaj := d - fst(!a);
      if !sum < 0 then czy := 0 end;
    if !sum > d then czy := 0
  done;
  if !czy = 0 then print_int (-1)
  else print_int (!wyn)
end

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

let n = scan_int () and d = scan_int();;

let x = Array.make n 0 and lim = Array.make n Int32.zero;;
let sumek = ref Int32.zero;;

for i = 0 to n - 1 do
  x.(i) <- scan_int();
  sumek := Int32.add !sumek (Int32.of_int x.(i));
  lim.(i) <- Int32.sub (Int32.of_int d) (!sumek);
done;;

for i = n - 2 downto 0 do
  lim.(i) <- min lim.(i) lim.(i + 1);
done;;

let koncz () =
  print_string("-1");
  exit 0;;

if lim.(0) < Int32.zero then koncz();;

let wyn = ref 0 and dod = ref Int32.zero;;
sumek := Int32.zero;
for i = 0 to n - 1 do
  if x.(i) == 0 && Int32.add !sumek !dod < Int32.zero then begin
    dod := lim.(i);
    incr wyn;
    if Int32.add !sumek !dod < Int32.zero then koncz();
  end;
  sumek := Int32.add !sumek (Int32.of_int x.(i));
done;;

print_int !wyn;;

(*
4 1000000000
-100 0 -250000000 0
*)

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

let n = scan_int () and d = scan_int();;

let x = Array.make n 0 and lim = Array.make n 0;;
let sumek = ref 0;;

for i = 0 to n - 1 do
  x.(i) <- scan_int();
  sumek := !sumek + x.(i);
  lim.(i) <- d - !sumek;
done;;

for i = n - 2 downto 0 do
  lim.(i) <- min lim.(i) lim.(i + 1);
done;;

let koncz () =
  print_string("-1");
  exit 0;;

if lim.(0) < 0 then koncz();;

let wyn = ref 0 and dod = ref 0;;
sumek := 0;
for i = 0 to n - 1 do
  if x.(i) == 0 && !sumek + !dod < 0 then begin
    dod := lim.(i);
    incr wyn;
    if !sumek + !dod < 0 then koncz();
  end;
  sumek := !sumek + x.(i);
done;;

print_int !wyn;;

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

let n = scan_int () and d = scan_int();;

let x = Array.make n 0 and lim = Array.make n 0;;
let sumek = ref 0;;

for i = 0 to n - 1 do
  x.(i) <- scan_int();
  sumek := !sumek + x.(i);
  lim.(i) <- max d (d - !sumek);
done;;

for i = n - 2 downto 0 do
  lim.(i) <- min lim.(i) lim.(i + 1);
done;;

let koncz () =
  print_string("-1");
  exit 0;;

if lim.(0) < 0 then koncz();;

let wyn = ref 0 and dod = ref 0;;
sumek := 0;
for i = 0 to n - 1 do
  if x.(i) == 0 && !sumek + !dod < 0 then begin
    dod := lim.(i);
    incr wyn;
    if !sumek + !dod < 0 then koncz();
  end;
  sumek := !sumek + x.(i);
done;;

print_int !wyn;;

(*
4 1000000000
-100 0 -250000000 0
*)

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

let n = scan_int () and d = scan_int();;

let x = Array.make n 0 and lim = Array.make n 0;;
let sumek = ref 0;;

for i = 0 to n - 1 do
  x.(i) <- scan_int();
  sumek := !sumek + x.(i);
  lim.(i) <- d - !sumek;
done;;

for i = n - 2 downto 0 do
  lim.(i) <- min lim.(i) lim.(i + 1);
done;;

let koncz =
  print_string("-1");
  exit 0;;

if lim.(0) < 0 then koncz

let wyn = ref 0 and dod = ref 0;;
sumek := 0;
for i = 0 to n - 1 do
  if x.(i) == 0 && !sumek + !dod < 0 then begin
    dod := lim.(i);
    incr wyn;
    if !sumek + !dod < 0 then koncz
  end;
  sumek := !sumek + x.(i);
done;;

print_int !wyn;;

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

let n = scan_int () and d = scan_int();;

let x = Array.make n 0 and lim = Array.make n 0;;
let sumek = ref 0;;

for i = 0 to n - 1 do
  x.(i) <- scan_int();
  sumek := !sumek + x.(i);
  lim.(i) <- min d (d - !sumek);
done;;

for i = n - 2 downto 0 do
  lim.(i) <- min lim.(i) lim.(i + 1);
done;;

let koncz () =
  print_string("-1");
  exit 0;;

if lim.(0) < 0 then koncz();;

let wyn = ref 0 and dod = ref 0;;
sumek := 0;
for i = 0 to n - 1 do
  if x.(i) == 0 && !sumek + !dod < 0 then begin
    dod := lim.(i);
    incr wyn;
    if !sumek + !dod < 0 then koncz();
  end;
  sumek := !sumek + x.(i);
done;;

print_int !wyn;;

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

let n = scan_int () and d = scan_int();;

let x = Array.make n 0 and lim = Array.make n 0;;
let sumek = ref 0;;

for i = 0 to n - 1 do
  x.(i) <- scan_int();
  sumek := !sumek + x.(i);
  lim.(i) <- d - !sumek;
done;;

for i = n - 2 downto 0 do
  lim.(i) <- min lim.(i) lim.(i + 1);
done;;

let wyn = ref 0 and dod = ref 0;;
sumek := 0;
for i = 0 to n - 1 do
  if x.(i) == 0 && !sumek + !dod < 0 then begin
    dod := lim.(i);
    incr wyn;
    if !sumek + !dod < 0 then begin
      print_string("-1");
      exit 0;
    end;
  end;
  sumek := !sumek + x.(i);
done;;

print_int !wyn;;


A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ 109) — the borders of the i-th segment. It is guaranteed that no two segments coincide.

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.

(* Codeforces 242B BigOtres done *)

open String;;
open Int64;;

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

let rec checkOtr i n mna mxb idx =
	if i > n then idx
	else
		let a = grl() in
		let b = grl() in
		if a <= mna && mxb <= b then checkOtr (i+1) n a b i
		else
			let idx = if mna <= a && b <= mxb then idx else -1 in
			let mna = min a mna in
			let mxb = max b mxb in
			checkOtr (i+1) n mna mxb idx;;

let main () =
	let n = gr() in
	let a = grl() in
	let b = grl() in
	let idx = checkOtr 2 n a b 1 in
	print_int idx;;

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 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 input = Array.init n
    (fun _ -> let l = read_int() in let r = read_int() in (l,r)) in
  let minleft = minf 0 (n-1) (fun i -> let (l,r)=input.(i) in l) in
  let maxright = maxf 0 (n-1) (fun i -> let (l,r)=input.(i) in r) in

  let rec findit i = if i=n then None else
    let (l,r) = input.(i) in
      if l<=minleft && r>=maxright then Some i else findit (i+1)
  in

  let ans =
    match findit 0 with
      |	None -> -1
      | Some i -> i+1
  in
    Printf.printf "%d\n" ans


DZY loves strings, and he enjoys collecting them.In China, many people like to use strings containing their names' initials, for example: xyz, jcvb, dzy, dyh.Once DZY found a lucky string s. A lot of pairs of good friends came to DZY when they heard about the news. The first member of the i-th pair has name ai, the second one has name bi. Each pair wondered if there is a substring of the lucky string containing both of their names. If so, they want to find the one with minimum length, which can give them good luck and make their friendship last forever.Please help DZY for each pair find the minimum length of the substring of s that contains both ai and bi, or point out that such substring doesn't exist.A substring of s is a string slsl + 1... sr for some integers l, r (1 ≤ l ≤ r ≤ |s|). The length of such the substring is (r - l + 1).A string p contains some another string q if there is a substring of p equal to q.

The first line contains a string s (1 ≤ |s| ≤ 50000). The second line contains a non-negative integer q (0 ≤ q ≤ 100000) — the number of pairs. Each of the next q lines describes a pair, the line contains two space-separated strings ai and bi (1 ≤ |ai|, |bi| ≤ 4). It is guaranteed that all the strings only consist of lowercase English letters.

For each pair, print a line containing a single integer — the minimum length of the required substring. If there is no such substring, output -1.

NoteThe shortest substrings in the first sample are: xyz, dyhduxyz.The shortest substrings in the second sample are: ca, abc and abd.The shortest substrings in the third sample are: baabca and abaa.

(* Sketch of my algorithm for this problem.

   Do a scan of the input string and compute for each query string a
   sorted list of the indices of the centers of these strings (the
   centers could be half integers so you probably double them to make
   them integers).  Then convert these lists into arrays of indices
   (so we can do binary search on them).

   Now, answering a query consists of taking the two corresponding
   lists A and B, and finding the closest pair (a,b) where a is from A
   and b is from B.  We can do this by different methods depending on
   the sizes A and B.  If |A| and |B| are about equal, we can just do
   a linear scan to find the closest pair.  If, say A is a lot smaller,
   then we can lookup each element of A in B using binary search.

   Also, we use a hash table to ensure that the same query is only
   analyzed once.

   Notice that the input string can contain at most 200K substrings of
   length 1,2,3, or 4.  So the total length of all the lists computed
   above is at most 200K.  The worst case will occur when there are
   about 500 query strings that occur about 500 times each.  So each
   query will take O(1000) to analyze.  So the whole algorithm is O(100M).

   Looking at the match editorial later (http://codeforces.com/blog/entry/12959).
   They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =
   O(15M).  But it loses at least a factor of four because they are
   consisering query strings of length at most 1.  So I don't think
   the algorithm is actually different.

*)

open Printf
open Scanf

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

let l2n c = (int_of_char c) - (int_of_char 'a')

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

let str_to_numb s =
  let n = String.length s in
  let rec loop i ac = if i=n then ac else
      loop (i+1) (26 * ac + (l2n s.[i]))
  in
  let code = loop 0 0 in
  code + [|0;26;26+26*26;26+26*26+26*26*26|].(n-1)

let () =
  let ns = (str_to_numb "zzzz") + 1 in
  let is_query = Array.make ns false in
  let s = read_string () in
  let n = String.length s in
  let q = read_int () in
  let query = Array.init q (
    fun _ ->
      let a = read_string() in
      let b = read_string() in
      let (a,b) = (min a b, max a b) in
      let (an,bn) = (str_to_numb a, str_to_numb b) in
      is_query.(an) <- true;
      is_query.(bn) <- true;
      (a,an,b,bn)
  ) in

  let indices = Array.make ns [] in

  for l=1 to 4 do
    for i=n-l downto 0 do
      let t = String.sub s i l in
      let index = 2*i + l - 1 in
      let tn = str_to_numb t in
      if is_query.(tn) then indices.(tn) <- index :: indices.(tn);
    done
  done;

  let index_arrays = Array.make ns [||] in
  for i=0 to ns-1 do
    if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)
  done;

  let query_table = Hashtbl.create 10 in

  let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in

  let bsearch a b la lb =
    let rec bs x i j =
      (* ind hyp is i<j && b.(i) < x && x < b.(j) *)
      if i=j-1 then min (x-b.(i)) (b.(j)-x) else
	let m = (i+j)/2 in
	if x=b.(m) then 0
	else if x<b.(m) then bs x i m else bs x m j
    in
    minf 0 (la-1) (
      fun l ->
	let x = a.(l) in
	if x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)
    )
  in

  let linsearch a b la lb =
    let rec loop i j ac = if i=la || j=lb then ac
      else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))
      else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))
      else 0
    in
    loop 0 0 max_int
  in

  let solve_query a an b bn =
    let la = Array.length index_arrays.(an) in
    let lb = Array.length index_arrays.(bn) in
    let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in
    (* decide which will be faster: linear scan or binary search *)
    if la=0 || lb=0 then -1 else
      let do_bsearch = la * (log lb) <= la + lb in
      let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in
      let (alen,blen) = (String.length a, String.length b) in
      let leftend = min (-alen) (-centerdist -blen) in
      let rightend = max alen (-centerdist + blen) in
      (rightend - leftend) / 2
  in

  for i=0 to q-1 do
    let (a,an,b,bn) = query.(i) in
    if Hashtbl.mem query_table (an,bn)
    then printf "%d\n" (Hashtbl.find query_table (an,bn))
    else
      let ans = solve_query a an b bn in
      Hashtbl.add query_table (an,bn) ans;
      printf "%d\n" ans
  done;

(* Sketch of my algorithm for this problem.

   Do a scan of the input string and compute for each query string a
   sorted list of the indices of the centers of these strings (the
   centers could be half integers so you probably double them to make
   them integers).  Then convert these lists into arrays of indices
   (so we can do binary search on them).

   Now, answering a query consists of taking the two corresponding
   lists A and B, and finding the closest pair (a,b) where a is from A
   and b is from B.  We can do this by different methods depending on
   the sizes A and B.  If |A| and |B| are about equal, we can just do
   a linear scan to find the closest pair.  If, say A is a lot smaller,
   then we can lookup each element of A in B using binary search.

   Also, we use a hash table to ensure that the same query is only
   analyzed once.

   Notice that the input string can contain at most 200K substrings of
   length 1,2,3, or 4.  So the total length of all the lists computed
   above is at most 200K.  The worst case will occur when there are
   about 500 query strings that occur about 500 times each.  So each
   query will take O(1000) to analyze.  So the whole algorithm is O(100M).

   Looking at the match editorial later (http://codeforces.com/blog/entry/12959).
   They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =
   O(15M).  But it loses at least a factor of four because they are
   consisering query strings of length at most 1.  So I don't think
   the algorithm is actually different.

*)

open Printf
open Scanf

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

let l2n c = (int_of_char c) - (int_of_char 'a')

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

let str_to_numb s =
  let n = String.length s in
  let rec loop i ac = if i=n then ac else
      loop (i+1) (26 * ac + (l2n s.[i]))
  in
  loop 1 (1 + (l2n s.[0]))

let () =
  let ns = (str_to_numb "zzzz") + 1 in
  let is_query = Array.make ns false in
  let s = read_string () in
  let n = String.length s in
  let q = read_int () in
  let query = Array.init q (
    fun _ ->
      let a = read_string() in
      let b = read_string() in
      let (a,b) = (min a b, max a b) in
      let (an,bn) = (str_to_numb a, str_to_numb b) in
      is_query.(an) <- true;
      is_query.(bn) <- true;
      (a,an,b,bn)
  ) in

  let indices = Array.make ns [] in

  for l=1 to 4 do
    for i=n-l downto 0 do
      let t = String.sub s i l in
      let index = 2*i + l - 1 in
      let tn = str_to_numb t in
      if is_query.(tn) then indices.(tn) <- index :: indices.(tn);
    done
  done;

  let index_arrays = Array.make ns [||] in
  for i=0 to ns-1 do
    if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)
  done;

  let query_table = Hashtbl.create 10 in

  let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in

  let bsearch a b la lb =
    let rec bs x i j =
      (* ind hyp is i<j && b.(i) < x && x < b.(j) *)
      if i=j-1 then min (x-b.(i)) (b.(j)-x) else
	let m = (i+j)/2 in
	if x=b.(m) then 0
	else if x<b.(m) then bs x i m else bs x m j
    in
    minf 0 (la-1) (
      fun l ->
	let x = a.(l) in
	if x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)
    )
  in

  let linsearch a b la lb =
    let rec loop i j ac = if i=la || j=lb then ac
      else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))
      else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))
      else 0
    in
    loop 0 0 max_int
  in

  let solve_query a an b bn =
    let la = Array.length index_arrays.(an) in
    let lb = Array.length index_arrays.(bn) in
    let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in
    (* decide which will be faster: linear scan or binary search *)
    if la=0 || lb=0 then -1 else
      let do_bsearch = la * (log lb) <= la + lb in
(*      let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in *)
      let centerdist = linsearch index_arrays.(an) index_arrays.(bn) la lb in
      let (alen,blen) = (String.length a, String.length b) in
      let leftend = min (-alen) (-centerdist -blen) in
      let rightend = max alen (-centerdist + blen) in
      (rightend - leftend) / 2
  in

  for i=0 to q-1 do
    let (a,an,b,bn) = query.(i) in
    if Hashtbl.mem query_table (an,bn)
    then printf "%d\n" (Hashtbl.find query_table (an,bn))
    else
      let ans = solve_query a an b bn in
      Hashtbl.add query_table (an,bn) ans;
      printf "%d\n" ans
  done;

(* Sketch of my algorithm for this problem.

   Do a scan of the input string and compute for each query string a
   sorted list of the indices of the centers of these strings (the
   centers could be half integers so you probably double them to make
   them integers).  Then convert these lists into arrays of indices
   (so we can do binary search on them).

   Now, answering a query consists of taking the two corresponding
   lists A and B, and finding the closest pair (a,b) where a is from A
   and b is from B.  We can do this by different methods depending on
   the sizes A and B.  If |A| and |B| are about equal, we can just do
   a linear scan to find the closest pair.  If, say A is a lot smaller,
   then we can lookup each element of A in B using binary search.

   Also, we use a hash table to ensure that the same query is only
   analyzed once.

   Notice that the input string can contain at most 200K substrings of
   length 1,2,3, or 4.  So the total length of all the lists computed
   above is at most 200K.  The worst case will occur when there are
   about 500 query strings that occur about 500 times each.  So each
   query will take O(1000) to analyze.  So the whole algorithm is O(100M).

   Looking at the match editorial later (http://codeforces.com/blog/entry/12959).
   They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =
   O(15M).  But it loses at least a factor of four because they are
   consisering query strings of length at most 1.  So I don't think
   the algorithm is actually different.

*)

open Printf
open Scanf

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

let l2n c = (int_of_char c) - (int_of_char 'a')

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

let str_to_numb s =
  let n = String.length s in
  let rec loop i ac = if i=n then ac else
      loop (i+1) (26 * ac + (l2n s.[i]))
  in
  loop 1 (1 + (l2n s.[0]))

let () =
  let ns = (str_to_numb "zzzz") + 1 in
  let is_query = Array.make ns false in
  let s = read_string () in
  let n = String.length s in
  let q = read_int () in
  let query = Array.init q (
    fun _ ->
      let a = read_string() in
      let b = read_string() in
      let (a,b) = (min a b, max a b) in
      let (an,bn) = (str_to_numb a, str_to_numb b) in
      is_query.(an) <- true;
      is_query.(bn) <- true;
      (a,an,b,bn)
  ) in

  let indices = Array.make ns [] in

  for l=1 to 4 do
    for i=n-l downto 0 do
      let t = String.sub s i l in
      let index = 2*i + l - 1 in
      let tn = str_to_numb t in
      if is_query.(tn) then indices.(tn) <- index :: indices.(tn);
    done
  done;

  let index_arrays = Array.make ns [||] in
  for i=0 to ns-1 do
    if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)
  done;

  let query_table = Hashtbl.create 10 in

  let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in

  let bsearch a b la lb =
    let rec bs x i j =
      (* ind hyp is i<j && b.(i) < x && x < b.(j) *)
      if i=j-1 then min (x-b.(i)) (b.(j)-x) else
	let m = (i+j)/2 in
	if x=b.(m) then 0
	else if x<b.(m) then bs x i m else bs x m j
    in
    minf 0 (la-1) (
      fun l ->
	let x = a.(l) in
	if x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)
    )
  in

  let linsearch a b la lb =
    let rec loop i j ac = if i=la || j=lb then ac
      else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))
      else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))
      else 0
    in
    loop 0 0 max_int
  in

  let solve_query a an b bn =
    let la = Array.length index_arrays.(an) in
    let lb = Array.length index_arrays.(bn) in
    let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in
    (* decide which will be faster: linear scan or binary search *)
    if la=0 || lb=0 then -1 else
      let do_bsearch = la * (log lb) <= la + lb in
      let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in
      let (alen,blen) = (String.length a, String.length b) in
      let leftend = min (-alen) (-centerdist -blen) in
      let rightend = max alen (-centerdist + blen) in
      (rightend - leftend) / 2
  in

  for i=0 to q-1 do
    let (a,an,b,bn) = query.(i) in
    if Hashtbl.mem query_table (an,bn)
    then printf "%d\n" (Hashtbl.find query_table (an,bn))
    else
      let ans = solve_query a an b bn in
      Hashtbl.add query_table (an,bn) ans;
      printf "%d\n" ans
  done;

(* Sketch of my algorithm for this problem.

   Do a scan of the input string and compute for each query string a
   sorted list of the indices of the centers of these strings (the
   centers could be half integers so you probably double them to make
   them integers).  Then convert these lists into arrays of indices
   (so we can do binary search on them).

   Now, answering a query consists of taking the two corresponding
   lists A and B, and finding the closest pair (a,b) where a is from A
   and b is from B.  We can do this by different methods depending on
   the sizes A and B.  If |A| and |B| are about equal, we can just do
   a linear scan to find the closest pair.  If, say A is a lot smaller,
   then we can lookup each element of A in B using binary search.

   Also, we use a hash table to ensure that the same query is only
   analyzed once.

   Notice that the input string can contain at most 200K substrings of
   length 1,2,3, or 4.  So the total length of all the lists computed
   above is at most 200K.  The worst case will occur when there are
   about 500 query strings that occur about 500 times each.  So each
   query will take O(1000) to analyze.  So the whole algorithm is O(100M).

   Looking at the match editorial later (http://codeforces.com/blog/entry/12959).
   They give a running time of O(S Sqrt(Q)) which means O(50K * 300) =
   O(15M).  But it loses at least a factor of four because they are
   consisering query strings of length at most 1.  So I don't think
   the algorithm is actually different.

*)

open Printf
open Scanf

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

let l2n c = (int_of_char c) - (int_of_char 'a')

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

let str_to_numb s =
  let n = String.length s in
  let rec loop i ac = if i=n then ac else
      loop (i+1) (26 * ac + (l2n s.[i]))
  in
  loop 1 (1 + (l2n s.[0]))

let () =
  let ns = (str_to_numb "zzzz") + 1 in
  let is_query = Array.make ns false in
  let s = read_string () in
  let n = String.length s in
  let q = read_int () in
  let query = Array.init q (
    fun _ ->
      let a = read_string() in
      let b = read_string() in
      let (a,b) = (min a b, max a b) in
      let (an,bn) = (str_to_numb a, str_to_numb b) in
      is_query.(an) <- true;
      is_query.(bn) <- true;
      (a,an,b,bn)
  ) in

  let indices = Array.make ns [] in

  for l=1 to 4 do
    for i=n-l downto 0 do
      let t = String.sub s i l in
      let index = 2*i + l - 1 in
      let tn = str_to_numb t in
      if is_query.(tn) then indices.(tn) <- index :: indices.(tn);
    done
  done;

  let index_arrays = Array.make ns [||] in
  for i=0 to ns-1 do
    if is_query.(i) then index_arrays.(i) <- Array.of_list indices.(i)
  done;

  let query_table = Hashtbl.create 10 in

  let rec log x = if x<=1 then 0 else 1 + (log (x lsr 1)) in

  let bsearch a b la lb =
    let rec bs x i j =
      (* ind hyp is i<j && b.(i) < x && x < b.(j) *)
      if i=j-1 then min (x-b.(i)) (b.(j)-x) else
	let m = (i+j)/2 in
	if x=b.(m) then 0
	else if x<b.(m) then bs x i m else bs x m j
    in
    minf 0 (la-1) (
      fun l ->
	let x = a.(l) in
	if x<=b.(0) then b.(0) - x else if x>=b.(lb-1) then x-b.(lb-1) else bs x 0 (lb-1)
    )
  in

  let linsearch a b la lb =
    let rec loop i j ac = if i=la || j=lb then ac
      else if a.(i) < b.(j) then loop (i+1) j (min ac (b.(j) - a.(i)))
      else if a.(i) > b.(j) then loop i (j+1) (min ac (a.(i) - b.(j)))
      else 0
    in
    loop 0 0 max_int
  in

  let solve_query a an b bn =
    let la = Array.length index_arrays.(an) in
    let lb = Array.length index_arrays.(bn) in
    let (la,lb,a,b,an,bn) = if la < lb then (la,lb,a,b,an,bn) else (lb,la,b,a,bn,an) in
    (* decide which will be faster: linear scan or binary search *)
    if la=0 || lb=0 then -1 else
      let do_bsearch = la * (log lb) <= la + lb in
(*      let centerdist = (if do_bsearch then bsearch else linsearch) index_arrays.(an) index_arrays.(bn) la lb in *)
      let centerdist = bsearch index_arrays.(an) index_arrays.(bn) la lb in
      let (alen,blen) = (String.length a, String.length b) in
      let leftend = min (-alen) (-centerdist -blen) in
      let rightend = max alen (-centerdist + blen) in
      (rightend - leftend) / 2
  in

  for i=0 to q-1 do
    let (a,an,b,bn) = query.(i) in
    if Hashtbl.mem query_table (an,bn)
    then printf "%d\n" (Hashtbl.find query_table (an,bn))
    else
      let ans = solve_query a an b bn in
      Hashtbl.add query_table (an,bn) ans;
      printf "%d\n" ans
  done;


You are given a chess board with $$$n$$$ rows and $$$n$$$ columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board.A knight is a chess piece that can attack a piece in cell ($$$x_2$$$, $$$y_2$$$) from the cell ($$$x_1$$$, $$$y_1$$$) if one of the following conditions is met:  $$$|x_1 - x_2| = 2$$$ and $$$|y_1 - y_2| = 1$$$, or  $$$|x_1 - x_2| = 1$$$ and $$$|y_1 - y_2| = 2$$$. Here are some examples of which cells knight can attack. In each of the following pictures, if the knight is currently in the blue cell, it can attack all red cells (and only them).  A duel of knights is a pair of knights of different colors such that these knights attack each other. You have to put a knight (a white one or a black one) into each cell in such a way that the number of duels is maximum possible.

The first line contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of rows (and columns) in the board.

Print $$$n$$$ lines with $$$n$$$ characters in each line. The $$$j$$$-th character in the $$$i$$$-th line should be W, if the cell ($$$i$$$, $$$j$$$) contains a white knight, or B, if it contains a black knight. The number of duels should be maximum possible. If there are multiple optimal answers, print any of them.

NoteIn the first example, there are $$$8$$$ duels:  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$3$$$, $$$2$$$);  the white knight in ($$$1$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$1$$$) attacks the black knight in ($$$2$$$, $$$3$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$1$$$, $$$2$$$);  the white knight in ($$$3$$$, $$$3$$$) attacks the black knight in ($$$2$$$, $$$1$$$).

let neighbors limit i j =
  let delta = [(2,1);(2,-1);(-2,1);(-2,-1);(1,2);(1,-2);(-1,-2);(-1,2)] in
  let l = List.map (fun (dx,dy) -> (dx+i,dy+j)) delta in
  List.filter (fun (i,j) -> i >= 0 && i < limit && j >= 0 && j < limit) l

let rec check limit array b (i,j) =
  match array.(i).(j) with
  | _, `Unseen ->
    array.(i).(j) <- (b, `Seen);
    let l = neighbors limit i j in
    List.iter (check limit array (not b)) l
  | _ -> ()

let _ =
  let n = int_of_string (input_line stdin) in
  let array = Array.make_matrix n n (false,`Unseen) in
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      match array.(i).(j) with
      | b,`Unseen ->
        check n array (not b) (i,j)
      | _ -> ()
    done;
  done;
  let rec pp_line fmt line =
    let to_string b = if b then "W" else "B" in
    match line with
    | []       -> ()
    | (b,_)::l -> Format.fprintf fmt "%s%a" (to_string b) pp_line l
  in
  let rec pp_arr fmt array =
    match array with
    | [] -> ()
    | line::array ->
      let line = Array.to_list line in
      Format.fprintf fmt "%a@.%a" pp_line line pp_arr array;
  in
  Format.printf "%a@." pp_arr (Array.to_list array)


Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1, m), then goes down 2 rows to (3, m), then goes left to (3, 1) and so on.Your task is to draw this snake for Fox Ciel: the empty cells should be represented as dot characters ('.') and the snake cells should be filled with number signs ('#').Consider sample tests in order to understand the snake pattern.

The only line contains two integers: n and m (3 ≤ n, m ≤ 50).  n is an odd number.

Output n lines. Each line should contain a string consisting of m characters. Do not output spaces.

let input () = Scanf.scanf "%d %d" (fun n m -> (n, m))

let get_parity row =
    if row mod 2 = 0
        then
            if row / 2 mod 2 = 0
            then
                `even_left
            else
                `even_right
        else
            `odd

let make_line parity m =
    match parity with
    |`even_left -> "#" ^ (String.make (m - 1) '.')
    |`even_right -> (String.make (m - 1) '.') ^ "#"
    |`odd -> String.make m '#'

let solve (n, m) =
    let rec loop i =
        if i <= n
        then
            let line = make_line (get_parity i) m in
            Printf.printf "%s\n" line;
            loop (i + 1)
        else
            ()
    in loop 1

let () = solve (input ())

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

let () =
  let n = read_int () in
  let m = read_int () in
  let rec solve pos str m = function
    | 0 -> str
    | n ->
        if (n mod 2) = 1 then
          solve pos (str ^ (String.make m '#') ^ "\n") m (n - 1)
        else
          if pos then
            solve false (str ^ (String.make (m - 1) '.') ^ "#\n") m (n - 1)
          else
            solve true (str ^ "#" ^ (String.make (m - 1) '.') ^ "\n") m (n - 1)
  in Printf.printf "%s" (solve true "" m n)

let () =
    Scanf.scanf "%d %d\n" (fun n m ->
        let line = String.make m '#' in
        let empty = String.make (m - 1) '.' in
        for i = 1 to n do
            if i mod 2 = 1 then
                print_endline line
            else
                if i mod 4 = 0 then begin
                    print_char '#';
                    print_endline empty
                end else begin
                    print_string empty;
                    print_endline "#"
                end
        done
    )

let id x = x in

let rec range lo hi =
                if lo >= hi then []
                else lo :: range (lo + 1) hi in

let n = Scanf.scanf " %d" id in
let m = Scanf.scanf " %d" id in

let rec stringn s n = match n with
1 -> s
| _ -> s ^ stringn s (n - 1) in

let get i = if i mod 2 = 0 then stringn "#" m
            else if i mod 4 = 1 then stringn "." (m - 1) ^ "#"
            else "#" ^ stringn "." (m - 1) in

n
|> range 0
|> List.map get
|> List.iter print_endline ;;
(*
Printf.printf " %d %d" n m ;; *)


You are given n integers a1, a2, ..., an. Find the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2 (i. e. some integer x exists so that ai + aj = 2x).

The first line contains the single positive integer n (1 ≤ n ≤ 105) — the number of integers. The second line contains n positive integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print the number of pairs of indexes i, j (i < j) that ai + aj is a power of 2.

NoteIn the first example the following pairs of indexes include in answer: (1, 4) and (2, 4).In the second example all pairs of indexes (i, j) (where i < j) include in answer.

(* Darooha style *)
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 ( *| ) = Int64.mul
let ( +| ) = Int64.add
let ( -| ) = Int64.sub
let ( /| ) = Int64.div
let ( %| ) = Int64.rem
*)
let long x = Int64.of_int x
let short x = Int64.to_int x

open Printf
open Scanf

let get h k =
    try Hashtbl.find h k with
    | Not_found -> 0

let set h k v = Hashtbl.replace h k v

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

let () =
    let n = read_int() in
    let a = Array.make n 0 in
    for i = 0 to n - 1 do
        a.(i) <- read_int()
    done;
    let h = Hashtbl.create n in
    for i = 0 to n - 1 do
        set h a.(i) (get h a.(i) + 1)
    done;
    let res = ref 0L in
    Hashtbl.iter (fun k v ->
		let pw2 = ref 1 in
		for _ = 1 to 30 do
			pw2 := !pw2 * 2;
			let k2 = !pw2 - k in
			if k < k2 then
				res := (long v)  ** (long (get h (!pw2 - k))) ++ !res
			else if k = k2 then
				res := (long v)  ** (long (v - 1)) // 2L ++ !res
		done
	) h;
    printf "%Ld\n" !res

(* Darooha style
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 ( *| ) = Int64.mul
let ( +| ) = Int64.add
let ( -| ) = Int64.sub
let ( /| ) = Int64.div
let ( %| ) = Int64.rem

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

open Printf
open Scanf

let get h k =
    try Hashtbl.find h k with
    | Not_found -> 0

let set h k v = Hashtbl.replace h k v

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

let () =
    let n = read_int() in
    let a = Array.make n 0 in
    for i = 0 to n - 1 do
        a.(i) <- read_int()
    done;
    let h = Hashtbl.create n in
    for i = 0 to n - 1 do
        set h a.(i) (get h a.(i) + 1)
    done;
    let res = ref 0L in
    Hashtbl.iter (fun k v ->
		let pw2 = ref 1 in
		for _ = 1 to 30 do
			pw2 := !pw2 * 2;
			let k2 = !pw2 - k in
			if k < k2 then
				res := (long v)  *| (long (get h (!pw2 - k))) +| !res
			else if k = k2 then
				res := (long v)  *| (long (v - 1)) /| 2L +| !res
		done
	) h;
    printf "%Ld\n" !res

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

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

open Printf
open Scanf

let get h k =
    try Hashtbl.find h k with
    | Not_found -> 0

let set h k v = Hashtbl.replace h k v

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

let () =
    let n = read_int() in
    let a = Array.make n 0 in
    for i = 0 to n - 1 do
        a.(i) <- read_int()
    done;
    let h = Hashtbl.create n in
    for i = 0 to n - 1 do
        set h a.(i) (get h a.(i) + 1)
    done;
    let res = ref 0L in
    Hashtbl.iter (fun k v ->
		let pw2 = ref 1 in
		for _ = 1 to 30 do
			pw2 := !pw2 * 2;
			let k2 = !pw2 - k in
			if k < k2 then
				res := (long v)  ** (long (get h (!pw2 - k))) ++ !res
			else if k = k2 then
				res := (long v)  ** (long (v - 1)) // 2L ++ !res
		done
	) h;
    printf "%Ld\n" !res

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

(*
let ( *| ) a b = Int64.mul
let ( +| ) a b = Int64.add
let ( -| ) a b = Int64.sub
let ( /| ) a b = Int64.div
let ( %| ) a b = Int64.rem
*)
let long x = Int64.of_int x
let short x = Int64.to_int x

open Printf
open Scanf

let get h k =
    try Hashtbl.find h k with
    | Not_found -> 0

let set h k v = Hashtbl.replace h k v

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

let () =
    let n = read_int() in
    let a = Array.make n 0 in
    for i = 0 to n - 1 do
        a.(i) <- read_int()
    done;
    let h = Hashtbl.create n in
    for i = 0 to n - 1 do
        set h a.(i) (get h a.(i) + 1)
    done;
    let res = ref 0L in
    Hashtbl.iter (fun k v ->
		let pw2 = ref 1 in
		for _ = 1 to 30 do
			pw2 := !pw2 * 2;
			let k2 = !pw2 - k in
			if k < k2 then
				res := (long v)  ** (long (get h (!pw2 - k))) ++ !res
			else if k = k2 then
				res := (long v)  ** (long (v - 1)) // 2L ++ !res
		done
	) h;
    printf "%Ld\n" !res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let ht = Hashtbl.create n in
  let _ =
    for i = 0 to n - 1 do
      let c =
	try
	  Hashtbl.find ht a.(i)
	with
	  | Not_found -> 0
      in
	Hashtbl.replace ht a.(i) (c + 1)
    done
  in
  let res = ref 0L in
    Hashtbl.iter
      (fun x c ->
	 for i = 1 to 30 do
	   try
	     if 1 lsl i - x = x
	     then res := !res +| Int64.of_int c *| Int64.of_int (c - 1)
	     else
	       let c2 = Hashtbl.find ht (1 lsl i - x) in
		 res := !res +| Int64.of_int c *| Int64.of_int c2;
	   with
	     | Not_found -> ()
	 done;
      ) ht;
    res := !res /| 2L;
    Printf.printf "%Ld\n" !res


There is a square field of size $$$n \times n$$$ in which two cells are marked. These cells can be in the same row or column.You are to mark two more cells so that they are the corners of a rectangle with sides parallel to the coordinate axes.For example, if $$$n=4$$$ and a rectangular field looks like this (there are asterisks in the marked cells):$$$$$$ \begin{matrix} . & . & * & . \\ . & . & . & . \\ * & . & . & . \\ . & . & . & . \\ \end{matrix} $$$$$$Then you can mark two more cells as follows$$$$$$ \begin{matrix} * & . & * & . \\ . & . & . & . \\ * & . & * & . \\ . & . & . & . \\ \end{matrix} $$$$$$If there are several possible solutions, then print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 400$$$). Then $$$t$$$ test cases follow. The first row of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 400$$$) — the number of rows and columns in the table. The following $$$n$$$ lines each contain $$$n$$$ characters '.' or '*' denoting empty and marked cells, respectively. It is guaranteed that the sums of $$$n$$$ for all test cases do not exceed $$$400$$$. It is guaranteed that there are exactly two asterisks on the field. They can be in the same row/column. It is guaranteed that the solution exists.

For each test case, output $$$n$$$ rows of $$$n$$$ characters — a field with four asterisks marked corresponding to the statements. If there multiple correct answers, print any of them.

(* https://codeforces.com/contest/1512/problem/B *)

type point = {
    x : int;
    y : int
}

type rectangle = {
    x1 : int;
    x2 : int;
    y1 : int;
    y2 : int
}

let make_rectangle { x=x1; y=y1 } { x=x2; y=y2 } =
    let min_x = min x1 x2 and
    max_x = max x1 x2 and
    min_y = min y1 y2 and
    max_y = max y1 y2 in
    if min_x = max_x
    then (
        let x = if min_x = 0 then 1 else 0 in
        { x1 = x; x2 = min_x; y1 = min_y; y2 = max_y }
    )
    else if min_y = max_y
    then (
        let y = if min_y = 0 then 1 else 0 in
        { x1 = min_x; x2 = max_x; y1 = y; y2 = min_y }
    )
    else { x1 = min_x; x2 = max_x; y1 = min_y; y2 = max_y }

let print_rectangle side rect =
    let line i =
        if i = rect.y1 || i = rect.y2
        then String.init side (fun i -> if i = rect.x1 || i = rect.x2 then '*' else '.')
        else String.make side '.' in
    let rec loop i =
        if i < side
        then (
            Printf.printf "%s\n" (line i);
            loop (i+1)
        ) in
    loop 0

let get_rect side =
    let rec find_star str i acc =
        if i < String.length str
        then find_star str (i+1) (if str.[i] = '*' then (i::acc) else acc)
        else acc in
    let rec helper i points =
        if i = side
        then points
        else (
            let line = read_line () in
            let xs = find_star line 0 [] in
            helper (i+1) ((List.map (fun x -> { x=x; y=i }) xs) @ points)
        ) in
    helper 0 []

let solve_n nb_cases =
    let rec helper i =
        if i > 0
        then (
            let side = read_int () in
            let [p1; p2] = get_rect side in
            make_rectangle p1 p2
            |> print_rectangle side;
            helper (i-1)
        ) in
    helper nb_cases

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


During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ.As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as early as 6, many problems may arise as to how to type a promotional code without errors. It is necessary to calculate such maximum k, that the promotional code could be uniquely identified if it was typed with no more than k errors. At that, k = 0 means that the promotional codes must be entered exactly.A mistake in this problem should be considered as entering the wrong numbers. For example, value "123465" contains two errors relative to promocode "123456". Regardless of the number of errors the entered value consists of exactly six digits.

The first line of the output contains number n (1 ≤ n ≤ 1000) — the number of promocodes. Each of the next n lines contains a single promocode, consisting of exactly 6 digits. It is guaranteed that all the promocodes are distinct. Promocodes can start from digit "0".

Print the maximum k (naturally, not exceeding the length of the promocode), such that any promocode can be uniquely identified if it is typed with at most k mistakes.

NoteIn the first sample k < 3, so if a bar customer types in value "090909", then it will be impossible to define which promocode exactly corresponds to it.

let l = ref [];;
let n = read_int() in for i = 1 to n do l := !l @ [read_line()] done;;
let comp s1 s2 =
    let rec compi s1 s2 i =
        if i == String.length s1 then 0
        else if (String.get s1 i) != (String.get s2 i) then (compi s1 s2 (i + 1)) + 1
        else (compi s1 s2 (i + 1))
    in ((compi s1 s2 0) - 1) / 2;;
let rec min_list lis =
    match lis with
        hd :: tl -> min (min_list tl) hd
        | [] -> 10000
;;
let rec f li =
    if (List.length  li == 1) then 6 else
    match li with
        hd :: tl -> min (min_list (List.map (comp hd) tl)) (f tl)
        | [] -> 1000000
;;
Printf.printf "%d\n" (f !l)
;;

let l = ref [];;
let n = read_int() in for i = 1 to n do l := !l @ [read_line()] done;;
let comp s1 s2 =
    let rec compi s1 s2 i =
        if i == String.length s1 then 0
        else if (String.get s1 i) != (String.get s2 i) then (compi s1 s2 (i + 1)) + 1
        else (compi s1 s2 (i + 1))
    in ((compi s1 s2 0) - 1) / 2;;
let rec min_list lis =
    match lis with
        hd :: tl -> min (min_list tl) hd
        | [] -> 10000
;;
let rec f li =
    match li with
        hd :: tl -> min (min_list (List.map (comp hd) tl)) (f tl)
        | [] -> 1000000
;;
Printf.printf "%d\n" (f !l)
;;


One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with size $$$1\times1$$$, Rainbow Dash has an infinite amount of light blue blocks, Fluttershy has an infinite amount of yellow blocks. The blocks are placed according to the following rule: each newly placed block must touch the built on the previous turns figure by a side (note that the outline borders of the grid are built initially). At each turn, one pony can place any number of blocks of her color according to the game rules.Rainbow and Fluttershy have found out that they can build patterns on the grid of the game that way. They have decided to start with something simple, so they made up their mind to place the blocks to form a chess coloring. Rainbow Dash is well-known for her speed, so she is interested in the minimum number of turns she and Fluttershy need to do to get a chess coloring, covering the whole grid with blocks. Please help her find that number!Since the ponies can play many times on different boards, Rainbow Dash asks you to find the minimum numbers of turns for several grids of the games.The chess coloring in two colors is the one in which each square is neighbor by side only with squares of different colors.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$): the number of grids of the games.  Each of the next $$$T$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$): the size of the side of the grid of the game.

For each grid of the game print the minimum number of turns required to build a chess coloring pattern out of blocks on it.

NoteFor $$$3\times3$$$ grid ponies can make two following moves:

open Scanf;;
open Printf;;

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

let solve n = (n + 2) / 2 in
   let t = read_int () in
      for i = 0 to t - 1 do
        printf "%d\n" (read_int () |> solve)
      done;;