In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.

The first line contains a single integer m (1 ≤ m ≤ 1000) — the size of the set S. The second line contains m integers s1, s2, ..., sm (1 ≤ si ≤ 106) — the elements of the set S. It's guaranteed that the elements of the set are given in strictly increasing order, that means s1 < s2 < ... < sm.

If there is no solution, print a single line containing -1. Otherwise, in the first line print a single integer n denoting the length of the sequence, n should not exceed 4000. In the second line print n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the sequence. We can show that if a solution exists, then there is a solution with n not exceeding 4000 and ai not exceeding 106. If there are multiple solutions, print any of them.

NoteIn the first example 2 = gcd(4, 6), the other elements from the set appear in the sequence, and we can show that there are no values different from 2, 4, 6 and 12 among gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n.

open Printf
open Scanf

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let gcdf i j f = fold (i+1) j (fun k a -> gcd (f k) a) (f i)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

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

  let d = gcdf 0 (m-1) (fun i -> s.(i)) in

  for i=0 to m-1 do
    s.(i) <- s.(i) / d
  done;

  if not (exists 0 (m-1) (fun i -> s.(i) = 1)) then printf "-1\n" else (
    printf "%d\n" (2*m);

    for i=0 to 2*m-1 do
      if i mod 2 = 0 then printf "%d " (d * s.(i/2)) else printf "%d " d
    done;

    print_newline()
  )


As some of you know, cubism is a trend in art, where the problem of constructing volumetrical shape on a plane with a combination of three-dimensional geometric shapes comes to the fore. A famous sculptor Cicasso, whose self-portrait you can contemplate, hates cubism. He is more impressed by the idea to transmit two-dimensional objects through three-dimensional objects by using his magnificent sculptures. And his new project is connected with this. Cicasso wants to make a coat for the haters of anticubism. To do this, he wants to create a sculpture depicting a well-known geometric primitive — convex polygon.Cicasso prepared for this a few blanks, which are rods with integer lengths, and now he wants to bring them together. The i-th rod is a segment of length li.The sculptor plans to make a convex polygon with a nonzero area, using all rods he has as its sides. Each rod should be used as a side to its full length. It is forbidden to cut, break or bend rods. However, two sides may form a straight angle .Cicasso knows that it is impossible to make a convex polygon with a nonzero area out of the rods with the lengths which he had chosen. Cicasso does not want to leave the unused rods, so the sculptor decides to make another rod-blank with an integer length so that his problem is solvable. Of course, he wants to make it as short as possible, because the materials are expensive, and it is improper deed to spend money for nothing. Help sculptor!

The first line contains an integer n (3 ≤ n ≤ 105) — a number of rod-blanks. The second line contains n integers li (1 ≤ li ≤ 109) — lengths of rods, which Cicasso already has. It is guaranteed that it is impossible to make a polygon with n vertices and nonzero area using the rods Cicasso already has.

Print the only integer z — the minimum length of the rod, so that after adding it it can be possible to construct convex polygon with (n + 1) vertices and nonzero area from all of the rods.

NoteIn the first example triangle with sides {1 + 1 = 2, 2, 1} can be formed from a set of lengths {1, 1, 1, 2}. In the second example you can make a triangle with lengths {20, 11, 4 + 3 + 2 + 1 = 10}.

open Printf
open Scanf

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

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

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

let () =
  let n = read_int () in
  let len = Array.init n (fun _ -> long (read_int())) in
  let maxlen = maxf 0 (n-1) (fun i -> len.(i)) in
  let total = sum 0 (n-1) (fun i -> len.(i)) in
  let rest = total -- maxlen in

  printf "%Ld\n" (maxlen -- rest ++ 1L)


You are given a set of $$$2n+1$$$ integer points on a Cartesian plane. Points are numbered from $$$0$$$ to $$$2n$$$ inclusive. Let $$$P_i$$$ be the $$$i$$$-th point. The $$$x$$$-coordinate of the point $$$P_i$$$ equals $$$i$$$. The $$$y$$$-coordinate of the point $$$P_i$$$ equals zero (initially). Thus, initially $$$P_i=(i,0)$$$.The given points are vertices of a plot of a piecewise function. The $$$j$$$-th piece of the function is the segment $$$P_{j}P_{j + 1}$$$.In one move you can increase the $$$y$$$-coordinate of any point with odd $$$x$$$-coordinate (i.e. such points are $$$P_1, P_3, \dots, P_{2n-1}$$$) by $$$1$$$. Note that the corresponding segments also change.For example, the following plot shows a function for $$$n=3$$$ (i.e. number of points is $$$2\cdot3+1=7$$$) in which we increased the $$$y$$$-coordinate of the point $$$P_1$$$ three times and $$$y$$$-coordinate of the point $$$P_5$$$ one time:  Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum $$$y$$$-coordinate among all initial points in the plot (i.e. points $$$P_0, P_1, \dots, P_{2n}$$$). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of $$$2n+1$$$ vertices and having an area equal to $$$k$$$. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^{18}$$$) — the number of vertices in a plot of a piecewise function and the area we need to obtain.

Print one integer — the minimum possible height of a plot consisting of $$$2n+1$$$ vertices and with an area equals $$$k$$$. It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.

NoteOne of the possible answers to the first example:  The area of this plot is 3, the height of this plot is 1.There is only one possible answer to the second example:  The area of this plot is 12, the height of this plot is 3.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q 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 labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| 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 print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done
	let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" 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 (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
end open MyInt64

let () =
	let n,k = get_2_i64 0
	in
	let a0 = ceildiv k n
	in printf "%Ld\n" a0

let split_on_space (str: string): string list =
	let length = String.length str in
	let is_space: int -> bool =
		fun index ->
			if (index < 0) || (index >= length) then true
			else str.[index] = ' '
	in
	let is_start: int -> bool =
		fun index -> not (is_space index) && is_space (index - 1)
	in
	let is_end: int -> bool =
		fun index -> not (is_space index) && is_space (index + 1)
	in
	let indices = Array.init length (fun i -> i) in
	let indices = Array.to_list indices in
	let start_pos = List.filter is_start indices in
	let end_pos = List.filter is_end indices in
	let make_substring: string list -> int -> int -> string list =
		fun tokens left right ->
			let new_token = String.sub str left (right - left + 1) in
			new_token :: tokens
	in
	let tokens = List.fold_left2 make_substring [] start_pos end_pos in
	List.rev tokens

class reader channel =
	object (this)

	val mutable tokens = []

  method private get_tokens () =
    let new_line = read_line () in
    let tokens = split_on_space new_line in
    match tokens with
    | [] -> this#get_tokens ()
    | _ -> tokens

	method next_string () =
    if (List.length tokens = 0) then tokens <- this#get_tokens();
    let result = List.hd tokens in
    tokens <- List.tl tokens; result

  method next_int () =
    let str = this#next_string() in (Int64.of_string) str

  method next_float () =
    let str = this#next_string() in (float_of_string) str

end

let reader = new reader stdin

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

let compare = Int64.compare
let ( = ) a b = compare a b = 0
let ( < ) a b = compare a b < 0
let ( > ) a b = compare a b > 0
let ( <= ) a b = compare a b <= 0
let ( >= ) a b = compare a b >= 0

let () =
  let n = reader#next_int () in
  let k = reader#next_int () in
  let res = k / n in
  let res = if k % n = Int64.zero then res else res + Int64.one in
  print_endline (Int64.to_string res);

let split_on_space (str: string): string list =
	let length = String.length str in
	let is_space: int -> bool =
		fun index ->
			if (index < 0) || (index >= length) then true
			else str.[index] = ' '
	in
	let is_start: int -> bool =
		fun index -> not (is_space index) && is_space (index - 1)
	in
	let is_end: int -> bool =
		fun index -> not (is_space index) && is_space (index + 1)
	in
	let indices = Array.init length (fun i -> i) in
	let indices = Array.to_list indices in
	let start_pos = List.filter is_start indices in
	let end_pos = List.filter is_end indices in
	let make_substring: string list -> int -> int -> string list =
		fun tokens left right ->
			let new_token = String.sub str left (right - left + 1) in
			new_token :: tokens
	in
	let tokens = List.fold_left2 make_substring [] start_pos end_pos in
	List.rev tokens

class reader channel =
	object (this)

	val mutable tokens = []

  method private get_tokens () =
    let new_line = read_line () in
    let tokens = split_on_space new_line in
    match tokens with
    | [] -> this#get_tokens ()
    | _ -> tokens

	method next_string () =
    if (List.length tokens = 0) then tokens <- this#get_tokens();
    let result = List.hd tokens in
    tokens <- List.tl tokens; result

  method next_int () =
    let str = this#next_string() in (Int64.of_string) str

  method next_float () =
    let str = this#next_string() in (float_of_string) str

end

let reader = new reader stdin

let () =
  let n = reader#next_int () in
  let k = reader#next_int () in
  let res = if n > k then Int64.one else Int64.div k n in
  print_endline (Int64.to_string res);
  flush stdout


Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps:  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \le h_C \le 10^{15}$$$; $$$1 \le d_C \le 10^9$$$) — the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \le h_M \le 10^{15}$$$; $$$1 \le d_M \le 10^9$$$) — the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \le k \le 2 \cdot 10^5$$$; $$$0 \le w \le 10^4$$$; $$$0 \le a \le 10^{10}$$$) — the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.

NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor.

open Printf
open Scanf

let max a b = if a > b then a else b
let min a b = if a < b then a else b

let remove_first s = (String.sub s 1 ((String.length s) - 1))
let remove_last s = (String.sub s 0 ((String.length s) - 1))

let parse_integers s =
  let stream = (Scanning.from_string s) in
  let rec do_parse acc =
    match (Scanf.bscanf stream " %Ld " (fun x -> x :: acc))
  with
    | xs -> do_parse xs
    | exception Scan_failure _ -> acc
    | exception End_of_file -> acc
  in Array.of_list (List.rev (do_parse []));;

let can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =
  let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in
  (* printf "hit = %Ld\n" hit; *)
  if (Int64.compare hit 1L) == 0 then true else (
    let mxdmg = Int64.add 1L (Int64.div (Int64.sub hc 1L) (Int64.sub hit 1L)) in
    (* let (dmg:int64) = Int64.mul dm  in *)
    (* printf "hc %Ld dc %Ld hm %Ld dm %Ld hit %Ld dmg %Ld\n" hc dc hm dm hit mxdmg; *)
    if mxdmg > dm then true else false
  )

let solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =
  let rec try_k (now_k:int64) =
    if now_k > k then false
    else (
      if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true
      else try_k (Int64.add now_k 1L)
    )
  in
  try_k 0L

let rec solve t =
  if t > 0 then (
    let sc = parse_integers (read_line()) in
    let hc = sc.(0) in
    let dc = sc.(1) in
    let sm = parse_integers (read_line()) in
    let hm = sm.(0) in
    let dm = sm.(1) in
    let s = parse_integers (read_line()) in
    let k = s.(0) in
    let w = s.(1) in
    let a = s.(2) in
    (if solve_one hc dc hm dm k w a then "YES" else "NO")
    |> print_endline;
    solve (t - 1)
  )
  else ()

let () =
  let t = int_of_string (read_line()) in
  solve t

open Printf
open Scanf

let max a b = if a > b then a else b
let min a b = if a < b then a else b

let remove_first s = (String.sub s 1 ((String.length s) - 1))
let remove_last s = (String.sub s 0 ((String.length s) - 1))

let parse_integers s =
  let stream = (Scanning.from_string s) in
  let rec do_parse acc =
    match (Scanf.bscanf stream " %Ld " (fun x -> x :: acc))
  with
    | xs -> do_parse xs
    | exception Scan_failure _ -> acc
    | exception End_of_file -> acc
  in Array.of_list (List.rev (do_parse []));;

let can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =
  let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in
  (* printf "hit = %Ld\n" hit; *)
  if (Int64.compare hit 1L) == 0 then true else (
    let mxdmg = Int64.div hc (Int64.sub hit 1L) in
    (* let (dmg:int64) = Int64.mul dm  in *)
    (* printf "hc %Ld dc %Ld hm %Ld dm %Ld hit %Ld dmg %Ld\n" hc dc hm dm hit mxdmg; *)
    if mxdmg > dm then true else false
  )

let solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =
  let rec try_k (now_k:int64) =
    if now_k > k then false
    else (
      if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true
      else try_k (Int64.add now_k 1L)
    )
  in
  try_k 0L

let rec solve t =
  if t > 0 then (
    let sc = parse_integers (read_line()) in
    let hc = sc.(0) in
    let dc = sc.(1) in
    let sm = parse_integers (read_line()) in
    let hm = sm.(0) in
    let dm = sm.(1) in
    let s = parse_integers (read_line()) in
    let k = s.(0) in
    let w = s.(1) in
    let a = s.(2) in
    (if solve_one hc dc hm dm k w a then "YES" else "NO")
    |> print_endline;
    solve (t - 1)
  )
  else ()

let () =
  let t = int_of_string (read_line()) in
  solve t

open Printf
open Scanf

let max a b = if a > b then a else b
let min a b = if a < b then a else b

let remove_first s = (String.sub s 1 ((String.length s) - 1))
let remove_last s = (String.sub s 0 ((String.length s) - 1))

let parse_integers s =
  let stream = (Scanning.from_string s) in
  let rec do_parse acc =
    match (Scanf.bscanf stream " %Ld " (fun x -> x :: acc))
  with
    | xs -> do_parse xs
    | exception Scan_failure _ -> acc
    | exception End_of_file -> acc
  in Array.of_list (List.rev (do_parse []));;

let can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =
  let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in
  if (Int64.compare hit 1L) == 0 then true else (
    let mxdmg = Int64.div hc (Int64.sub hit 1L) in
    (* let (dmg:int64) = Int64.mul dm  in *)
    (* printf "hc %Ld dc %Ld hm %Ld dm %Ld hit %Ld dmg %Ld\n" hc dc hm dm hit mxdmg; *)
    if mxdmg >= dm then true else false
  )

let solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =
  let rec try_k (now_k:int64) =
    if now_k > k then false
    else (
      if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true
      else try_k (Int64.add now_k 1L)
    )
  in
  try_k 0L

let rec solve t =
  if t > 0 then (
    let sc = parse_integers (read_line()) in
    let hc = sc.(0) in
    let dc = sc.(1) in
    let sm = parse_integers (read_line()) in
    let hm = sm.(0) in
    let dm = sm.(1) in
    let s = parse_integers (read_line()) in
    let k = s.(0) in
    let w = s.(1) in
    let a = s.(2) in
    (if solve_one hc dc hm dm k w a then "YES" else "NO")
    |> print_endline;
    solve (t - 1)
  )
  else ()

let () =
  let t = int_of_string (read_line()) in
  solve t

open Printf
open Scanf

let max a b = if a > b then a else b
let min a b = if a < b then a else b

let remove_first s = (String.sub s 1 ((String.length s) - 1))
let remove_last s = (String.sub s 0 ((String.length s) - 1))

let parse_integers s =
  let stream = (Scanning.from_string s) in
  let rec do_parse acc =
    match (Scanf.bscanf stream " %Ld " (fun x -> x :: acc))
  with
    | xs -> do_parse xs
    | exception Scan_failure _ -> acc
    | exception End_of_file -> acc
  in Array.of_list (List.rev (do_parse []));;

let can_alive (hc:int64) (dc:int64) (hm:int64) (dm:int64) =
  let (hit:int64) = Int64.div (Int64.sub (Int64.add hm dc) 1L) dc in
  let (dmg:int64) = Int64.mul dm (Int64.sub hit 1L) in
  (* printf "hc %d dc %d hm %d dm %d hit %d dmg %d\n" hc dc hm dm hit dmg; *)
  if dmg >= hc then false else true

let solve_one (hc:int64) (dc:int64) (hm:int64) (dm:int64) (k:int64) (w:int64) (a:int64) =
  let rec try_k (now_k:int64) =
    if now_k > k then false
    else (
      if can_alive (Int64.add hc (Int64.mul a now_k)) (Int64.add dc (Int64.mul w (Int64.sub k now_k))) hm dm then true
      else try_k (Int64.add now_k 1L)
    )
  in
  try_k 0L

let rec solve t =
  if t > 0 then (
    let sc = parse_integers (read_line()) in
    let hc = sc.(0) in
    let dc = sc.(1) in
    let sm = parse_integers (read_line()) in
    let hm = sm.(0) in
    let dm = sm.(1) in
    let s = parse_integers (read_line()) in
    let k = s.(0) in
    let w = s.(1) in
    let a = s.(2) in
    (if solve_one hc dc hm dm k w a then "YES" else "NO")
    |> print_endline;
    solve (t - 1)
  )
  else ()

let () =
  let t = int_of_string (read_line()) in
  solve t


Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.

The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends. The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.

If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).

NoteThe drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.

open Printf
open Scanf

(*------ union find code *)
let makeset n = Array.make n (-1)
let rec find i p = if p.(i) < 0 then i else (
  p.(i) <- find p.(i) p;
  p.(i);
)
let union i j p =
  (* non-rank union. i and j are canonical elements, i remains canonical *)
  if i<>j then p.(j) <- i
(*------ end union find code *)

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) ++ a) 0L

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

  let uf = makeset n in

  for i=1 to m do
    let (a,b) = read_pair() in
    let (a,b) = (a-1, b-1) in
    let a = find a uf in
    let b = find b uf in
    union a b uf;
  done;

  let size = Array.make n 0 in

  for i=0 to n-1 do
    let comp = find i uf in
    size.(comp) <- size.(comp) + 1
  done;

  let choose2 x =
    let x = long x in
    (x ** (x -- 1L))//2L
  in

  let desired_edges = sum 0 (n-1) (fun i -> choose2 size.(i)) in
  if desired_edges = long m then printf "YES\n" else printf "NO\n"


You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 106) — the number of segments and the value of k. The next n lines contain two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109) each — the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.

First line contains integer m — the smallest number of segments. Next m lines contain two integers aj, bj (aj ≤ bj) — the ends of j-th segment in the answer. The segments should be listed in the order from left to right.

open Scanf
open Printf

let print_list_x l = List.iter (fun (a,b) -> printf "%d %s\n" a (if b = -1 then "starts" else "ends")) l
let print_list l = List.iter (fun (a,b) -> printf "%d %d\n" a b) l

let read_int () = scanf " %d" (fun x -> x)
let read_pair () = scanf " %d %d" (fun x y -> (x,y))
let read_list num =
    let rec pom num acc =
        if num = 0 then acc
        else
            let a,b = read_pair () in
            let x,y = (a, -1), (b, 1) in
            pom (num - 1) (x :: y :: acc)
    in pom num []

let n = read_int ()
let k = read_int ()
let intervals = read_list n

(*let get_result ar =
    let cur = ref (fst( ar.(0)))
    and ind, curind = ref 0, ref 0
    and cnt = ref 0 in
    while !ind < n do
        cnt := 0;
        curind := !ind;
        printf "Having %d \n" (fst(ar.(!curind)));
        while !curind < n && fst(ar.(!curind)) = !cur do
            incr cnt;
            let (a,b) = ar.(!curind) in
            ar.(!curind) <- (a+1, b);
            incr curind
        done;
        let (a,b) = ar.(!ind) in
        if (a > b) then incr ind;
        if !cnt >= k then printf "%d \n" !cur; (* fixme *)
        cur := fst (ar.(!ind))
    done*)

let update_result (level, last, li) (num, state) =
    let nlevel = level - state in
    if nlevel = k && state = -1 then (nlevel, num, li)
    else if level = k && state = 1 then (nlevel, num, (last, num)::li)
    else (nlevel, last, li)

let get_result l =
    let _, _, a = List.fold_left update_result (0, 0, []) l
    in List.rev a
    (*let loop l cnt acc =
        match l with
        | []
        | (a,b)::t ->
    in loop l 0 []*)

let print_result res =
    print_int (List.length res); print_newline ();
    print_list res

let intervals = List.sort compare intervals
let res = get_result intervals
let () = print_result res

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let a = Array.make (2 * n) (0, 0) in
    for i = 0 to n - 1 do
      let l = getnum () in
      let r = getnum () in
	a.(2 * i) <- (l, 0);
	a.(2 * i + 1) <- (r, 1);
    done;
    Array.sort compare a;
    let res = ref [] in
    let cnt = ref 0 in
    let start = ref 0 in
      for i = 0 to 2 * n - 1 do
	let (x, t) = a.(i) in
	  if !cnt >= k
	  then res := (!start, x) :: !res;
	  if t = 0
	  then incr cnt
	  else decr cnt;
	  if !cnt >= k
	  then start := x;
      done;
      let res = List.rev !res in
      let rec combine =
	function
	  | [] -> []
	  | (x1, y1) :: (x2, y2) :: xs when y1 = x2 ->
	      combine ((x1, y2) :: xs)
	  | x :: xs ->
	      x :: combine xs
      in
      let res = combine res in
	Printf.printf "%d\n" (List.length res);
	List.iter (fun (x, y) -> Printf.printf "%d %d\n" x y) res;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make (2 * n) (0, 0) in
    for i = 0 to n - 1 do
      let l = Scanf.bscanf sb "%d " (fun s -> s) in
      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(2 * i) <- (l, 0);
	a.(2 * i + 1) <- (r, 1);
    done;
    Array.sort compare a;
    let res = ref [] in
    let cnt = ref 0 in
    let start = ref 0 in
      for i = 0 to 2 * n - 1 do
	let (x, t) = a.(i) in
	  if !cnt = k
	  then res := (!start, x) :: !res;
	  if t = 0
	  then incr cnt
	  else decr cnt;
	  if !cnt = k
	  then start := x;
      done;
      let res = List.rev !res in
      let rec combine =
	function
	  | [] -> []
	  | (x1, y1) :: (x2, y2) :: xs when y1 = x2 ->
	      combine ((x1, y2) :: xs)
	  | x :: xs ->
	      x :: combine xs
      in
      let res = combine res in
	Printf.printf "%d\n" (List.length res);
	List.iter (fun (x, y) -> Printf.printf "%d %d\n" x y) res;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make (2 * n) (0, 0) in
    for i = 0 to n - 1 do
      let l = Scanf.bscanf sb "%d " (fun s -> s) in
      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(2 * i) <- (l, 0);
	a.(2 * i + 1) <- (r, -1);
    done;
    Array.sort compare a;
    let res = ref [] in
    let cnt = ref 0 in
    let start = ref 0 in
      for i = 0 to 2 * n - 1 do
	let (x, t) = a.(i) in
	  if !cnt = k
	  then res := (!start, x) :: !res;
	  if t = 0
	  then incr cnt
	  else decr cnt;
	  if !cnt = k
	  then start := x;
      done;
      let res = List.rev !res in
      let rec combine =
	function
	  | [] -> []
	  | (x1, y1) :: (x2, y2) :: xs when y1 = x2 ->
	      combine ((x1, y2) :: xs)
	  | x :: xs ->
	      x :: combine xs
      in
      let res = combine res in
	Printf.printf "%d\n" (List.length res);
	List.iter (fun (x, y) -> Printf.printf "%d %d\n" x y) res;


Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7).The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.

The only line contains two integers n, m (1 ≤ n, m ≤ 1013) — the parameters of the sum.

Print integer s — the value of the required sum modulo 109 + 7.

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

let _ =
  let mm = 1000000007L in
  let mmod n =
    let r = Int64.rem n mm in
      if r < 0L
      then r +/ mm
      else r
  in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let n2 = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let isqrt n = int_of_float (sqrt (Int64.to_float n)) in
  let m = isqrt n in
  let res = ref 0L in
  let muld2 x y =
    if Int64.logand x 1L = 0L
    then mmod ((mmod (x // 2L)) */ mmod y)
    else mmod ((mmod (y // 2L)) */ mmod x)
  in
    for i = 1 to Int64.to_int (min n2 (n // Int64.of_int (m + 1))) do
      res := mmod (!res +/ (Int64.rem n (Int64.of_int i)))
    done;
    for i = 1 to m do
      let l = n // Int64.of_int (i + 1) in
      let u = n // Int64.of_int i in
	if l < n2 then (
	  let u = min u n2 in
	    res := !res +/
		muld2 (u -/ l)
		  (n -/ (l +/ 1L) */ Int64.of_int i +/ n -/ u */ Int64.of_int i);
	)
    done;
    let res2 =
      if n2 > n then (
	mmod (mmod (n2 -/ n) */ mmod n)
      ) else 0L
    in
    let res = mmod (res2 +/ !res) in
      Printf.printf "%Ld\n" res

open Big_int

let (+|) = add_big_int
let (-|) = sub_big_int
let ( *| ) = mult_big_int
let (/|) = div_big_int
let bmod = mod_big_int
let (=|) = eq_big_int
let (/=|) a b = not (a =| b)
let (>|) = gt_big_int
let (<|) = lt_big_int
let (>=|) = ge_big_int
let (<=|) = le_big_int

let n0 = zero_big_int
let n1 = unit_big_int
let n2 = big_int_of_int 2

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let n2 = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let isqrt n = int_of_float (sqrt (Int64.to_float n)) in
  let m = isqrt n in
  let res = ref n0 in
    for i = 1 to Int64.to_int (min n2 (n // Int64.of_int (m + 1))) do
      res := !res +| big_int_of_int64 (Int64.rem n (Int64.of_int i))
    done;
    for i = 1 to m do
      let l = n // Int64.of_int (i + 1) in
      let u = n // Int64.of_int i in
	if l < n2 then (
	  let u = min u n2 in
	    res := !res +|
		big_int_of_int64 (u -/ l) *|
		    big_int_of_int64 (n -/ (l +/ 1L) */ Int64.of_int i +/ n -/
					u */ Int64.of_int i) /| (big_int_of_int 2);
	)
    done;
    let res2 =
      if n2 > n then (
	big_int_of_int64 (n2 -/ n) *| big_int_of_int64 n
      ) else n0
    in
    let res = res2 +| !res in
      Printf.printf "%s\n" (string_of_big_int res)

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

let _ =
  let mm = 1000000007L in
  let mmod n =
    let r = Int64.rem n mm in
      if r < 0L
      then r +/ mm
      else r
  in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let n2 = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let isqrt n = int_of_float (sqrt (Int64.to_float n)) in
  let m = isqrt n in
  let res = ref 0L in
  let muld2 x y =
    if Int64.logand x 1L = 0L
    then mmod ((mmod x // 2L) */ mmod y)
    else mmod ((mmod y // 2L) */ mmod x)
  in
    for i = 1 to Int64.to_int (min n2 (n // Int64.of_int (m + 1))) do
      res := mmod (!res +/ (Int64.rem n (Int64.of_int i)))
    done;
    for i = 1 to m do
      let l = n // Int64.of_int (i + 1) in
      let u = n // Int64.of_int i in
	if l < n2 then (
	  let u = min u n2 in
	    res := !res +/
		muld2 (u -/ l)
		  (n -/ (l +/ 1L) */ Int64.of_int i +/ n -/ u */ Int64.of_int i);
	)
    done;
    let res2 =
      if n2 > n then (
	mmod (mmod (n2 -/ n) */ mmod n)
      ) else 0L
    in
    let res = mmod (res2 +/ !res) in
      Printf.printf "%Ld\n" res


Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:  some dwarf in one of the chosen lines is located in the rightmost cell of his row;  some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells.Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.

The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).  Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".

In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.

let s=read_line();;
let i=ref 0;;
while s.[ !i]<>' ' do
   incr i
done;;
let n=int_of_string(String.sub s 0 !i);;
let m=int_of_string(String.sub s ( !i+1) (String.length(s)- !i-1));;
let tab=Array.make (m+1) false;;

let pos c s=
let i=ref 0 in
while s.[ !i]<>c do
   incr i
done;
!i;;

for i=1 to n do
   let s=read_line() in
   let a=(pos 'S' s)-(pos 'G' s) in
   if a<0 then tab.(0)<-true else tab.(a)<-true
done;;

let nb=ref 0;;

for i=1 to m do
   if tab.(i) then incr nb
done;;

if tab.(0) then print_int (-1) else print_int !nb;;

(*let tab=Array.make (m+1) false;;

let pos c s=
let i=ref 0 in
while s.[ !i]<>c do
   incr i
done;
!i;;*)

let s=read_line() in print_string s;;

(*let str=Array.init n (fun i->read_line());;

for i=1 to n do
   let s=str.(i-1) in
   let a=(pos 'S' s)-(pos 'G' s) in
   if a<0 then tab.(0)<-true else tab.(a)<-true
done;;

let nb=ref 0;;

for i=1 to m do
   if tab.(i) then incr nb
done;;

if tab.(0) then print_int (-1) else print_int !nb;;*)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and m=read_int();;
let tab=Array.make (m+1) false;;

let pos c s=
let i=ref 0 in
while s.[ !i]<>c do
   i:= !i+1
done;
!i;;

for i=1 to n do
   let s="S**G" in
   let a=(pos 'S' s)-(pos 'G' s) in
   if a<0 then tab.(0)<-true else tab.(a)<-true
done;;

let nb=ref 0;;

for i=1 to m do
   if tab.(i) then nb:= !nb+1
done;;

if tab.(0) then print_int (-1) else print_int !nb;;


Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively. The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.

Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.

NoteIn the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.In the third sample, the optimal solution is {3, 5} and {7}.

let main () =
   let (n,k) = Scanf.scanf "%d %d" (fun i j -> (i,j)) in
   let tab = Array.make (2 * k) 0 in
       for i=1 to n do
           Scanf.scanf " %d" (fun j -> tab.(n - i) <- j);
       done;
   let res = ref 0 in
       for i=0 to 2*k - 1 do
           res := max !res (tab.(i) + tab.(2 * k - i - 1));
       done;
   Printf.printf "%d" !res;;

main ();;

open Printf
open Scanf

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

let () =
  let n = read_int() in
  let k = read_int() in
  let s = Array.init n (fun _ -> read_int()) in

  let fit size =  (* return true if they fit in k boxes of size s.  Assume s >= s.(n-1) *)
    let rec loop i j count =
      if i = j then count+1 else if i>j then count else (
	if s.(i) + s.(j) > size
	then loop i (j-1) (count+1)
	else loop (i+1) (j-1) (count+1)
      )
    in
    let c = loop 0 (n-1) 0 in
    c <= k
  in

  let rec bsearch lo hi = (* lo fails and hi succeeds *)
    if lo = hi-1 then hi else
      let m = (lo+hi)/2 in
      if fit m then bsearch lo m else bsearch m hi
  in

  let answer = if fit s.(n-1)
    then s.(n-1)
    else bsearch s.(n-1) (2*(s.(n-1)))
  in

  printf "%d\n" answer


Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.

The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.

Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.

NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.

open Printf
open Scanf

type direction = Left | Right

let next d i =
  match d with
  | Left  -> i - 1
  | Right -> i + 1

let rec collect a changes info d i =
  (*printf "%d %d %d\n%!" changes info i;*)
  if info = Array.length a || changes > 10000 then
    changes
  else if i < 0 then
    collect a (changes + 1) info Right 0
  else if i >= Array.length a then
    collect a (changes + 1) info Left (Array.length a - 1)
  else if a.(i) <= info && a.(i) >= 0 then begin
      (*printf "collected %d\n%!" i;*)
      a.(i) <- -1;
      collect a changes (info + 1) d (next d i)
    end
  else
    collect a changes info d (next d i)

let () =
  let _ = read_int () in
  let s = read_line () in
  let l = List.map int_of_string (Str.split (Str.regexp " +") s) in
  let a = Array.of_list l in
  let res = collect a 0 0 Right 0 in
  printf "%d\n%!" res;

open Printf
open Scanf

type direction = Left | Right

let next d i =
  match d with
  | Left  -> i - 1
  | Right -> i + 1

let rec collect a changes info d i =
  (*printf "%d %d %d\n%!" changes info i;*)
  if info = Array.length a then
    changes
  else if i < 0 then
    collect a (changes + 1) info Right 0
  else if i >= Array.length a then
    collect a (changes + 1) info Left (Array.length a - 1)
  else if a.(i) <= info && a.(i) >= 0 then begin
      (*printf "collected %d\n%!" i;*)
      a.(i) <- -1;
      collect a changes (info + 1) d (next d i)
    end
  else
    collect a changes info d (next d i)

let () =
  let _ = read_int () in
  let s = read_line () in
  let l = List.map int_of_string (Str.split (Str.regexp " +") s) in
  let a = Array.of_list l in
  let l_res = 99 (*collect a 0 0 Left (Array.length a - 1)*) in
  let r_res = collect a 0 0 Right 0 in
  printf "%d\n%!" (min l_res r_res);

open Printf
open Scanf

type direction = Left | Right

let next d i =
  match d with
  | Left  -> i - 1
  | Right -> i + 1

let rec collect a changes info d i =
  (*printf "%d %d %d\n%!" changes info i;*)
  if info = Array.length a || changes > 1000000 then
    changes
  else if i < 0 then
    collect a (changes + 1) info Right 0
  else if i >= Array.length a then
    collect a (changes + 1) info Left (Array.length a - 1)
  else if a.(i) <= info && a.(i) >= 0 then begin
      (*printf "collected %d\n%!" i;*)
      a.(i) <- -1;
      collect a changes (info + 1) d (next d i)
    end
  else
    collect a changes info d (next d i)

let () =
  let _ = read_int () in
  let s = read_line () in
  let l = List.map int_of_string (Str.split (Str.regexp " +") s) in
  let a = Array.of_list l in
  let i = ref 0 in
  while a.(!i) > 0 do
    i := !i + 1
  done;
  let l_res = collect a 0 0 Left !i in
  let r_res = collect a 0 0 Right !i in
  printf "%d\n%!" (min l_res r_res);

open Printf
open Scanf

type direction = Left | Right

let next d i =
  match d with
  | Left  -> i - 1
  | Right -> i + 1

let rec collect a changes info d i =
  (*printf "%d %d %d\n%!" changes info i;*)
  if info = Array.length a || changes > 1000000 then
    changes
  else if i < 0 then
    collect a (changes + 1) info Right 0
  else if i >= Array.length a then
    collect a (changes + 1) info Left (Array.length a - 1)
  else if a.(i) <= info && a.(i) >= 0 then begin
      (*printf "collected %d\n%!" i;*)
      a.(i) <- -1;
      collect a changes (info + 1) d (next d i)
    end
  else
    collect a changes info d (next d i)

let () =
  let _ = read_int () in
  let s = read_line () in
  let l = List.map int_of_string (Str.split (Str.regexp " +") s) in
  let a = Array.of_list l in
  let l_res = collect a 0 0 Left (Array.length a - 1) in
  let r_res = collect a 0 0 Right 0 in
  printf "%d\n%!" (min l_res r_res);


You have an $$$n \times n$$$ chessboard and $$$k$$$ rooks. Rows of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from top to bottom and columns of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and collumn $$$y$$$ for $$$1 \leq x \leq n$$$ and $$$1 \leq y \leq n$$$.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side.  Such arrangement of $$$3$$$ rooks on the $$$4 \times 4$$$ chessboard is good, but it is not stable: the rook from $$$(1, 1)$$$ can be moved to the adjacent cell $$$(2, 1)$$$ and rooks on cells $$$(2, 1)$$$ and $$$(2, 4)$$$ will beat each other. Please, find any stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard or report that there is no such arrangement.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq k \leq n \leq 40$$$) — the size of the chessboard and the number of rooks.

If there is a stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard, output $$$n$$$ lines of symbols . and R. The $$$j$$$-th symbol of the $$$i$$$-th line should be equals R if and only if there is a rook on the cell $$$(i, j)$$$ in your arrangement. If there are multiple solutions, you may output any of them. If there is no stable arrangement, output $$$-1$$$.

NoteIn the first test case, you should find stable arrangement of $$$2$$$ rooks on the $$$3 \times 3$$$ chessboard. Placing them in cells $$$(3, 1)$$$ and $$$(1, 3)$$$ gives stable arrangement.In the second test case it can be shown that it is impossbile to place $$$3$$$ rooks on the $$$3 \times 3$$$ chessboard to get stable arrangement.

(* Codeforces 1621 A Stable Arrangement of Rooks, train, *)
(* on their computer runtime error ???? (((((  *)

(* 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;;

let do_one () =
    let n = gr() in (* field size *)
    let k = gr() in (* number of rooks *)
    if k > (n + 1) / 2 then
        print_string "-1\n"
    else
        for i = 1 to n do
            let s = if ((i mod 2) == 0) || (i > 2*k) then String.make n '.'
                        else (String.make (i-1) '.') ^ "R" ^ (String.make (n - i) '.') in
            let se = s ^ "\n" in
            print_string se
        done;;

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

let main() =
	let st = rdln () in
	let t = int_of_string st in
	do_all t;;

main();;


Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.In the bookshop, Jack decides to buy two books of different genres.Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.The books are given by indices of their genres. The genres are numbered from 1 to m.

The first line contains two positive integers n and m (2 ≤ n ≤ 2·105, 2 ≤ m ≤ 10) — the number of books in the bookstore and the number of genres. The second line contains a sequence a1, a2, ..., an, where ai (1 ≤ ai ≤ m) equals the genre of the i-th book. It is guaranteed that for each genre there is at least one book of that genre.

Print the only integer — the number of ways in which Jack can choose books. It is guaranteed that the answer doesn't exceed the value 2·109.

NoteThe answer to the first test sample equals 5 as Sasha can choose:  the first and second books,  the first and third books,  the first and fourth books,  the second and third books,  the third and fourth books.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make m 0 in
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
      let k = k - 1 in
	a.(k) <- a.(k) + 1
    done;
    let res = ref 0L in
      for i = 0 to m - 1 do
	for j = i + 1 to m - 1 do
	  res := !res +| Int64.of_int a.(i) *| Int64.of_int a.(j)
	done
      done;
      Printf.printf "%Ld\n" !res

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let ( ++ ) a b = Int64.add a b
let ( ** ) a b = Int64.mul a b
let long x = Int64.of_int x
let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))

let () =

  let n = read_int() in
  let m = read_int() in
  let a = Array.init n (fun _ -> read_int()) in

  let count = Array.make (m+1) 0L in

  for i=0 to n-1 do
    count.(a.(i)) <- 1L ++ count.(a.(i))
  done;

  let answer =
    sum 1 (m-1) (fun i -> sum (i+1) m (fun j -> count.(i)**count.(j)) 0L) 0L
  in

  printf "%Ld\n" answer


Polycarp is a head of a circus troupe. There are $$$n$$$ — an even number — artists in the troupe. It is known whether the $$$i$$$-th artist can perform as a clown (if yes, then $$$c_i = 1$$$, otherwise $$$c_i = 0$$$), and whether they can perform as an acrobat (if yes, then $$$a_i = 1$$$, otherwise $$$a_i = 0$$$).Split the artists into two performances in such a way that:   each artist plays in exactly one performance,  the number of artists in the two performances is equal (i.e. equal to $$$\frac{n}{2}$$$),  the number of artists that can perform as clowns in the first performance is the same as the number of artists that can perform as acrobats in the second performance.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5\,000$$$, $$$n$$$ is even) — the number of artists in the troupe. The second line contains $$$n$$$ digits $$$c_1 c_2 \ldots c_n$$$, the $$$i$$$-th of which is equal to $$$1$$$ if the $$$i$$$-th artist can perform as a clown, and $$$0$$$ otherwise. The third line contains $$$n$$$ digits $$$a_1 a_2 \ldots a_n$$$, the $$$i$$$-th of which is equal to $$$1$$$, if the $$$i$$$-th artist can perform as an acrobat, and $$$0$$$ otherwise.

Print $$$\frac{n}{2}$$$ distinct integers — the indices of the artists that should play in the first performance. If there are multiple answers, print any. If there is no solution, print a single integer $$$-1$$$.

NoteIn the first example, one of the possible divisions into two performances is as follows: in the first performance artists $$$1$$$ and $$$4$$$ should take part. Then the number of artists in the first performance who can perform as clowns is equal to $$$1$$$. And the number of artists in the second performance who can perform as acrobats is $$$1$$$ as well.In the second example, the division is not possible.In the third example, one of the possible divisions is as follows: in the first performance artists $$$3$$$ and $$$4$$$ should take part. Then in the first performance there are $$$2$$$ artists who can perform as clowns. And the number of artists in the second performance who can perform as acrobats is $$$2$$$ as well.

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_char _  = bscanf Scanning.stdin " %c " (fun x -> Char.(code x - code '0'))

let rec zip_with f a b =
  match a,b with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys -> (f x y) :: zip_with f xs ys

let rec loop ab none a c both =
  let rec inner aa =
    if aa > a
    then loop (ab+1) none a c both
    else
      let k = ab + aa in
      let cc = k - (both - ab) in
      let ka = k + (c - cc) in
      let kc = a - aa + (both - ab) + cc in
      let an = max 0 (kc-ka) + (none - abs (kc-ka))/2 in
      if cc > c || cc < 0 || abs (kc-ka) > none
      then inner (aa+1)
      else Some (an,aa,c-cc,ab) in
  if ab > both
  then None
  else inner 0

let rec make_ans n a c b i = function
  | 0 :: rest when n > 0 -> i :: make_ans (n-1) a c b (i+1) rest
  | 1 :: rest when a > 0 -> i :: make_ans n (a-1) c b (i+1) rest
  | 2 :: rest when c > 0 -> i :: make_ans n a (c-1) b (i+1) rest
  | 3 :: rest when b > 0 -> i :: make_ans n a c (b-1) (i+1) rest
  | x :: rest -> make_ans n a c b (i+1) rest
  | _ -> []

let () =
  let n = read_int () in
  let s = Array.(init n read_char |> to_list) in
  let t = Array.(init n read_char |> to_list) in
  let ca = zip_with (fun x y -> x lor (y lsl 1)) s t in
  let cnt = Array.make 4 0 in
  let () = List.iter (fun v -> cnt.(v) <- cnt.(v) + 1) ca in
  match loop 0 cnt.(0) cnt.(1) cnt.(2) cnt.(3) with
  | Some (n,a,c,b) ->
    let ans = make_ans n a c b 0 ca in
    let ans = List.map (fun v -> sprintf "%d" (v+1)) ans |> String.concat " " in
    printf "%s\n" ans
  | None -> printf "-1\n"


It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.There are $$$n$$$ displays placed along a road, and the $$$i$$$-th of them can display a text with font size $$$s_i$$$ only. Maria Stepanovna wants to rent such three displays with indices $$$i < j < k$$$ that the font size increases if you move along the road in a particular direction. Namely, the condition $$$s_i < s_j < s_k$$$ should be held.The rent cost is for the $$$i$$$-th display is $$$c_i$$$. Please determine the smallest cost Maria Stepanovna should pay.

The first line contains a single integer $$$n$$$ ($$$3 \le n \le 3\,000$$$) — the number of displays. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 10^9$$$) — the font sizes on the displays in the order they stand along the road. The third line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \le c_i \le 10^8$$$) — the rent costs for each display.

If there are no three displays that satisfy the criteria, print -1. Otherwise print a single integer — the minimum total rent cost of three displays with indices $$$i < j < k$$$ such that $$$s_i < s_j < s_k$$$.

NoteIn the first example you can, for example, choose displays $$$1$$$, $$$4$$$ and $$$5$$$, because $$$s_1 < s_4 < s_5$$$ ($$$2 < 4 < 10$$$), and the rent cost is $$$40 + 10 + 40 = 90$$$.In the second example you can't select a valid triple of indices, so the answer is -1.

let input_int_array n =
  Array.init n (fun i -> Scanf.scanf " %d" (fun i -> i))

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

let discretize src =
  let set = src |> Array.to_list |> IntSet.of_list in
  let map = Hashtbl.create (Array.length src) in
  set |> IntSet.elements |> List.iteri (fun i v -> Hashtbl.add map v i);
  Array.map (fun i -> Hashtbl.find map i) src

let _ =
  let n = Scanf.scanf " %d" (fun i -> i) in
  let font_sizes = input_int_array n in
  let costs = input_int_array n in
  (* let font_sizes = font_sizes_raw |> discretize in *)

  let dp: (int option) array = Array.make n None in
  for i = 1 to n - 2 do
    for j = 0 to i - 1 do
      if font_sizes.(i) > font_sizes.(j) then
        let v = costs.(j) in
        match dp.(i) with
        | Some x when v < x -> dp.(i) <- Some v
        | None -> dp.(i) <- Some v
        | _ -> ()
    done
  done;
  Array.iteri (fun i v -> dp.(i) <-
    match v with | Some v -> Some (v + costs.(i)) | x -> x) dp;

  let ret = ref None in
  for i = 2 to n - 1 do
    for j = 1 to i - 1 do
      match dp.(j) with
      | None -> ()
      | Some v ->
        if font_sizes.(i) > font_sizes.(j) then
            let v = v + costs.(i) in
            match !ret with
            | Some x when v < x -> ret := Some v
            | None -> ret := Some v
            | _ -> ()
    done
  done;

  (match !ret with | None -> -1 | Some x -> x)
    |> string_of_int |> print_endline

(* x^y ? y^x *)
(* so much special cases ... *)

let compare x y =
  if x > y then `Greater
  else if x < y
  then `Less
  else `Equal

let serialize_pow = function
  | `Greater -> ">"
  | `Less -> "<"
  | `Equal -> "="

let invert = function
  | `Greater -> `Less
  | `Less -> `Greater
  | `Equal -> `Equal

let compute (x, y) =
  match x, y with
  | 2, 4 | 4, 2 -> `Equal
  | _, 1 | 1, _ | 2, 3 | 3, 2 -> compare x y
  | x, y -> compare x y |> invert

let _ =
  let x, y = Scanf.scanf " %d %d" (fun x y -> (x, y)) in
  (x, y) |> compute |> serialize_pow |> print_endline


A Christmas party in city S. had n children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to m, and the children are numbered from 1 to n. Then the i-th child has both mittens of color ci.The Party had Santa Claus ('Father Frost' in Russian), his granddaughter Snow Girl, the children danced around the richly decorated Christmas tree. In fact, everything was so bright and diverse that the children wanted to wear mittens of distinct colors. The children decided to swap the mittens so that each of them got one left and one right mitten in the end, and these two mittens were of distinct colors. All mittens are of the same size and fit all the children.The children started exchanging the mittens haphazardly, but they couldn't reach the situation when each child has a pair of mittens of distinct colors. Vasily Petrov, the dad of one of the children, noted that in the general case the children's idea may turn out impossible. Besides, he is a mathematician and he came up with such scheme of distributing mittens that the number of children that have distinct-colored mittens was maximum. You task is to repeat his discovery. Note that the left and right mittens are different: each child must end up with one left and one right mitten.

The first line contains two integers n and m — the number of the children and the number of possible mitten colors (1 ≤ n ≤ 5000, 1 ≤ m ≤ 100). The second line contains n integers c1, c2, ... cn, where ci is the color of the mittens of the i-th child (1 ≤ ci ≤ m).

In the first line, print the maximum number of children who can end up with a distinct-colored pair of mittens. In the next n lines print the way the mittens can be distributed in this case. On the i-th of these lines print two space-separated integers: the color of the left and the color of the right mitten the i-th child will get. If there are multiple solutions, you can print any of them.

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

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

let a = Array.init n (fun _ -> let x = read_int() in (x,x)) in

let swap i j =
  let (xi, yi),(xj, yj) = a.(i),a.(j) in
  begin
    a.(i) <- (xi, yj);
    a.(j) <- (xj, yi);
  end in

let rec f i j =
  if i = Array.length a || j = Array.length a then ()
  else if i = j || fst a.(i) = fst a.(j) then f i (j+1)
  else begin
    swap i j;
    f (i+1) (j+1);
  end
  in f 0 0;

let rec f i =
  if i = Array.length a then ()
  else begin
    let rec g j =
      if j = Array.length a then ()
      else if fst a.(i) <> fst a.(j) && fst a.(i) <> snd a.(j) then
      begin
        swap i j;
      end
      else g (j+1)
      in
    if fst a.(i) = snd a.(i) then g 0;
    f (i+1);
  end
  in f 0;

Printf.printf "%d\n" (Array.fold_left (fun acc (x,y) -> acc + (if x <> y then 1 else 0)) 0 a);
Array.iter (fun (x,y) -> Printf.printf "%d %d\n" x y) a;


In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners:That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an.Your task is to paint a cardiogram by given sequence ai.

The first line contains integer n (2 ≤ n ≤ 1000). The next line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 1000). It is guaranteed that the sum of all ai doesn't exceed 1000.

Print max |yi - yj| lines (where yk is the y coordinate of the k-th point of the polyline), in each line print  characters. Each character must equal either « / » (slash), « \ » (backslash), « » (space). The printed image must be the image of the given polyline. Please study the test samples for better understanding of how to print a cardiogram. Note that in this problem the checker checks your answer taking spaces into consideration. Do not print any extra characters. Remember that the wrong answer to the first pretest doesn't give you a penalty.

NoteDue to the technical reasons the answers for the samples cannot be copied from the statement. We've attached two text documents with the answers below.http://assets.codeforces.com/rounds/435/1.txthttp://assets.codeforces.com/rounds/435/2.txt

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let tab=Array.make (n+1) 0;;
let sum=Array.make (n+1) 0;;
let s=ref 0;;

let puiss i=if (i mod 2)=0 then (-1) else 1;;

for i=1 to n do
   let x=(puiss i)*read_int() in
   tab.(i)<-x;
   sum.(i)<-x+sum.(i-1);
   s:= !s+abs(x)
done;;

let rec maxi a b=
   if (a=b) then sum.(a) else max sum.(a) (maxi (a+1) b );;
let rec mini a b=
   if (a=b) then sum.(a) else min sum.(a) (mini (a+1) b );;

let p=maxi 1 n;;
let m=min 0 (mini 1 n);;

let mat=Array.make_matrix (p-m) !s " ";;

let i=ref (max 0 ((-1)*m));;
let j=ref 0;;

for k=1 to n do
   for l=1 to abs(tab.(k)) do
      if tab.(k)<0 then
         begin
         mat.(!i).(!j)<-"\\";
         if l=abs(tab.(k)) then incr j
         else (incr j;decr i)
         end
      else
         begin
         mat.(!i).(!j)<-"/";
         if l=abs(tab.(k)) then incr j
         else (incr j;incr i);
         end
   done
done;;

for i=(p-m-1) downto 0 do
   for j=0 to !s-1 do
      print_string mat.(i).(j)
   done;
   print_newline()
done;;


Polycarpus enjoys studying Berland hieroglyphs. Once Polycarp got hold of two ancient Berland pictures, on each of which was drawn a circle of hieroglyphs. We know that no hieroglyph occurs twice in either the first or the second circle (but in can occur once in each of them).Polycarpus wants to save these pictures on his laptop, but the problem is, laptops do not allow to write hieroglyphs circles. So Polycarp had to break each circle and write down all of its hieroglyphs in a clockwise order in one line. A line obtained from the first circle will be called a, and the line obtained from the second one will be called b.There are quite many ways to break hieroglyphic circles, so Polycarpus chooses the method, that makes the length of the largest substring of string a, which occurs as a subsequence in string b, maximum.Help Polycarpus — find the maximum possible length of the desired substring (subsequence) if the first and the second circles are broken optimally.The length of string s is the number of characters in it. If we denote the length of string s as |s|, we can write the string as s = s1s2... s|s|.A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings of "codeforces", while "coders" is not. A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces".

The first line contains two integers la and lb (1 ≤ la, lb ≤ 1000000) — the number of hieroglyphs in the first and second circles, respectively. Below, due to difficulties with encoding of Berland hieroglyphs, they are given as integers from 1 to 106. The second line contains la integers — the hieroglyphs in the first picture, in the clockwise order, starting with one of them. The third line contains lb integers — the hieroglyphs in the second picture, in the clockwise order, starting with one of them. It is guaranteed that the first circle doesn't contain a hieroglyph, which occurs twice. The second circle also has this property.

Print a single number — the maximum length of the common substring and subsequence. If at any way of breaking the circles it does not exist, print 0.

NoteIn the first test Polycarpus picks a string that consists of hieroglyphs 5 and 1, and in the second sample — from hieroglyphs 1, 3 and 5.

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let la = getnum () in
  let lb = getnum () in
  let a = Array.make la 0 in
  let b = Array.make lb 0 in
  let () =
    for i = 0 to la - 1 do
      a.(i) <- getnum () - 1
    done;
    for i = 0 to lb - 1 do
      b.(i) <- getnum () - 1
    done;
  in
  let c = Array.make 1000000 (-1) in
  let res = ref 0 in
  let max (x : int) y = if x > y then x else y in
  let j = ref 0 in
  let next x =
    if x = la - 1
    then 0
    else x + 1
  in
    for i = 0 to lb - 1 do
      c.(b.(i)) <- i
    done;
    for i = 0 to la - 1 do
      if next !j = i
      then j := i;
      if c.(a.(i)) >= 0 then (
	while next !j <> i &&
	  c.(a.(next !j)) <> -1 &&
	  (c.(a.(!j)) < c.(a.(i)) &&
	     (c.(a.(next !j)) > c.(a.(!j)) && c.(a.(next !j)) < c.(a.(i))) ||
	     c.(a.(!j)) >= c.(a.(i)) &&
	     (c.(a.(next !j)) > c.(a.(!j)) || c.(a.(next !j)) < c.(a.(i))))
	do
	  j := next !j;
	done;
	(*Printf.printf "asd %d %d\n" i !j;*)
	let l = if !j >= i then !j - i + 1 else !j + la - i + 1 in
	  res := max !res l
      )
    done;
    Printf.printf "%d\n" !res

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let la = getnum () in
  let lb = getnum () in
  let a = Array.make la 0 in
  let b = Array.make lb 0 in
  let () =
    for i = 0 to la - 1 do
      a.(i) <- getnum () - 1
    done;
    for i = 0 to lb - 1 do
      b.(i) <- getnum () - 1
    done;
  in
  let c = Array.make 1000000 (-1) in
  let res = ref 0 in
  let max (x : int) y = if x > y then x else y in
  let j = ref 0 in
  let next x =
    if x = la - 1
    then 0
    else x + 1
  in
    for i = 0 to lb - 1 do
      c.(b.(i)) <- i
    done;
    for i = 0 to la - 1 do
      if !j = next i
      then j := i;
      if c.(a.(i)) >= 0 then (
	while next !j <> i &&
	  c.(a.(next !j)) <> -1 &&
	  (c.(a.(!j)) < c.(a.(i)) &&
	     (c.(a.(next !j)) > c.(a.(!j)) && c.(a.(next !j)) < c.(a.(i))) ||
	     c.(a.(!j)) >= c.(a.(i)) &&
	     (c.(a.(next !j)) > c.(a.(!j)) || c.(a.(next !j)) < c.(a.(i))))
	do
	  j := next !j;
	done;
	(*Printf.printf "asd %d %d\n" i !j;*)
	let l = if !j >= i then !j - i + 1 else !j + la - i + 1 in
	  res := max !res l
      )
    done;
    Printf.printf "%d\n" !res


Luca has a cypher made up of a sequence of $$$n$$$ wheels, each with a digit $$$a_i$$$ written on it. On the $$$i$$$-th wheel, he made $$$b_i$$$ moves. Each move is one of two types:   up move (denoted by $$$\texttt{U}$$$): it increases the $$$i$$$-th digit by $$$1$$$. After applying the up move on $$$9$$$, it becomes $$$0$$$.  down move (denoted by $$$\texttt{D}$$$): it decreases the $$$i$$$-th digit by $$$1$$$. After applying the down move on $$$0$$$, it becomes $$$9$$$.     Example for $$$n=4$$$. The current sequence is 0 0 0 0. Luca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of wheels. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$0 \leq a_i \leq 9$$$) — the digit shown on the $$$i$$$-th wheel after all moves have been performed. Then $$$n$$$ lines follow, the $$$i$$$-th of which contains the integer $$$b_i$$$ ($$$1 \leq b_i \leq 10$$$) and $$$b_i$$$ characters that are either $$$\texttt{U}$$$ or $$$\texttt{D}$$$ — the number of moves performed on the $$$i$$$-th wheel, and the moves performed. $$$\texttt{U}$$$ and $$$\texttt{D}$$$ represent an up move and a down move respectively.

For each test case, output $$$n$$$ space-separated digits  — the initial sequence of the cypher.

3

3

9 3 1

3 DDD

4 UDUU

2 DU

2

0 9

9 DDDDDDDDD

9 UUUUUUUUU

5

0 5 9 8 3

10 UUUUUUUUUU

3 UUD

8 UUDUUDDD

10 UUDUUDUDDU

4 UUUU

NoteIn the first test case, we can prove that initial sequence was $$$[2,1,1]$$$. In that case, the following moves were performed:   On the first wheel: $$$2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{D}]{} 9$$$.  On the second wheel: $$$1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{D}]{} 1 \xrightarrow[\texttt{U}]{} 2 \xrightarrow[\texttt{U}]{} 3$$$.  On the third wheel: $$$1 \xrightarrow[\texttt{D}]{} 0 \xrightarrow[\texttt{U}]{} 1$$$.  The final sequence was $$$[9,3,1]$$$, which matches the input.

(* From @Darooha's code (https://codeforces.com/profile/Darooha) *)

open Printf
open Scanf

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

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

(* Main Code file *)

let rec sum = function
        | [] -> 0
        | h::t -> h + sum(t)

let () =
    let t = read_int() in
    for i=1 to t do
        let n = read_int() in
        let arr = Array.init n read_int in
        for j=0 to n-1 do
            let m = read_int() in
            let s = read_string() in
            for k=0 to m-1 do
                if s.[k] = 'U' then
                    arr.(j) <- arr.(j)-1
                else
                    arr.(j) <- arr.(j)+1
            done;
            printf "%d " (((arr.(j) mod 10) + 10) mod 10)
        done;
        print_newline()
    done;


Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?

In the first line of the input integer n (1 ≤ n ≤ 105) is given — the number of vertices in the tree. In the second line the sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 109) is given, where ai is the number written on vertex i. The next n - 1 lines describe tree edges: ith of them consists of two integers pi and ci (1 ≤ pi ≤ n,  - 109 ≤ ci ≤ 109), meaning that there is an edge connecting vertices i + 1 and pi with number ci written on it.

Print the only integer — the minimum number of leaves Alyona needs to remove such that there will be no any sad vertex left in the tree.

NoteThe following image represents possible process of removing leaves from the tree:

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0L in
  let es = Array.make n [] in
  let () =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
    for i = 1 to n - 1 do
      let p = Scanf.bscanf sb "%d " (fun s -> s) in
      let c = Scanf.bscanf sb "%Ld " (fun s -> s) in
	es.(p - 1) <- (i, c) :: es.(p - 1)
    done;
  in
  let es = Array.map Array.of_list es in
  let res = ref 0 in
  let rec dfs u s =
    if s < 0L || s > a.(u)
    then incr res;
    for i = 0 to Array.length es.(u) - 1 do
	let (v, c) = es.(u).(i) in
	  if s < 0L || s > a.(u)
	  then dfs v (-1L)
	  else (
	    let s = max 0L (s +| c) in
	      dfs v s
	  )
    done
  in
    dfs 0 0L;
    Printf.printf "%d\n" !res

open Printf
open Scanf

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

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

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

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> long (read_int())) in

  let tree = Array.make n [] in
  let c = Array.make n 0L in
  let add_edge i j =
    tree.(i) <- j::tree.(i);
    tree.(j) <- i::tree.(j)
  in

  for i = 1 to n-1 do
    let p = -1 + read_int() in
    c.(i) <- long (read_int());
    add_edge i p
  done;

  let mark = Array.make n false in

  let rec dfs v p dist =
    List.iter (fun w ->
      if w <> p then (
	let dist = max 0L (dist ++ c.(w)) in
	dfs w v dist;
	if dist > a.(w) then mark.(w) <- true
      )
    ) tree.(v)
  in

  dfs 0 (-1) 0L;

  let rec dfs2 v p =
    if mark.(v) then 0 else (
      List.fold_left (fun ac w ->
	if w = p then ac else ac + (dfs2 w v)
      ) 1 tree.(v)
    )
  in

  let good_count = dfs2 0 (-1) in

  printf "%d\n" (n - good_count)

open Printf
open Scanf

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

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

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

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> long (read_int())) in

  let tree = Array.make n [] in
  let c = Array.make n 0L in
  let add_edge i j =
    tree.(i) <- j::tree.(i);
    tree.(j) <- i::tree.(j)
  in

  for i = 1 to n-1 do
    let p = -1 + read_int() in
    c.(i) <- long (read_int());
    add_edge i p
  done;

  let mark = Array.make n false in

  let rec dfs v p dist =
    List.iter (fun w ->
      if w <> p then (
	let dist = dist ++ c.(w) in
	dfs w v dist;
	if dist > a.(w) then mark.(w) <- true
      )
    ) tree.(v)
  in

  dfs 0 (-1) 0L;

  let rec dfs2 v p =
    if mark.(v) then 0 else (
      List.fold_left (fun ac w ->
	if w = p then ac else ac + (dfs2 w v)
      ) 1 tree.(v)
    )
  in

  let good_count = dfs2 0 (-1) in

  printf "%d\n" (n - good_count)


It was decided in IT City to distinguish successes of local IT companies by awards in the form of stars covered with gold from one side. To order the stars it is necessary to estimate order cost that depends on the area of gold-plating. Write a program that can calculate the area of a star.A "star" figure having n ≥ 5 corners where n is a prime number is constructed the following way. On the circle of radius r n points are selected so that the distances between the adjacent ones are equal. Then every point is connected by a segment with two maximally distant points. All areas bounded by the segments parts are the figure parts.

The only line of the input contains two integers n (5 ≤ n < 109, n is prime) and r (1 ≤ r ≤ 109) — the number of the star corners and the radius of the circumcircle correspondingly.

Output one number — the star area. The relative error of your answer should not be greater than 10 - 7.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%f " (fun s -> s) in
  let r = Scanf.bscanf sb "%f " (fun s -> s) in
  let pi = 4.0 *. atan 1.0 in
  let alpha = pi /. n in
  let a = r *. sin alpha /. sin (pi -. 1.5 *. alpha) in
  let b = r *. sin (alpha /. 2.0) /. sin (pi -. 1.5 *. alpha) in
  let s =
    r *. r *. sin alpha *. sin (alpha /. 2.0) /.
      (2.0 *. sin (1.5 *. alpha))
  in
  let res = 2.0 *. n *. s in
    Printf.printf "%.9f\n" res


A dragon symbolizes wisdom, power and wealth. On Lunar New Year's Day, people model a dragon with bamboo strips and clothes, raise them with rods, and hold the rods high and low to resemble a flying dragon.A performer holding the rod low is represented by a 1, while one holding it high is represented by a 2. Thus, the line of performers can be represented by a sequence a1, a2, ..., an.Little Tommy is among them. He would like to choose an interval [l, r] (1 ≤ l ≤ r ≤ n), then reverse al, al + 1, ..., ar so that the length of the longest non-decreasing subsequence of the new sequence is maximum.A non-decreasing subsequence is a sequence of indices p1, p2, ..., pk, such that p1 < p2 < ... < pk and ap1 ≤ ap2 ≤ ... ≤ apk. The length of the subsequence is k.

The first line contains an integer n (1 ≤ n ≤ 2000), denoting the length of the original sequence. The second line contains n space-separated integers, describing the original sequence a1, a2, ..., an (1 ≤ ai ≤ 2, i = 1, 2, ..., n).

Print a single integer, which means the maximum possible length of the longest non-decreasing subsequence of the new sequence.

NoteIn the first example, after reversing [2, 3], the array will become [1, 1, 2, 2], where the length of the longest non-decreasing subsequence is 4.In the second example, after reversing [3, 7], the array will become [1, 1, 1, 1, 2, 2, 2, 2, 2, 1], where the length of the longest non-decreasing subsequence is 9.

open Scanf

let read_array n =
  let f i = scanf " %u" (fun i -> i) in
  Array.init n f

let count_array f a =
  Array.fold_left (fun i v -> if f v then i + 1 else i) 0 a

let update_ref (ref1, ref2) = function
  | 1 -> ref1 := !ref1 + 1
  | 2 -> ref2 := !ref2 + 1
  | _ -> ()

(*
  ret = max(n1_0a + n2_bn + n2_ak + n1_kb)
      => n1_0a + (n2 - n2_0b) + n2_0k - n2_0a + n1_0b - n1_0k
      => n1_0a + n2_bn - n2_0a + n1_0b + **(n2_0k - n1_0k)**
*)
let () =
  let n = scanf " %u " (fun i -> i) in
  let a = read_array n in

  let ret = ref 0 in
  let n2 = count_array (fun x -> x = 2) a in
  let n1_0a = ref 0 in
  let n2_0a = ref 0 in
  for ia = 0 to n do begin
    if ia > 0 then begin update_ref (n1_0a, n2_0a) a.(ia - 1) end;
    let max_diff = ref min_int in
    let n1_0b = ref !n1_0a in
    let n2_0b = ref !n2_0a in
    for ib = ia to n do
      if ib > ia then begin update_ref (n1_0b, n2_0b) a.(ib - 1) end;
      (* the diff. we are maximizing is effectively (n2_0k - n1_0k) *)
      max_diff := max !max_diff (!n2_0b - !n1_0b);
      let n2_bn = n2 - !n2_0b in
      ret := max !ret
        (!n1_0a + n2_bn + !n1_0b - !n2_0a + !max_diff)
    done
  end
  done;
  !ret |> string_of_int |> print_endline

open Scanf

let () = Printexc.record_backtrace true

let read_array n =
  let f i = scanf " %u" (fun i -> i) in
  Array.init n f

let count_array f a =
  Array.fold_left (fun i v -> if f v then i + 1 else i) 0 a

let () =
  let n = scanf " %u " (fun i -> i) in
  let a = read_array n in
  let ret = ref 0 in
  let n1 = count_array (fun x -> x = 1) a in
  let n2 = count_array (fun x -> x = 2) a in
  let n1_0a = ref 0 in
  let n2_0a = ref 0 in
  for ia = 0 to n do begin
    if ia > 0 then begin
      match a.(ia - 1) with
      | 1 -> n1_0a := !n1_0a + 1
      | 2 -> n2_0a := !n2_0a + 1
      | _ -> ()
    end;
    let max_diff = ref min_int in
    let n1_0b = ref !n1_0a in
    let n2_0b = ref !n2_0a in
    for ib = ia to n do
      if ib > ia then begin
        match a.(ib - 1) with
        | 1 -> n1_0b := !n1_0b + 1
        | 2 -> n2_0b := !n2_0b + 1
        | _ -> ()
      end;
      max_diff := max !max_diff (!n2_0b - !n1_0b);
      let n2_bn = n2 - !n2_0b in
      ret := max !ret
        (!n1_0a + n2_bn + !n1_0b - !n2_0a + !max_diff)
    done
  end
  done;
  !ret |> string_of_int |> print_endline


Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the point where at least two different roads intersect.Your home is located in one of the blocks. Today you need to get to the University, also located in some block. In one step you can move from one block to another, if the length of their common border is nonzero (in particular, this means that if the blocks are adjacent to one intersection, but have no shared nonzero boundary segment, then it are not allowed to move from one to another one in one step).Determine what is the minimum number of steps you have to perform to get to the block containing the university. It is guaranteed that neither your home nor the university is located on the road.

The first line contains two space-separated integers x1, y1 ( - 106 ≤ x1, y1 ≤ 106) — the coordinates of your home. The second line contains two integers separated by a space x2, y2 ( - 106 ≤ x2, y2 ≤ 106) — the coordinates of the university you are studying at. The third line contains an integer n (1 ≤ n ≤ 300) — the number of roads in the city. The following n lines contain 3 space-separated integers ( - 106 ≤ ai, bi, ci ≤ 106; |ai| + |bi| > 0) — the coefficients of the line aix + biy + ci = 0, defining the i-th road. It is guaranteed that no two roads are the same. In addition, neither your home nor the university lie on the road (i.e. they do not belong to any one of the lines).

NotePictures to the samples are presented below (A is the point representing the house; B is the point representing the university, different blocks are filled with different colors):

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0

let () =
  let x1 = float (read_int ()) in
  let y1 = float (read_int ()) in
  let x2 = float (read_int ()) in
  let y2 = float (read_int ()) in
  let n = read_int () in
  let line = Array.init n (fun _ ->
    let a = float (read_int()) in
    let b = float (read_int()) in
    let c = float (read_int()) in
    (a,b,c)
  ) in

  let side (x,y) i =
    let (a,b,c) = line.(i) in
    let v = a*.x +. b*.y +. c in
    if v>0.0 then 1 else if v<0.0 then -1 else failwith "on a line"
  in

  let diff_side_count =
    sum 0 (n-1) (fun i -> if (side (x1,y1) i) = (side (x2,y2) i) then 0 else 1)
  in

  printf "%d\n" diff_side_count


You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves:   decrease $$$n$$$ by $$$1$$$;  divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The only line of each query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$2 \le k \le 10^{18}$$$).

For each query print the minimum number of steps to reach $$$0$$$ from $$$n$$$ in single line.

NoteSteps for the first test case are: $$$59 \rightarrow 58 \rightarrow 57 \rightarrow 19 \rightarrow 18 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.In the second test case you have to divide $$$n$$$ by $$$k$$$ $$$18$$$ times and then decrease $$$n$$$ by $$$1$$$.

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

let () =
  let t = Scanf.scanf "%d\n" (fun x -> x) in
  for i = 1 to t do
    let n, k = Scanf.scanf "%Ld %Ld\n" (fun x y -> x, y) in
    let n = ref n in
    let res = ref Int64.zero in
    while !n >= k do
      let x = !n - ((!n / k) * k) in
      if x = Int64.zero then begin n:=!n/k; res := !res + 1L end else
        begin n := !n - x;
          res := !res + x;
        end;
    done;
    res := !res + !n;
    Printf.printf "%Ld\n" !res
  done
;;


Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of polygons in the market.  Each of the next $$$t$$$ lines contains a single integer $$$n_i$$$ ($$$3 \le n_i \le 10^9$$$): it means that the $$$i$$$-th polygon is a regular $$$n_i$$$-sided polygon.

For each polygon, print YES if it's beautiful or NO otherwise (case insensitive).

NoteIn the example, there are $$$4$$$ polygons in the market. It's easy to see that an equilateral triangle (a regular $$$3$$$-sided polygon) is not beautiful, a square (a regular $$$4$$$-sided polygon) is beautiful and a regular $$$12$$$-sided polygon (is shown below) is beautiful as well.

let t = read_int();;
for i=0 to t-1 do
	let n = read_int() in
	if n mod 4 = 0 then begin
		print_endline "Yes";
	end else begin
		print_endline "No";
	end
done;;

let t = read_int();;
for i=0 to t-1 do
	let n = read_int() in
	if n mod 2 = 0 then begin
		print_endline "Yes";
	end else begin
		print_endline "No";
	end
done;;


You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.

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

Print the maximum length of an increasing subarray of the given array.

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

;;

let rec solve lst cnt ans prev =
    match lst with
    | [] -> max cnt ans
    | hd :: tl -> if hd > prev then
                    solve tl (cnt+1) (max cnt ans) hd
                  else
                    solve tl 1  (max cnt ans) hd
;;

let  main () =
    let _ = read_int () in
    let l = read_nums () in
    let n = solve l 1 1 1000000007 in
    let () = print_int n in
    print_string "\n"

;;

main ()

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

open Printf
open Scanf

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

let () =
        let n = read_int() in
        let a = Array.make n 0 in
        for i = 0 to n - 1 do
                a.(i) <- read_int()
        done;
        let res = ref 1 in
        let cur = ref 1 in
        for i = 1 to n - 1 do
                if a.(i) > a.(i - 1) then
                        cur := !cur + 1
                else
                        cur := 1;
                if res < cur then
                        res := !cur
        done;
        printf "%d\n" !res

open Scanf
open Printf

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

let a = Array.make (n+1) 0

let b = Array.make (n+1) 0

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

let cnt = ref 0

for i = 1 to n do
  begin
  if a.(i) > a.(i-1) then
    cnt := !cnt + 1
  else
    cnt := 1
  end; b.(i) <- !cnt
done

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

let ff = Array.make (n+1) (-10)
let rec f m =
  if m = 1 then
    1
  else
    if ff.(m-1) < 0 then
      begin
      ff.(m-1) <- f (m-1);
      max ff.(m-1) b.(m)
      end
  else
    max ff.(m-1) b.(m)

let rslt = f n in
printf "%d\n" rslt

open Printf
let input_int_array n =
	Array.init n (fun _ -> Scanf.scanf " %d" (fun v -> v))

let get_int () = Scanf.scanf " %d" (fun v -> v)
let get_2_ints () = Scanf.scanf " %d %d" (fun u v -> u,v)
let get_3_ints () = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w)
let get_4_ints () = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x)
let get_5_ints () = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)

let print_int_endline n = n |> string_of_int |> print_endline

let () =
  let n = get_int ()
  in let a = input_int_array n
  in let v,len,lenmax = ref a.(0),ref 1,ref 1
  in
  for i=1 to (n-1) do
    if !v < a.(i) then (
      len := !len+1;
      if !len > !lenmax then lenmax := !len;
    ) else (
      len := 1;
    );
    v := a.(i)
  done;
  !lenmax |> print_int_endline

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let res = ref 1 in
  let p = ref a.(0) in
  let len = ref 1 in
    for i = 1 to n - 1 do
      if a.(i) > !p then (
	p := a.(i);
	incr len;
	res := max !res !len;
      ) else (
	p := a.(i);
	len := 1;
      )
    done;
    Printf.printf "%d\n" !res

let n = int_of_string (input_line stdin) ;;

let rec solve last acc best count =
    if count == 0 then max best acc
    else let num = Scanf.scanf "%d " (fun a -> a) in
        if num > last then solve num (acc + 1) best (count - 1)
        else solve num 1 (max best acc) (count - 1) ;;

let ans = solve 0 0 0 n in
    Printf.printf "%d\n" ans ;;

let n = int_of_string (input_line stdin) ;;

let rec solve last acc best count =
    Printf.printf "solve %d %d %d %d\n" last acc best count ;
    if count == 0 then max best acc
    else let num = Scanf.scanf "%d " (fun a -> a) in
        if num > last then solve num (acc + 1) best (count - 1)
        else solve num 1 (max best acc) (count - 1) ;;

let ans = solve 0 0 0 n in
    Printf.printf "%d\n" ans ;;