Petya loves computer games. Finally a game that he's been waiting for so long came out!The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values of  for all i from 1 to n. The expression ⌊ x⌋ denotes the result of rounding the number x down to the nearest integer.At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.

The first line of the input contains two positive integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 107) — the number of skills of the character and the number of units of improvements at Petya's disposal. The second line of the input contains a sequence of n integers ai (0 ≤ ai ≤ 100), where ai characterizes the level of the i-th skill of the character.

The first line of the output should contain a single non-negative integer — the maximum total rating of the character that Petya can get using k or less improvement units.

NoteIn the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to  lfloor frac{100}{10} rfloor +  lfloor frac{100}{10} rfloor = 10 + 10 =  20.In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is .In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to .

let cmp x y =
    let a = 10 - (x mod 10)
    and b = 10 - (y mod 10) in
    compare a b

let () = Scanf.scanf "%d %d\n" (fun n k ->
    (* read initial skills *)
    let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
    (* sort by distance from the next multiple of 10 *)
    Array.sort cmp a;

    (* calculate the possible improvement *)
    let (rating, rem) = Array.fold_left (fun (acc, rem) skill ->
            (* if we have enough skill points remaining, use them *)
            let diff = 10 - (skill mod 10) in
            if diff <= rem
            then (acc + (skill + diff) / 10, rem - diff)
            else (acc + skill / 10, rem)
        ) (0, k) a in

    Printf.printf "%d\n" (min (rating + rem / 10) (n * 10)))

(*I should use a cyclic list*)
open Scanf;;
open Printf;;

let (n,k) = Scanf.scanf "%d %d " (fun x y -> (x,y) )

let a = Array.make n 0

let rec readi i l =
  if i = n then
    List.rev l
  else
    begin
      let x = Scanf.scanf "%d " (fun x -> x) in
      readi (i+1) (x::l)
    end

let b = readi 0 []

let b1 = List.filter (fun x -> x mod 10 !=0 ) b |> List.sort (fun x y -> compare (y mod 10)  (x mod 10) )

let b2 = List.filter (fun x -> x mod 10 =0 ) b |> List.sort (fun x y -> compare y  x)

       (*
let _ =
  List.iter (fun x -> printf "%d " x) b

let _ = List.mapi (fun i x -> a.(i)<-x) (b2 @ b1)
        *)

let rec f ll rl k =
  if k==0 then
    (((List.rev ll) @ rl), k)
  else
    begin
      match rl with
      | [] -> ( (List.rev ll), k)
      | hd::tl ->
         begin
           if (hd mod 10) + k >= 10 then
             let x = 10 - (hd mod 10) in
             f ((hd + x)::ll) tl (k-x)
           else
             f (hd::ll) tl 0
         end
    end

let (l,t) = f [] b1 k

let l = l @ b2
(*
let _ =
  print_endline "";
  printf "%d\n" t;
  List. iter (fun x -> printf "%d " x) l;
  print_endline ""
 *)

let _ =
  if t>0 then
    let s = List.fold_left (fun x y -> x + (100-y)) 0 l in
    if s<= t then
      printf "%d\n" (10*(List.length l))
    else
      begin
        let s1 = List.fold_left (fun x y -> x + y/10) 0 (t::l) in
        printf "%d\n" s1
      end
  else
    begin
      let s1 = List.fold_left (fun x y -> x + y/10) 0 l in
      printf "%d\n" s1
    end

let cmp x y =
    let a = 10 - (x mod 10)
    and b = 10 - (y mod 10) in
    compare a b

let () = Scanf.scanf "%d %d\n" (fun n k ->
    (* read initial skills *)
    let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
    (* sort by distance from the next multiple of 10 *)
    Array.sort cmp a;

    (* calculate the possible improvement *)
    let (rating, rem) = Array.fold_left (fun (acc, rem) skill ->
            (* if we have enough skill points remaining, use them *)
            let diff = 10 - (skill mod 10) in
            if diff <= rem
            then (acc + (skill + diff) / 10, rem - diff)
            else (acc + skill / 10, rem)
        ) (0, k) a in

    Printf.printf "%d\n" (rating + rem / 10))

open Scanf;;
open String;;
open Printf;;
open Int64;;
open Char;;

let (n,k) = Scanf.scanf "%d %d " (fun x y -> (x,y) )

let a = Array.make n 0

let _ =
  for i = 0 to (n-1) do
    let x = Scanf.scanf "%d " (fun x -> x) in
    a.(i) <- x
  done

let cmp x y =
  if x mod 10 = 0 then
    1
  else
    begin
      let xi = x mod 10 in
      let yi = y mod 10 in
      if xi > yi then
        1
      else
        begin
          if xi < yi then
            -1
          else 0
        end
    end
    in
    Array.fast_sort (fun x y -> cmp y x) a
(*
let _ =
  Array.iter (fun x -> printf "%d " x) a
 *)

exception BR

 let _ =
   let rk = ref k in
   try
   for i = 0 to (n-1) do
    if !rk <= 0 then
      raise BR
    else
      if !rk+a.(i) >= 100 then
        begin
          rk := !rk - (100-a.(i));
          a.(i) <- 100
        end
      else
        begin
          if !rk + (a.(i) mod 10) >= 10 then
            begin
              let tmp = !rk+a.(i) in
              let tmp2 = tmp - (tmp mod 10) in
              (
                rk := !rk - (tmp2 - a.(i));
                a.(i) <- tmp2
              )
            end
          else ()
        end
   done
   with BR -> ()

(*
 let _ =
   print_endline "";
   Array.iter (fun x -> printf "%d " x) a
 *)

 let rslt =
   Array.fold_left (fun x y -> x + y/10) 0 a
 in
 printf "%d " rslt

open Scanf;;
open String;;
open Printf;;
open Int64;;
open Char;;

let (n,k) = Scanf.scanf "%d %d " (fun x y -> (x,y) )

let a = Array.make n 0

let _ =
  for i = 0 to (n-1) do
    let x = Scanf.scanf "%d " (fun x -> x) in
    a.(i) <- x
  done

let cmp x y =
  if x mod 10 = 0 then
    1
  else begin
    let xi = x mod 10 in
    let yi = y mod 10 in
    if xi > yi then
      1
    else if xi < yi then
      -1
    else 0
  end
  in
  Array.fast_sort (fun x y -> cmp x y) a

  (*
 let _ =
   Array.iter (fun x -> printf "%d " x) a
   *)

exception BR

 let _ =
   let rk = ref k in
   try
   for i = 0 to (n-1) do
    if !rk <= 0 then
      raise BR
    else
      if !rk+a.(i) >= 100 then
        begin
          rk := !rk - (100-a.(i));
          a.(i) <- 100
        end
      else
        begin
          let tmp = !rk+a.(i) in
          let tmp2 = tmp - (tmp mod 10) in
          (
          rk := !rk - (tmp2 - a.(i));
          a.(i) <- tmp2
          )
        end
   done
   with BR -> ()

 let rslt =
   Array.fold_left (fun x y -> x + y/10) 0 a
 in
 printf "%d " rslt


You are given $$$n$$$ strings $$$a_1, a_2, \ldots, a_n$$$: all of them have the same length $$$m$$$. The strings consist of lowercase English letters.Find any string $$$s$$$ of length $$$m$$$ such that each of the given $$$n$$$ strings differs from $$$s$$$ in at most one position. Formally, for each given string $$$a_i$$$, there is no more than one position $$$j$$$ such that $$$a_i[j] \ne s[j]$$$.Note that the desired string $$$s$$$ may be equal to one of the given strings $$$a_i$$$, or it may differ from all the given strings.For example, if you have the strings abac and zbab, then the answer to the problem might be the string abab, which differs from the first only by the last character, and from the second only by the first.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing two positive integers $$$n$$$ ($$$1 \le n \le 10$$$) and $$$m$$$ ($$$1 \le m \le 10$$$) — the number of strings and their length. Then follow $$$n$$$ strings $$$a_i$$$, one per line. Each of them has length $$$m$$$ and consists of lowercase English letters.

Print $$$t$$$ answers to the test cases. Each answer (if it exists) is a string of length $$$m$$$ consisting of lowercase English letters. If there are several answers, print any of them. If the answer does not exist, print "-1" ("minus one", without quotes).

5
2 4
abac
zbab
2 4
aaaa
bbbb
3 3
baa
aaa
aab
2 2
ab
bb
3 1
a
b
c

NoteThe first test case was explained in the statement.In the second test case, the answer does not exist.

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

let () = for _ = 1 to t do
  let (n, m) = Scanf.sscanf (read_line ()) "%d %d" @@ fun n m -> (n, m) in
  let a = Array.init n @@ fun _ -> read_line () in
  let ans = Bytes.of_string a.(0) in
  let diff s t = Array.init m (fun i -> if s.[i] = t.[i] then 0 else 1) |> Array.fold_left (+) 0 in
  try
    for i = 0 to m - 1 do
      let ch = Bytes.get ans i in
      for j = 0 to 25 do
        Bytes.set ans i (char_of_int ((int_of_char 'a') + j));
        if List.for_all (fun str -> diff (Bytes.to_string ans) str < 2) (Array.to_list a) then begin
          print_endline @@ Bytes.to_string ans;
          raise Exit
        end
      done;
      Bytes.set ans i ch;
    done;
    print_endline "-1"
  with Exit -> ()
done

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

let rec for_all f = function
  | [] -> true
  | x :: xs -> f x && for_all f xs

let () = for _ = 1 to t do
  let (n, m) = Scanf.sscanf (read_line ()) "%d %d" @@ fun n m -> (n, m) in
  let a = Array.init n (fun _ -> read_line () |> split_string |> Array.of_list) in
  let tmp = Array.init m (fun i -> let arr = Array.init n (fun j -> a.(j).(i)) in Array.sort compare arr; arr) in
  let ans = (Array.init m @@ fun i -> tmp.(i).(0)) |> Array.to_list |> String.concat "" in
  let diff s t =
    let res = ref 0 in
    for i = 0 to m - 1 do
      if s.[i] <> t.[i] then res := !res + 1
    done;
    !res
  in
  print_endline @@ if for_all (fun arr ->
    let str = arr |> Array.to_list |> String.concat "" in
    diff str ans < 2
  ) (Array.to_list a) then ans
  else "-1"
done


You're given a tree with $$$n$$$ vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the size of the tree.  The next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ ($$$1 \le u, v \le n$$$) each, describing the vertices connected by the $$$i$$$-th edge. It's guaranteed that the given edges form a tree.

Output a single integer $$$k$$$ — the maximum number of edges that can be removed to leave all connected components with even size, or $$$-1$$$ if it is impossible to remove edges in order to satisfy this property.

NoteIn the first example you can remove the edge between vertices $$$1$$$ and $$$4$$$. The graph after that will have two connected components with two vertices in each.In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is $$$-1$$$.

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

let () =
    let n = read_int () in
    let g = Array.make (n + 1) []
    and subtree = Array.make (n + 1) 1
    and visited = Array.make (n + 1) false
    and ans = ref 0 in
    let rec dfs v =
        if not visited.(v) then begin
            visited.(v) <- true;
            subtree.(v) <- List.fold_left (fun acc x ->
                if not visited.(x) then begin
                    dfs x;
                    acc + subtree.(x)
                end
                else acc
            ) 1 g.(v);
            if subtree.(v) mod 2 = 0 then incr ans
        end in
    for i = 1 to n - 1 do
        let a = read_int () and b = read_int () in
        g.(a) <- b::g.(a);
        g.(b) <- a::g.(b)
    done;
    dfs 1;
    if n mod 2 = 1 then printf "-1\n"
    else printf "%d\n" (!ans - 1)

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
	(* 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 I64_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
	(* input *)
	let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	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 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
	(* imperative *)
	let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
	let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
	let repm f t ?(stride=1L) m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
	let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
	let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
	let repim f t ?(stride=1) m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
	let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
	let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
	let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
	let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
	let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
	let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
	(* output *)
	let print_list_mle f ls = string_of_list f ls |> print_endline
	let print_array_mle f a = string_of_array f a |> print_endline
	let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
	let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
	(* debug *)
	let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
	let dump_i64_list ls = print_list ist ls
	let dump_i64_array a = print_array ist a
end open Lib open Array

let () =
	let n=get_i64 0 in let n=i32 n in
	let e=make n [] in
	let visited = make n false in
	repi 2 n (fun _->
		let u,v = get_2_i64 0 in
		let u,v = i32 u-$1,i32 v-$1 in
		e.(u) <- v::e.(u);
		e.(v) <- u::e.(v);
	);
	let res = ref 0L in
	let s = fix (fun f i ->
		visited.(i) <- true;
		List.fold_left (fun sum j->
			if visited.(j) then sum
			else (
				let v = f j in
				if v %$ 2 = 0 then (
					res += 1L; sum
				) else sum +$ v
			)
		) 1 e.(i)
	) 0 in
	if s %$ 2 = 0 then printf "%Ld\n" !res
	else printf "-1\n"

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

let () =
    let n = read_int () in
    let g = Array.make (n + 1) []
    and subtree = Array.make (n + 1) 1
    and visited = Array.make (n + 1) false
    and ans = ref 0
    and err = ref false in
    let rec dfs v =
        let flag = ref false in
        if not visited.(v) then begin
            visited.(v) <- true;
            subtree.(v) <- List.fold_left (fun acc x ->
                if not visited.(x) then begin
                    dfs x;
                    if subtree.(x) mod 2 = 1 then flag := true;
                    acc + subtree.(x)
                end
                else acc
            ) 1 g.(v);
            if subtree.(v) mod 2 = 0 then incr ans
            else if !flag then err := true;
        end in
    for i = 1 to n - 1 do
        let a = read_int () and b = read_int () in
        g.(a) <- b::g.(a);
        g.(b) <- a::g.(b)
    done;
    dfs 1;
    if !err then printf "-1\n"
    else printf "%d\n" (!ans - 1)


There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1, c2, ..., cn. The Old Peykan wants to travel from city c1 to cn using roads. There are (n - 1) one way roads, the i-th road goes from city ci to city ci + 1 and is di kilometers long.The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.Each city ci (except for the last city cn) has a supply of si liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times. Initially (at time zero) the Old Peykan is at city c1 and s1 liters of fuel is transferred to it's empty tank from c1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.Find the minimum time the Old Peykan needs to reach city cn.

The first line of the input contains two space-separated integers m and k (1 ≤ m, k ≤ 1000). The value m specifies the number of roads between cities which is equal to n - 1. The next line contains m space-separated integers d1, d2, ..., dm (1 ≤ di ≤ 1000) and the following line contains m space-separated integers s1, s2, ..., sm (1 ≤ si ≤ 1000).

In the only line of the output print a single integer — the minimum time required for The Old Peykan to reach city cn from city c1.

NoteIn the second sample above, the Old Peykan stays in c1 for 3 hours.

let _ =
  let sb = Scanf.Scanning.stdib in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let d = Array.make m 0 in
  let s = Array.make m 0 in
  let () =
    for i = 0 to m - 1 do
      d.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    for i = 0 to m - 1 do
      s.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let b = ref 0 in
  let res = ref 0 in
  let f = ref 0 in
    for i = 0 to m - 1 do
      b := max !b s.(i);
      f := !f + s.(i);
      if !f < d.(i) then (
	let t = (d.(i) - !f - 1) / !b + 1 in
	  (*Printf.printf "asd %d %d %d\n" i d.(i) t;*)
	  res := !res + k * t;
	  f := !f + !b * t;
      );
      f := !f - d.(i);
      res := !res + d.(i);
    done;
    Printf.printf "%d\n" !res


Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.

The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108.

If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples).

exception Infinite;;

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

let differences a =
    let n = Array.length a in
    let rec aux i acc =
        if i < n then
            aux (i + 1) (IntSet.add (a.(i) - a.(i - 1)) acc)
        else
            acc
    in
    IntSet.elements (aux 1 IntSet.empty)
;;

type 'a option = None | Some of 'a;;
let is_none = function
    | None -> true
    | Some x -> false
;;

let find_possible_cards a =
    let () = Array.sort compare a in
    let n = Array.length a in
    let diff = differences a in
    let try_inside x =
        let rec loop i used =
            if i > n - 2 then used
            else if x = a.(i + 1) - a.(i) then loop (i + 1) used
            else if x * 2 = a.(i + 1) - a.(i) && is_none used then
                loop (i + 1) (Some (a.(i) + x))
            else None
        in
        match loop 0 None with
        | None -> []
        | Some x -> [x]
    in
    match diff with
    | [] -> raise Infinite
    | [0] -> [a.(0)]
    | [x] -> (a.(0) - x) :: (a.(n - 1) + x) :: try_inside (x / 2)
    | [x; y] ->  (try_inside (x / 2)) @ (try_inside (y / 2))
    | _ -> []
;;

let main () =
    let n = Scanf.scanf "%d" (fun x -> x) in
    let a = Array.make n 0 in
    for i = 0 to n - 1 do
        try
            Scanf.scanf " %d" (Array.set a i)
        with End_of_file -> ();
    done;
    try
        let answer = find_possible_cards a in
        Printf.printf "%d\n" (List.length answer);
        List.iter (fun x -> Printf.printf "%d " x) (List.sort compare answer)
    with Infinite ->
        Printf.printf "-1"
;;
let _ = main ()

exception Infinite;;

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

let differences a =
    let n = Array.length a in
    let rec aux i acc =
        if i < n then
            aux (i + 1) (IntSet.add (a.(i) - a.(i - 1)) acc)
        else
            acc
    in
    IntSet.elements (aux 1 IntSet.empty)
;;

type 'a option = None | Some of 'a;;
let is_none = function
    | None -> true
    | Some x -> false
;;

let find_possible_cards a =
    let () = Array.sort compare a in
    let n = Array.length a in
    let diff = differences a in
    let try_inside x =
        let rec loop i used =
            if i > n - 2 then used
            else if x = a.(i + 1) - a.(i) then loop (i + 1) used
            else if x * 2 = a.(i + 1) - a.(i) && is_none used then
                loop (i + 1) (Some (a.(i) + x))
            else None
        in
        match loop 0 None with
        | None -> []
        | Some x -> [x]
    in
    match diff with
    | [] -> raise Infinite
    | [x] -> (a.(0) - x) :: (a.(n - 1) + x) :: try_inside (x / 2)
    | [x; y] ->  (try_inside (x / 2)) @ (try_inside (y / 2))
    | _ -> []
;;

let main () =
    let n = Scanf.scanf "%d" (fun x -> x) in
    let a = Array.make n 0 in
    for i = 0 to n - 1 do
        try
            Scanf.scanf " %d" (Array.set a i)
        with End_of_file -> ();
    done;
    try
        let answer = find_possible_cards a in
        Printf.printf "%d\n" (List.length answer);
        List.iter (fun x -> Printf.printf "%d " x) answer
    with Infinite ->
        Printf.printf "-1"
;;
let _ = main ()

exception Infinite;;

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

let differences a =
    let n = Array.length a in
    let rec aux i acc =
        if i < n then
            aux (i + 1) (IntSet.add (a.(i) - a.(i - 1)) acc)
        else
            acc
    in
    IntSet.elements (aux 1 IntSet.empty)
;;

type 'a option = None | Some of 'a;;
let is_none = function
    | None -> true
    | Some x -> false
;;

let find_possible_cards a =
    let () = Array.sort compare a in
    let n = Array.length a in
    let diff = differences a in
    let try_inside x =
        let rec loop i used =
            if i > n - 2 then used
            else if x = a.(i + 1) - a.(i) then loop (i + 1) used
            else if x * 2 = a.(i + 1) - a.(i) && is_none used then
                loop (i + 1) (Some (a.(i) + x))
            else None
        in
        match loop 0 None with
        | None -> []
        | Some x -> [x]
    in
    match diff with
    | [] -> raise Infinite
    | [x] -> (a.(0) - x) :: (a.(n - 1) + x) :: try_inside (x / 2)
    | [x; y] ->  (try_inside (x / 2)) @ (try_inside (y / 2))
    | _ -> []
;;

let main () =
    let n = Scanf.scanf "%d" (fun x -> x) in
    let a = Array.make n 0 in
    for i = 0 to n - 1 do
        try
            Scanf.scanf " %d" (Array.set a i)
        with End_of_file -> ();
    done;
    try
        let answer = find_possible_cards a in
        Printf.printf "%d\n" (List.length answer);
        List.iter (fun x -> Printf.printf "%d " x) (List.sort compare answer)
    with Infinite ->
        Printf.printf "-1"
;;
let _ = main ()


Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.

Print the index of the day when Polycarp will celebrate the equator.

NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.

(* Codeforces 962 A Equator - TODO *)

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

let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;

let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;

let rec sumlist sm l = match l with
| [] -> sm
| h :: t ->
	let nsm = Int64.add (Int64.of_int h) sm in
	sumlist nsm t;;

let rec limidx sm lim idx l = match l with
| [] -> (idx + 1)
| h :: t ->
	let nidx = idx + 1 in
	let nsm = Int64.add (Int64.of_int h) sm in
	(*let _ = begin Printf.printf "nsm lim = %Ld %Ld\n" nsm lim end in *)
	if (Int64.compare nsm lim) >= 0 then nidx
	else limidx nsm lim nidx t;;

let main() =
	let n = gr () in
	let a = readlist n [] in
	let a = List.rev a in
	let sum = sumlist Int64.zero a in
	let two = Int64.succ Int64.one in
	let lim = Int64.div (Int64.succ sum) two in
	let equator = limidx Int64.zero lim 0 a in
	begin
		print_int equator;
		print_string "\n"
	end;;

main();;


You are given two arrays $$$a$$$ and $$$b$$$, both consisting of $$$n$$$ integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \neq j$$$) and swap $$$a_i$$$ with $$$a_j$$$ and $$$b_i$$$ with $$$b_j$$$. You have to perform the swap in both arrays.You are allowed to perform at most $$$10^4$$$ moves (possibly, zero). Can you make both arrays sorted in a non-decreasing order at the end? If you can, print any sequence of moves that makes both arrays sorted.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the first array. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$) — the second array.

For each testcase, print the answer. If it's impossible to make both arrays sorted in a non-decreasing order in at most $$$10^4$$$ moves, print -1. Otherwise, first, print the number of moves $$$k$$$ $$$(0 \le k \le 10^4)$$$. Then print $$$i$$$ and $$$j$$$ for each move $$$(1 \le i, j \le n$$$; $$$i \neq j)$$$. If there are multiple answers, then print any of them. You don't have to minimize the number of moves.

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

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

  let cases = read_int()in
  for case = 1 to cases do
    let n = read_int() in
    let a = Array.init n read_int in
    let b = Array.init n read_int in

    if exists 0 (n-2) (fun i -> exists i (n-1) (fun j ->
      ((compare a.(i) a.(j)) * (compare b.(i) b.(j))) = -1))
    then printf "-1\n" else (
      let z = Array.init n (fun i -> a.(i),b.(i),i) in
      Array.sort compare z;
      let get3rd (a,b,c) = c in
      let zinv = Array.make n 0 in
      for i=0 to n-1 do
	zinv.(get3rd(z.(i))) <- i
      done;

      let rec find i j = if j = n then failwith "bad find"
	else if zinv.(j) = i then j else find i (j+1) in

      let swap i j =
	let (ai,aj) = (zinv.(i),zinv.(j)) in
	zinv.(i) <- aj;
	zinv.(j) <- ai
      in

(*      printf "z = ";
      for i=0 to n-1 do printf "%d  " (get3rd z.(i)) done;
      print_newline();
*)
      let swaplist = ref [] in
      for i=0 to n-1 do
	let j = find i i in
	if j > i then (
	  swaplist := (i,j):: (!swaplist);
	  swap i j
	)
      done;
      printf "%d\n" (List.length !swaplist);
      List.iter (fun (i,j) -> printf "%d %d\n" (i+1) (j+1)) (List.rev !swaplist)
    )
  done


Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.

The first line contains two integers n, m (1 ≤ n, m ≤ 100) — the number of streets and avenues in Munhattan. Each of the next n lines contains m integers cij (1 ≤ cij ≤ 109) — the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.

Print the only integer a — the cost of the dinner for Jack and Emma.

NoteIn the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1.

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;
let read x = (if x = 0 then Scanf.scanf "%d\n" else Scanf.scanf "%d ") ( fun x -> x );;

let (+$) x y =
  if x > max_int - y then max_int
  else x + y;;

let rec ( *$ ) x y =
  if y = 0 then 0 else
  if y mod 2 = 1 then x *$ (y-1) +$ x
  else let a = x *$ (y/2) in a +$ a;;

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

let _ =
  let (n, m) = read2 () in
  let maxi = ref 0 in
  for i=1 to n do
    let mini = ref max_int in
    for i=1 to m-1 do
      Scanf.scanf "%d " ( fun x -> if x < !mini then mini := x )
    done;
    Scanf.scanf "%d\n" ( fun x -> if x < !mini then mini := x );
    if !mini > !maxi then maxi := !mini;
  done;
  Printf.printf "%d\n" !maxi ;;

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

let () =
  let n = xint() and m = xint() in
  let cost = ref 0 in
  for i = 0 to n - 1 do
    let tmp = ref 1000000000 in
    for j = 0 to m - 1 do
      let x = xint() in
      tmp := if x < !tmp then x else !tmp;
    done;
    cost := if !cost < !tmp then !tmp else !cost;
  done;
  Printf.printf "%d\n" !cost;


Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $$$n$$$ types of candies, there are $$$a_i$$$ candies of the type $$$i$$$ ($$$1 \le i \le n$$$).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. The following is a description of $$$t$$$ test cases of input, two lines for each. The first line of the case contains the single number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of types of candies in the package. The second line of the case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the number of candies of the type $$$i$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer, output "YES" if Vlad can eat candy as planned, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first example, it is necessary to eat sweets in this order: a candy of the type $$$2$$$, it is the most frequent, now $$$a = [2, 2]$$$; a candy of the type $$$1$$$, there are the same number of candies of the type $$$2$$$, but we just ate one, now $$$a = [1, 2]$$$; a candy of the type $$$2$$$, it is the most frequent, now $$$a = [1, 1]$$$; a candy of the type $$$1$$$, now $$$a = [0, 1]$$$; a candy of the type $$$2$$$, now $$$a = [0, 0]$$$ and the candy has run out.In the second example, all the candies are of the same type and it is impossible to eat them without eating two identical ones in a row.In the third example, first of all, a candy of the type $$$2$$$ will be eaten, after which this kind will remain the only kind that is the most frequent, and you will have to eat a candy of the type $$$2$$$ again.

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

let maxes tab = let max1 = ref tab.(0) in
	let count = ref 0 in
  for i = 1 to Array.length tab -1 do
	if tab.(i) = !max1 then incr count;
    if tab.(i) > !max1 then (max1 := tab.(i); count := 0) ;

  done;
let toto = ref false in
  if !count <> 0 then true else begin
	for i = 0 to Array.length tab -1 do
	if tab.(i) = (!max1 -1) then toto := true
done ; !toto

end ;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let len = int_of_string (input_line stdin) in
  let str = input_line stdin in
  let tab = parse str len in
  if len < 2 then (if tab.(0) = 1 then print_endline "YES" else print_endline "NO")
  else begin
    if maxes tab then print_endline "YES" else print_endline "NO" end
done;;

open Printf
open Scanf
module LL = Int64
let ( !! ) x = LL.to_int x
let ( ++ ) x y = LL.add x y
let ( -- ) x y = LL.sub x y
let ( ** ) x y = LL.mul x y
let ( // ) x y = LL.div x y
let ( %% ) x y = LL.rem x y
let ( >> ) x y = (LL.compare x y) > 0
let ( << ) x y = (LL.compare x y) < 0
let ( == ) x y = (LL.compare x y) = 0
let rd_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let rd_ll _ = bscanf Scanning.stdin " %Ld " (fun x -> x)
let rd_arr n = Array.init n rd_ll

let solve n a =
  Array.sort LL.compare a;
  let dx =
    if n = 1 then a.(0)
    else a.(n-1) -- a.(n-2) in

  if dx >> 1L then "NO" else "YES"

let () =
  let t = read_int () in
  for i=1 to t do
    let n = rd_int () in
    let a = rd_arr n in
    printf "%s\n" (solve n a)
  done;

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

let maxes tab = let max1 = ref tab.(0) in
	let count = ref 0 in
  for i = 1 to Array.length tab -1 do
    if tab.(i) > !max1 then (max1 := tab.(i); count := 0) ;
	if tab.(i) = !max1 then incr count;
  done;
let toto = ref false in
  if !count <> 0 then true else begin
	for i = 0 to Array.length tab -1 do
	if tab.(i) = !max1 -1 then toto := true
done ; !toto

end ;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let len = int_of_string (input_line stdin) in
  let str = input_line stdin in
  let tab = parse str len in
  if len < 2 then (if tab.(0) = 1 then print_endline "YES" else print_endline "NO")
  else begin
    if maxes tab then print_endline "YES" else print_endline "NO" end
done;;

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

let maxes tab = let max1 = ref tab.(0) in let max2 = ref tab.(1) in
  for i = 2 to Array.length tab -1 do
    if !max1 < !max2 && tab.(i) > !max1 then max1 := tab.(i) ;
    if !max1 >= !max2 && tab.(i) > !max2 then max2 := tab.(i) ;
  done;
  !max1 = !max2 || !max1 = !max2 -1 || !max2 = !max1 -1;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let len = int_of_string (input_line stdin) in
  let str = input_line stdin in
  let tab = parse str len in
  if len < 2 then (if tab.(0) = 1 then print_endline "YES" else print_endline "NO")
  else begin
    if maxes tab then print_endline "YES" else print_endline "NO" end
done;;

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

let maxes tab = let max1 = ref tab.(0) in let max2 = ref tab.(1) in
  for i = 2 to Array.length tab -1 do
    if !max1 < !max2 && tab.(i) > !max1 then max1 := tab.(i) ;
    if !max1 >= !max2 && tab.(i) > !max2 then max2 := tab.(i) ;
  done;
  !max1 = !max2 || !max1 = !max2 +1 || !max2 = !max1 +1;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let len = int_of_string (input_line stdin) in
  let str = input_line stdin in
  let tab = parse str len in
  if len < 2 then (if tab.(0) = 1 then print_endline "YES" else print_endline "NO")
  else begin
    if maxes tab then print_endline "YES" else print_endline "NO" end
done;;


A frog is currently at the point $$$0$$$ on a coordinate axis $$$Ox$$$. It jumps by the following algorithm: the first jump is $$$a$$$ units to the right, the second jump is $$$b$$$ units to the left, the third jump is $$$a$$$ units to the right, the fourth jump is $$$b$$$ units to the left, and so on.Formally:   if the frog has jumped an even number of times (before the current jump), it jumps from its current position $$$x$$$ to position $$$x+a$$$;  otherwise it jumps from its current position $$$x$$$ to position $$$x-b$$$. Your task is to calculate the position of the frog after $$$k$$$ jumps.But... One more thing. You are watching $$$t$$$ different frogs so you have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. Each of the next $$$t$$$ lines contain queries (one query per line). The query is described as three space-separated integers $$$a, b, k$$$ ($$$1 \le a, b, k \le 10^9$$$) — the lengths of two types of jumps and the number of jumps, respectively.

Print $$$t$$$ integers. The $$$i$$$-th integer should be the answer for the $$$i$$$-th query.

NoteIn the first query frog jumps $$$5$$$ to the right, $$$2$$$ to the left and $$$5$$$ to the right so the answer is $$$5 - 2 + 5 = 8$$$.In the second query frog jumps $$$100$$$ to the right, $$$1$$$ to the left, $$$100$$$ to the right and $$$1$$$ to the left so the answer is $$$100 - 1 + 100 - 1 = 198$$$.In the third query the answer is $$$1 - 10 + 1 - 10 + 1 = -17$$$.In the fourth query the answer is $$$10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997$$$.In the fifth query all frog's jumps are neutralized by each other so the answer is $$$0$$$.The sixth query is the same as the fifth but without the last jump so the answer is $$$1$$$.

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

let read_input () =
  let a = ri() and
  b = ri() and
  c = ri() in
    (Int64.of_int a, Int64.of_int b, Int64.of_int c)

let res a b k =
  let res1 = Int64.mul (Int64.sub a b) (Int64.div k (Int64.of_int 2)) and
  res2 = Int64.mul (Int64.rem k (Int64.of_int 2)) a in
  (*print_int a; print_int b; print_int k; *)
  Int64.add res1 res2

let solveCase () =
  let (a, b, k) = read_input () in
  let x = res a b k in
  print_endline (Int64.to_string x)

let rec solve t =
  (*print_int t; print_endline ". test"; *)
  if t=0 then ()
  else
    (solveCase ();
    solve (t-1))

let () =
  let t = read_int() in
  solve t

open Scanf;;
open String;;
open Num;;

let mprint z =
  print_endline (Num.string_of_num z);;

let one_jump () =
  let (a,b,k) = Scanf.bscanf Scanf.Scanning.stdin "%d %d %d " (fun x y z -> (x,y,z) ) in
  let k2 = (num_of_int (k/2)) in
  let aa = num_of_int a in
  let bb = num_of_int b in
  let rslt = k2*/aa -/ k2*/bb +/ (num_of_int (k mod 2)) */ aa in
  mprint rslt
;;

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

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 I64_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
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
  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 string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
  let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
  let fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

let () =
  let t = get_i64 0 in
  rep 1L t (fun _ ->
    let a,b,k = get_3_i64 0 in
    let n = k/2L in
    let d = a-b in
    printf "%Ld\n" @@ d * n + (if k mod 2L = 1L then a else 0L)
  )

open Scanf;;
open String;;

let one_jump () =
  let (a,b,k) = Scanf.bscanf Scanf.Scanning.stdin "%d %d %d " (fun x y z -> (x,y,z) ) in
  let k2 = k/2 in
  let rslt = k2*a - k2*b + (k mod 2) * a in
  print_int rslt; print_string "\n"
;;

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


A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".

The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.

Print the single number — the number of substrings of the given string, containing exactly k characters "1". 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 the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".

let ( +:), ( *:), ( /:), (!<) = Int64.add, Int64.mul, Int64.div, Int64.of_int

let _ =
    let main () =
        let k = read_int () in
        let s = read_line () in
        let len = String.length s in
        let arr = Array.create (len + 1) 0 in
        let rec loop pos i acc =
            if pos = len then (arr.(i) <- acc; i + 1) else
            if s.[pos] = '0' then loop (pos + 1) i (acc + 1) else
            (arr.(i) <- acc; loop (pos + 1) (i + 1) 0)
        in
        let m = loop 0 0 0 in
        let rec loop i acc =
            if i + k >= m then acc else
            let acc = acc +: if k = 0 then (!< (arr.(i)) *: !< (arr.(i) + 1)) /: 2L
                                      else (!< (arr.(i) + 1) *: !< (arr.(i + k) + 1))
            in
            loop (i + 1) acc
        in
        let r = loop 0 0L in
        Printf.printf "%Ld\n" r
    in
    main ()


In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:  overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.

The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.

Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.

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

let ident x = x ;;

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

module List = struct
  include ListLabels ;;

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

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

module Array = struct
  include ArrayLabels ;;

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

module String = struct
  include StringLabels ;;

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

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

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

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

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

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

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

let other = function
| 1 -> (2, 3)
| 2 -> (3, 1)
| 3 -> (1, 2)
| _ -> assert false
;;

let pick colors (x, xc) (y, yc) (z, zc) =
  if xc >= 0 then let yc, zc = other xc in (y, yc), (z, zc)
  else if yc >= 0 then let xc, zc = other yc in (x, xc), (z, zc)
  else if zc >= 0 then let xc, yc = other zc in (x, xc), (y, yc)
  else begin
    colors.(x) <- 1; colors.(y) <- 2; colors.(z) <- 3;
    raise Exit
  end
;;

let () =
  let n, m = Scanf.scanf "%d %d " (fun x y -> x, y) in
  let ds = fold_for 0 m ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d %d %d " (fun x y z -> x - 1, y - 1, z - 1) :: acc) |> List.rev in
  let colors = Array.create n (-1) in
  List.iter ds ~f:(fun (x, y, z) ->
    try
      let (y, yc), (z, zc) = pick colors (x, colors.(x)) (y, colors.(y)) (z, colors.(z)) in
      colors.(y) <- yc; colors.(z) <- zc
    with
    | Exit -> ());
  Array.iter colors ~f:(fun x -> Printf.printf "%d " x);
  print_endline "";
;;


Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||.   Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the number of matches.

For each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME.

NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||).

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let m = int_of_string (input_line stdin) in
    if m = 2 then
      Format.printf "2@."
    else if m mod 2 = 0 then
      Format.printf "0@."
    else
      Format.printf "1@."
  done


There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the number of boxes you have. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the quantity of candies in each box.

For each test case, print a single integer denoting the minimum number of candies you have to eat to satisfy the requirements.

NoteFor the first test case, you can eat $$$1$$$ candy from the second box, $$$2$$$ candies from the third box, $$$3$$$ candies from the fourth box and $$$4$$$ candies from the fifth box. Now the boxes have $$$[1, 1, 1, 1, 1]$$$ candies in them and you ate $$$0 + 1 + 2 + 3 + 4 = 10$$$ candies in total so the answer is $$$10$$$.For the second test case, the best answer is obtained by making all boxes contain $$$5$$$ candies in them, thus eating $$$995 + 995 + 0 + 995 + 995 + 995 = 4975$$$ candies in total.

let read () = Scanf.scanf " %d" (fun x -> x);;
let rec getInputs total m = function
 | 0 -> total, m
 | n ->
    let box = read () in
    getInputs
        (total+box)
        (if (box<m) then box else m)
        (n-1)
;;

let rec outputResult = function
 | 0 -> 0
 | n ->
    let numBoxes = read () in
    let totalAndMin = getInputs 0 (int_of_float 10e7) numBoxes in
    match totalAndMin with
     | total, m ->
    print_int (
        total - (m*numBoxes)
    );
    print_newline ();
    outputResult (n-1)
;;
outputResult (read ());;

let read () = Scanf.scanf " %d" (fun x -> x);;
let rec getInputs total m = function
 | 0 -> total, m
 | n ->
    let box = read () in
    getInputs
        (total+box)
        (if (box<m) then box else m)
        (n-1)
;;

let rec outputResult = function
 | 0 -> 0
 | n ->
    let totalAndMin = getInputs 0 (int_of_float 10e7) (read ()) in
    match totalAndMin with
     | total, m ->
    print_int (
        total - (m*n)
    );
    print_newline ();
    outputResult (n-1)
;;
outputResult (read ());;


Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.

The first line of the input will contain a single integer n (2 ≤ n ≤ 50). The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given.

Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.

NoteIn the first case, the answer can be {1, 2} or {2, 1}.In the second case, another possible answer is {2, 4, 5, 1, 3}.

Scanf.scanf "%d" (fun n ->
   let tab = Array.make n 0 and flag = ref true in
      for i = 0 to n-1 do
          let maxi = ref 0 in
          for j=0 to n-1 do
             Scanf.scanf " %d" (fun k -> maxi := max !maxi k);
          done;
          tab.(i) <- if !maxi = n-1 && !flag then (flag := false; n) else !maxi;
      done;
      for i = 0 to n-1 do Printf.printf "%d%s" (tab.(i)) (if i=n-1 then "" else " "); done
)


You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.

NoteIn the first test case of the example, we can perform the following sequence of moves:  choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$);  choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.

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

let rec fill acc = function
  | 0 -> acc
  | n -> fill (acc @ [read_int ()]) (n - 1)

let solve (n : int) : string =
  let rec f (l : int list) : string =
    match l with
    | []
    | [_] -> "YES"
    | a :: b :: tl -> if (b - a) > 1 then "NO" else f ([b] @ tl)
  in f (List.sort compare (fill [] n))

let () =
  let t = read_int () in
  for i = 1 to t do
    let n = read_int () in
    Printf.printf "%s\n" (solve n)
  done;

open Printf
open Scanf

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

let solve () =
  let n = read_int() in
  let arr = Array.init n read_int in
  Array.sort compare arr;
  let rec loop i =
    if i >= n then (
        printf "YES\n";
    ) else if arr.(i) - arr.(i - 1) > 1 then (
        printf "NO\n";
    ) else (
        loop (i + 1)
    )
  in
  loop 1

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve ()
    done

open Printf
open Scanf

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

let solve () =
  let n = read_int() in
  let arr = Array.init n read_int in
  Array.sort compare arr;
  for i = 1 to n - 1 do
    if arr.(i) - arr.(i - 1) > 1 then (
        printf "NO\n";
    ) else if i = n - 1 then (
        printf "YES\n"
    )
  done;
  ()

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve ()
    done

open Printf
open Scanf

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

let solve () =
  let n = read_int() in
  let arr = Array.init n read_int in
  Array.sort compare arr;
  let rec loop i =
    if i >= n - 1 then (
        printf "YES\n";
    ) else if arr.(i) - arr.(i - 1) > 1 then (
        printf "NO\n";
    ) else (
        loop (i + 1)
    )
  in
  loop 1

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve ()
    done


You are given two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 100$$$). Represent the number $$$n$$$ as the sum of $$$k$$$ positive integers of the same parity (have the same remainder when divided by $$$2$$$).In other words, find $$$a_1, a_2, \ldots, a_k$$$ such that all $$$a_i>0$$$, $$$n = a_1 + a_2 + \ldots + a_k$$$ and either all $$$a_i$$$ are even or all $$$a_i$$$ are odd at the same time.If such a representation does not exist, then report it.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 100$$$).

For each test case print:   YES and the required values $$$a_i$$$, if the answer exists (if there are several answers, print any of them);  NO if the answer does not exist.  The letters in the words YES and NO can be printed in any case.

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

open List
open Printf

let solve () =
  let n = re () in
  let k = re () in
  if (n mod 2 = 0 && ((k mod 2 = 1 && n < 2 * k) || (k mod 2 = 0 && n < k))) || (n mod 2 = 1 && (n < k || k mod 2 = 0)) then printf "NO\n"
  else let _ = printf "YES\n" in
    for i = 1 to k - 1 do
      if n mod 2 = 0 then
        if k mod 2 = 1 then printf "%d " 2
        else printf "%d " 1
      else printf "%d " 1
    done;
    if n mod 2 = 0 then
      if k mod 2 = 1 then printf "%d \n" (n - 2 * (k - 1))
      else printf "%d \n" (n - (k - 1))
    else printf "%d \n" (n - (k - 1))
;;

let _ =
  let t = re () in
  for i = 1 to t do
    solve ()
  done
;;

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

open Printf

let init (x : int) (f : int -> 'a) : 'a list =
  let rec build k =
    if k = x then []
    else (f k) :: build (k + 1) in
  build 0
;;

let run () =
  let n = scan_int () in
  let k = scan_int () in
  if n < k || (k mod 2 = 0 && n mod 2 = 1) then
    printf "NO\n"
  else begin
    let lst =
      if n mod 2 = 1 then
        init k (fun x -> if x = 0 then n - k + 1 else 1)
      else if k mod 2 = 1 then
        init k (fun x -> if x = 0 then n - 2 * (k - 1) else 2)
      else
        init k (fun x -> if x = 0 then (n - k + 1) else 1) in
    if List.hd lst < 1 then printf "NO\n"
    else begin
      printf "YES\n";
      List.iter (printf "%d ") lst;
      print_endline "";
    end
  end
;;

let () =
  let t = scan_int () in
  for i = 1 to t do
    run ()
  done
;;

(* Codeforces 1352 B Same Parity Summands train  *)

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

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

let rec repeat a n = match n with
  | 0 -> []
  | _ -> a :: repeat a (n-1);;

let rec repeat2 o d k = match k with
	| 0 -> []
	| _ ->
		if o == 0 then repeat d k
		else
			(2 + d) :: repeat2 (o - 2) d (k - 1);;

let rec summands n k =
	if k == 1 then [ n ]
	else if n < k then []
  else if n == k then repeat 1 k
  else if n == (k+1) then []
	else if (n mod 2) == 1 && (k mod 2) == 0 then []
	else
		let o = n mod k in
		let d = n / k in
		if (o mod 2) == 0 then	(d + o) :: repeat d (k-1)
		else if d == 1 then []
		else
			repeat2 (o + k) (d - 1) k;;

let do_one () =
    let n = gr () in
    let k = gr () in
		let suml = summands n k in
		if (List.length suml) == 0 then print_string "NO\n"
		else
			begin
				print_string "YES\n";
				printlisti suml;
				print_string "\n"
			end;;

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

let main() =
	let t = gr () in
	do_all t;;

main();;


Polycarp doesn't like integers that are divisible by $$$3$$$ or end with the digit $$$3$$$ in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.Polycarp starts to write out the positive (greater than $$$0$$$) integers which he likes: $$$1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \dots$$$. Output the $$$k$$$-th element of this sequence (the elements are numbered from $$$1$$$).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 1000$$$).

For each test case, output in a separate line one integer $$$x$$$ — the $$$k$$$-th element of the sequence that was written out by Polycarp.

open Array;;
let readInt () = Scanf.scanf " %d" (fun i -> i);;

let print_number x = print_string (string_of_int x); print_newline();;
let ptr = ref 0;;
let a = make 10000 0;;
for i = 1 to 10000 do
  if i mod 3 <> 0 then
    if i mod 10 <> 3 then
      let () =
        ptr := !ptr + 1 in
      a.(!ptr) <- i
done;;

let t = readInt() in
for i = 1 to t do
  let k = readInt() in
  print_number a.(k)
done;;


Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems — the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is string slsl + 1... sr.String x = x1x2... xp is lexicographically smaller than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there exists such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The string characters are compared by their ASCII codes.

The first line contains integer n (1 ≤ n ≤ 30) — the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.

Print a string, consisting of lowercase English letters — the lexicographically minimum shortest original title.

5
threehorses
goodsubstrings
secret
primematrix
beautifulyear

NoteIn the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title.

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

let () =
  let n = read_int() in
  let s = Array.init n (fun i -> read_string()) in

  let h = Hashtbl.create 100 in

    for i=0 to n-1 do
      let ilen = String.length s.(i) in
	for len = 1 to ilen do
	  for start = 0 to ilen - len do
	    let sub = String.sub s.(i) start len in
	      Hashtbl.replace h sub true
	  done
	done
    done;

    let num_to_string k len =
      let a = String.create len in
      let n = ref k in
	for i=len-1 downto 0 do
	  a.[i] <- char_of_int ((int_of_char 'a') + (!n mod 26));
	  n := !n / 26
	done;
	a
    in

    let rec power a i =
      if i=0 then 1 else
	let p = power a (i/2) in
	  p * p * (if i land 1 = 0 then 1 else a)
    in

    let rec loop len =
      let hi = power 26 len in
      let rec loop2 i = if i=hi then "0" else
	let ss = num_to_string i len in
	  if Hashtbl.mem h ss then loop2 (i+1) else ss
      in
      let ans = loop2 0 in
	if ans = "0" then loop (len+1) else ans
    in

      Printf.printf "%s\n" (loop 1)


Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from $$$1$$$ to $$$n$$$ and then $$$3n$$$ times takes a random pair of different elements and swaps them. Alex envies Petr and tries to imitate him in all kind of things. Alex has also come up with a problem about random permutation. He generates a random permutation just like Petr but swaps elements $$$7n+1$$$ times instead of $$$3n$$$ times. Because it is more random, OK?!You somehow get a test from one of these problems and now you want to know from which one.

In the first line of input there is one integer $$$n$$$ ($$$10^{3} \le n \le 10^{6}$$$). In the second line there are $$$n$$$ distinct integers between $$$1$$$ and $$$n$$$ — the permutation of size $$$n$$$ from the test. It is guaranteed that all tests except for sample are generated this way: First we choose $$$n$$$ — the size of the permutation. Then we randomly choose a method to generate a permutation — the one of Petr or the one of Alex. Then we generate a permutation using chosen method.

If the test is generated via Petr's method print "Petr" (without quotes). If the test is generated via Alex's method print "Um_nik" (without quotes).

NotePlease note that the sample is not a valid test (because of limitations for $$$n$$$) and is given only to illustrate input/output format. Your program still has to print correct answer to this test to get AC.Due to randomness of input hacks in this problem are forbidden.

let count_inversion (src: int array): int =
  let ninv = ref 0 in

  let merge lhs rhs: int array =
    let ll = Array.length lhs in
    let rl = Array.length rhs in
    let ret = Array.make (ll + rl) 0 in
    let rec loop idx i j =
      if i >= ll
      then begin
        Array.blit rhs j ret idx (rl - j)
      end else if j >= rl
      then begin
        (* ninv := !ninv + ll - i; *)
        Array.blit lhs i ret idx (ll - i)
      end else if lhs.(i) <= rhs.(j)
      then begin
        ret.(idx) <- lhs.(i);
        loop (idx + 1) (i + 1) j
      end else begin
        ret.(idx) <- rhs.(j);
        ninv := !ninv + ll - i;
        loop (idx + 1) i (j + 1)
      end
    in
    loop 0 0 0;
    ret
  in

  let rec do_sort (src: int array): int array =
    match Array.length src with
    | 0 | 1 -> src
    | n ->
      let m = n / 2 in
      let lhs = Array.sub src 0 m in
      let rhs = Array.sub src m (n - m) in
      let lhs = do_sort lhs in
      let rhs = do_sort rhs in
      merge lhs rhs
  in
  let sorted = do_sort src in
  (* Array.iter (fun i -> Printf.printf "%d " i) src; print_newline (); *)
  (* Array.iter (fun i -> Printf.printf "%d " i) sorted; print_newline (); *)
  !ninv

let _ =
  let n = Scanf.scanf " %d" (fun i -> i) in
  let src = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i)) in
  let inv = count_inversion src in
  (* inv |> string_of_int |> print_endline; *)
  (if (inv - n * 3) mod 2 = 0
   then "Petr"
   else if (inv - (7 * n + 1)) mod 2 = 0
   then "Um_nik"
   else "hhh") |> print_endline

let count_inversion (src: int array): int =
  let ninv = ref 0 in

  let merge lhs rhs: int array =
    let ll = Array.length lhs in
    let rl = Array.length rhs in
    let ret = Array.make (ll + rl) 0 in
    let rec loop idx i j =
      if i >= ll
      then begin
        Array.blit rhs j ret idx (rl - j)
      end else if j >= rl
      then begin
        ninv := !ninv + ll - i;
        Array.blit lhs i ret idx (ll - i)
      end else if lhs.(i) <= rhs.(j)
      then begin
        ret.(idx) <- lhs.(i);
        loop (idx + 1) (i + 1) j
      end else begin
        ret.(idx) <- rhs.(j);
        ninv := !ninv + 1;
        loop (idx + 1) i (j + 1)
      end
    in
    loop 0 0 0;
    ret
  in

  let rec do_sort (src: int array): int array =
    match Array.length src with
    | 0 | 1 -> src
    | n ->
      let m = n / 2 in
      let lhs = Array.sub src 0 m in
      let rhs = Array.sub src m (n - m) in
      let lhs = do_sort lhs in
      let rhs = do_sort rhs in
      merge lhs rhs
  in
  let sorted = do_sort src in
  (* Array.iter (fun i -> Printf.printf "%d " i) src; print_newline (); *)
  (* Array.iter (fun i -> Printf.printf "%d " i) sorted; print_newline (); *)
  !ninv

let _ =
  let n = Scanf.scanf " %d" (fun i -> i) in
  let src = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i)) in
  let inv = count_inversion src in
  (* inv |> string_of_int |> print_endline; *)
  (if (inv - n * 3) mod 2 = 0
   then "Petr"
   else if (inv - (7 * n + 1)) mod 2 = 0
   then "Um_nik"
   else "hhh") |> print_endline

let count_inversion (src: int array): int =
  let ninv = ref 0 in

  let merge lhs rhs: int array =
    let ll = Array.length lhs in
    let rl = Array.length rhs in
    let ret = Array.make (ll + rl) 0 in
    let rec loop idx i j =
      if i >= ll
      then Array.blit rhs j ret idx (rl - j)
      else if j >= rl
      then Array.blit lhs i ret idx (ll - i)
      else if lhs.(i) <= rhs.(j)
      then begin
        ret.(idx) <- lhs.(i);
        loop (idx + 1) (i + 1) j
      end else begin
        ret.(idx) <- rhs.(j);
        ninv := !ninv + 1;
        loop (idx + 1) i (j + 1)
      end
    in
    loop 0 0 0;
    ret
  in

  let rec do_sort (src: int array): int array =
    match Array.length src with
    | 0 | 1 -> src
    | n ->
      let m = n / 2 in
      let lhs = Array.sub src 0 m in
      let rhs = Array.sub src m (n - m) in
      let lhs = do_sort lhs in
      let rhs = do_sort rhs in
      merge lhs rhs
  in
  let sorted = do_sort src in
  Array.iter (fun i -> Printf.printf "%d " i) src; print_newline ();
  Array.iter (fun i -> Printf.printf "%d " i) sorted; print_newline ();
  !ninv

let _ =
  let n = Scanf.scanf " %d" (fun i -> i) in
  let src = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i)) in
  let inv = count_inversion src in
  (if inv = n * 3
   then "Petr"
   else if inv = 7 * n + 1
   then "Um_nik"
   else "hhh") |> print_endline


You are given a keyboard that consists of $$$26$$$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word $$$s$$$ on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $$$8$$$, $$$5$$$, $$$12$$$ and $$$15$$$, respectively. Therefore, it will take $$$|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$$$ units of time to type the word "hello". Determine how long it will take to print the word $$$s$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of a description contains a keyboard — a string of length $$$26$$$, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard. The second line of the description contains the word $$$s$$$. The word has a length from $$$1$$$ to $$$50$$$ letters inclusive and consists of lowercase Latin letters.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word $$$s$$$ on the given keyboard.

5
abcdefghijklmnopqrstuvwxyz
hello
abcdefghijklmnopqrstuvwxyz
i
abcdefghijklmnopqrstuvwxyz
codeforces
qwertyuiopasdfghjklzxcvbnm
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
qwertyuiopasdfghjklzxcvbnm
abacaba

open Printf
open Scanf

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

let explode s =
  let n = String.length s in
  let rec iter s idx n acc =
    if idx == n then
      acc
    else
      iter s (idx+1) n ((String.get s idx) :: acc) in
  List.rev (iter s 0 n [])

let time_to_type keyboard word =
  let keyboard_table = Hashtbl.create (String.length keyboard) in
  let add_char_to_map keyboard_table idx char = Hashtbl.add keyboard_table char (idx + 1) in
  let () = String.iteri (add_char_to_map keyboard_table) keyboard in
  let word_list = explode word in
  let rec count_moves keyboard_table word_list acc prev =
    match word_list with
    | [] -> acc
    | h::t -> count_moves keyboard_table t (acc + abs (prev - (Hashtbl.find keyboard_table h))) (Hashtbl.find keyboard_table h) in
  match word_list with
  | [] -> 0
  | h :: t -> count_moves keyboard_table t 0 (Hashtbl.find keyboard_table h)

let () =
  let cases = read_int() in
  for cases = 1 to cases do
    let keyboard = read_string() in
    let word = read_string() in
    printf "%d\n" (time_to_type keyboard word)
  done


The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line — the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited — that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.

The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.

In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "<" (less) character to the left of your lexemes and the ">" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples.

"RUn.exe O" "" "   2ne, " two! . " "
firstarg   second   ""

(* CF Min Frac 281B TODO *)
open Filename;;

(* you can use either gr or rdln but not both *)
let use_input_txt = false;;
let fn = (Filename.dirname Filename.current_dir_name);;
let filename = Filename.concat "." "input.txt";;
let cin = if use_input_txt then Scanf.Scanning.open_in filename
	else Scanf.Scanning.stdin;;

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

let cmd = rdln() ^ " ";;

let rec prilexems lexems = match lexems with
	| [] -> ()
	| hd :: tl ->
			begin
				print_string "<";
				print_string hd;
				print_string ">\n";
				prilexems tl
			end;;

let scanbra s idx = (* idx pos exactly after bracket *)
	let i1 = String.index_from s idx '"' in
	let lex = String.sub s idx (i1 - idx) in
	(lex, i1 +1);;

let scanspace s idx = (* idx - pos of char after space *)
	let i1 = String.index_from s idx ' ' in
	let lex = String.sub s idx (i1 - idx) in
	(lex, i1);;

let rec scancmd s idx acc =
	if idx >= String.length s then acc
	else
		let c = s.[idx] in
		if c = ' ' then scancmd s (idx +1) acc
		else if c = '"' then
			let (lex, nextIdx) = scanbra s (idx +1) in
			scancmd s nextIdx (lex :: acc)
		else
			let (lex, nextIdx) = scanspace s idx in
			scancmd s nextIdx (lex :: acc);;

let main() =
	let ls = scancmd cmd 0 [] in
	let rls = List.rev ls in
	prilexems rls;;

main ();;


You have $$$r$$$ red and $$$b$$$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:   has at least one red bean (or the number of red beans $$$r_i \ge 1$$$);  has at least one blue bean (or the number of blue beans $$$b_i \ge 1$$$);  the number of red and blue beans should differ in no more than $$$d$$$ (or $$$|r_i - b_i| \le d$$$) Can you distribute all beans?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains three integers $$$r$$$, $$$b$$$, and $$$d$$$ ($$$1 \le r, b \le 10^9$$$; $$$0 \le d \le 10^9$$$) — the number of red and blue beans and the maximum absolute difference in each packet.

For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, you can form one packet with $$$1$$$ red and $$$1$$$ blue bean. The absolute difference $$$|1 - 1| = 0 \le d$$$.In the second test case, you can form two packets: $$$1$$$ red and $$$4$$$ blue beans in the first packet and $$$1$$$ red and $$$3$$$ blue beans in the second one.In the third test case, since $$$b = 1$$$, you can form only one packet with $$$6$$$ red and $$$1$$$ blue beans. The absolute difference $$$|6 - 1| = 5 > d$$$.In the fourth test case, since $$$d = 0$$$ so each packet should contain the same number of red and blue beans, but $$$r \neq b$$$.

(** val add : int64 -> int64 -> int64 **)

let rec add = Int64.add

(** val mul : int64 -> int64 -> int64 **)

let rec mul = Int64.mul

module Nat =
 struct
  (** val leb : int64 -> int64 -> bool **)

  let rec leb = (fun x y -> Int64.compare x y <= 0)
 end

(** val can_distribute : int64 -> int64 -> int64 -> bool **)

let can_distribute r b d =
  if Nat.leb b
       (mul r (add d ((fun x -> Int64.succ x) Int64.zero)))
  then Nat.leb r
         (mul b (add d ((fun x -> Int64.succ x) Int64.zero)))
  else false

let rec solve = function
  | 0 -> ()
  | n -> let (r,b,d) = Scanf.scanf "%d %d %d\n" (fun a b c -> (Int64.of_int a, Int64.of_int b,Int64.of_int c)) in
         let ans = if can_distribute r b d then "YES" else "NO" in
         print_endline ans;
         solve (n-1)

let t = read_int();;
solve t;;

(** val add : int -> int -> int **)

let rec add = Int64.add

(** val mul : int -> int -> int **)

let rec mul = Int64.mul

let rec leq x y = Int64.compare x y <= 0

module Nat =
 struct
 end

(** val can_distribute : int -> int -> int -> bool **)

let can_distribute r b d =
  (&&) ((<=) b (mul r (add d (Int64.one))))
    ((<=) r (mul b (add d (Int64.one))))

let rec solve = function
  | 0 -> ()
  | n -> let (r,b,d) = Scanf.scanf "%d %d %d\n" (fun a b c -> (Int64.of_int a, Int64.of_int b,Int64.of_int c)) in
         let ans = if can_distribute r b d then "YES" else "NO" in
         print_endline ans;
         solve (n-1)

let t = read_int();;
solve t;;

(** val add : int -> int -> int **)

let rec add = (+)

(** val mul : int -> int -> int **)

let rec mul = ( * )

module Nat =
 struct
 end

(** val can_distribute : int -> int -> int -> bool **)

let can_distribute r b d =
  (&&) ((<=) b (mul r (add d (Pervasives.succ 0))))
    ((<=) r (mul b (add d (Pervasives.succ 0))))

let rec solve = function
  | 0 -> ()
  | n -> let (r,b,d) = Scanf.scanf "%d %d %d\n" (fun a b c -> (a,b,c)) in
         let ans = if can_distribute r b d then "YES" else "NO" in
         print_endline ans;
         solve (n-1)

let t = read_int();;
solve t;;


"The Chamber of Secrets has been opened again" — this news has spread all around Hogwarts and some of the students have been petrified due to seeing the basilisk. Dumbledore got fired and now Harry is trying to enter the Chamber of Secrets. These aren't good news for Lord Voldemort. The problem is, he doesn't want anybody to be able to enter the chamber. The Dark Lord is going to be busy sucking life out of Ginny.The Chamber of Secrets is an n × m rectangular grid in which some of the cells are columns. A light ray (and a basilisk's gaze) passes through the columns without changing its direction. But with some spell we can make a column magic to reflect the light ray (or the gaze) in all four directions when it receives the ray. This is shown in the figure below.   The left light ray passes through a regular column, and the right ray — through the magic column.  The basilisk is located at the right side of the lower right cell of the grid and is looking to the left (in the direction of the lower left cell). According to the legend, anyone who meets a basilisk's gaze directly dies immediately. But if someone meets a basilisk's gaze through a column, this person will get petrified. We know that the door to the Chamber is located on the left side of the upper left corner of the grid and anyone who wants to enter will look in the direction of its movement (in the direction of the upper right cell) from that position.   This figure illustrates the first sample test.  Given the dimensions of the chamber and the location of regular columns, Lord Voldemort has asked you to find the minimum number of columns that we need to make magic so that anyone who wants to enter the chamber would be petrified or just declare that it's impossible to secure the chamber.

The first line of the input contains two integer numbers n and m (2 ≤ n, m ≤ 1000). Each of the next n lines contains m characters. Each character is either "." or "#" and represents one cell of the Chamber grid. It's "." if the corresponding cell is empty and "#" if it's a regular column.

Print the minimum number of columns to make magic or -1 if it's impossible to do.

NoteThe figure above shows the first sample test. In the first sample we should make both columns magic. The dragon figure represents the basilisk and the binoculars represent the person who will enter the Chamber of secrets. The black star shows the place where the person will be petrified. Yellow lines represent basilisk gaze moving through columns.

exception Found of int

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n "" in
  let () =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%s " (fun s -> s)
    done
  in
  let d = [| (1, 0); (0, 1); (-1, 0); (0, -1) |] in
    if n = 1 then (
      Printf.printf "0\n"
    ) else (
      let h = Array.make n false in
      let v = Array.make m false in
      let u = Array.make_matrix n m false in
      let q1 = Array.make (n * m) (0, 0) in
      let l1 = ref 0 in
      let q2 = Array.make (n * m) (0, 0) in
      let l2 = ref 0 in
      let rec bfs_step k q1 l1 q2 l2 =
	l2 := 0;
	for i = 0 to !l1 - 1 do
	  let (x, y) = q1.(i) in
	  let () =
	    if y = n - 1
	    then raise (Found k)
	  in
	    if not h.(y) then (
	      for x = 0 to m - 1 do
		if a.(y).[x] = '#' then (
		  if not u.(y).(x) then (
		    u.(y).(x) <- true;
		    q2.(!l2) <- (x, y);
		    incr l2
		  );
		);
	      done;
	      h.(y) <- true;
	    );
	    if not v.(x) then (
	      for y = 0 to n - 1 do
		if a.(y).[x] = '#' then (
		  if not u.(y).(x) then (
		    u.(y).(x) <- true;
		    q2.(!l2) <- (x, y);
		    incr l2
		  );
		);
	      done;
	      v.(x) <- true
	    )
	done;
	if !l2 > 0
	then bfs_step (k + 1) q2 l2 q1 l1
      in
	for x = 0 to m - 1 do
	  if a.(0).[x] = '#' then (
	    u.(0).(x) <- true;
	    q1.(!l1) <- (x, 0);
	    incr l1
	  );
	done;
	try
	  bfs_step 1 q1 l1 q2 l2;
	  Printf.printf "-1\n"
	with
	  | Found k ->
	      Printf.printf "%d\n" k;
    )