You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.

The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i < b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.

Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).

NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.

let rec sum acc base digits = match digits with
| [] -> acc
| first :: digits -> sum (acc + first * base) base digits in

let is_even base digits = match digits with
| [] -> false
| first :: digits -> ((sum first base digits) mod 2 == 0) in

let main b a = if is_even b a then "even" else "odd" in

let rec read (acc: int list) k = if k == 0
  then acc
  else read ((Scanf.scanf " %s" (fun a -> (int_of_string (String.trim a)))) :: acc) (k - 1) in

Scanf.scanf "%s %s\n" (fun b k ->
  print_string(main (int_of_string (String.trim b)) (read [] (int_of_string (String.trim k))))
)


There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times:  Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$

For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.

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

let rec update ind2 tab2 loserb len =

  if tab2.(!ind2 -1) = tab2.(!ind2) && Hashtbl.mem loserb (tab2.(!ind2)) then begin
    let num = Hashtbl.find loserb (tab2.(!ind2)) in
    if num = 1 then Hashtbl.remove loserb (tab2.(!ind2))
    else Hashtbl.replace loserb (tab2.(!ind2)) (num-1) ;
    incr ind2 ;
    if !ind2 < len then
      update ind2 tab2 loserb len
    ;
  end
;;

let n = int_of_string (input_line stdin) in
for j = 0 to n-1 do
  let len = int_of_string (input_line stdin) in
  let str1 = (input_line stdin) in
  let str2 = (input_line stdin) in
  let tab1 = parse len str1 in
  let tab2 = parse len str2 in
  let ind2 = ref 0 in
  let loserb = Hashtbl.create(len) in
  for i = 0 to len -1 do
    if tab1.(i) = tab2.(!ind2) then begin
      incr ind2;
      if !ind2 < len then
        update ind2 tab2 loserb len
      ;
    end
    else begin
      if Hashtbl.mem loserb (tab1.(i)) then
        (let num = Hashtbl.find loserb (tab1.(i)) in Hashtbl.replace loserb (tab1.(i)) (num+1))
      else Hashtbl.add loserb (tab1.(i)) 1
    end;

  done;
if !ind2 = len then print_endline "YES" else print_endline "NO"
done;;


The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.

The first line contains a single integer n (2 ≤ n ≤ 105) — the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, — array a. Note that the elements of the array are not necessarily distinct numbers.

In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise.

NoteIn the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES".In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES".In the third sample we can't sort the array in more than one swap operation, so the answer is "NO".

let swap ary i j =
  let temp = ary.(i) in
  ary.(i) <- ary.(j);
  ary.(j) <- temp

let input_array size ary =
  let rec input_array n =
    if n == size then ary
    else begin
      ary.(n) <- Scanf.scanf " %d" (fun x -> x);
      input_array (n + 1);
    end
  in
  input_array 0

let solve n =
  let a = input_array n (Array.make n 0) in
  let a_ = Array.copy a in
  let sorted_a =
    begin
      Array.stable_sort (fun a b -> if a <= b then -1 else 1) a;
      a;
    end
  in
  let rec solve x cnt =
    if cnt >= 3 then "NO"
    else if n == x then "YES"
    else if a_.(x) != sorted_a.(x) then solve (x + 1) (cnt + 1)
    else solve (x + 1) cnt
  in
  solve 0 0

let _ =
  Printf.printf "%s\n" (Scanf.scanf " %d" solve)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec mins i v=if i=0 then 0 else if tab.(i-1)=v then mins (i-1) v else i;;
let rec maxs i v=if i=n-1 then n-1 else if tab.(i+1)=v then maxs (i+1) v else i;;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then mins i tab.(i) else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then maxs i tab.(i) else last (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;
(*10 1 2 9 4 5 6 7 8 3 10*)

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 b = Array.copy a in
  let cmp (x : int) y =
    if x < y
    then -1
    else if x = y
    then 0
    else 1
  in
    Array.sort cmp b;
    let c = ref 0 in
      for i = 0 to n - 1 do
	if a.(i) <> b.(i)
	then incr c;
      done;
      if !c >= 3
      then Printf.printf "NO\n"
      else Printf.printf "YES\n"

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec mins i v=if i=0 then 0 else if tab.(i-1)=v then mins (i-1) v else i;;
let rec maxs i v=if i=n-1 then n-1 else if tab.(i+1)=v then mins (i+1) v else i;;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then mins i tab.(i) else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then maxs i tab.(i) else last (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;
(*10 1 2 9 4 5 6 7 8 3 10*)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then i else last (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;
(*10 1 2 9 4 5 6 7 8 3 10*)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then i else prem (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then i else prem (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-tab.(i);;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;


Pig is visiting a friend.Pig's house is located at point 0, and his friend's house is located at point m on an axis.Pig can use teleports to move along the axis.To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds.  Determine if Pig can visit the friend using teleports only, or he should use his car.

The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of teleports and the location of the friend's house. The next n lines contain information about teleports. The i-th of these lines contains two integers ai and bi (0 ≤ ai ≤ bi ≤ m), where ai is the location of the i-th teleport, and bi is its limit. It is guaranteed that ai ≥ ai - 1 for every i (2 ≤ i ≤ n).

Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower).

NoteThe first example is shown on the picture below:  Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.The second example is shown on the picture below:  You can see that there is no path from Pig's house to his friend's house that uses only teleports.

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

let n = read_int ();;
let m = read_int ();;
let i = (ref 0);;
let tab = (ref [(0,0)]);;
while ((!i) < (n)) do
  let a = read_int ()
  in
  let b = read_int ()
  in
  tab := [(a, b)]@(!tab);
  i := (!i + 1)
done
let tab = (rev (!tab));;
if ((fst (List.hd tab)) <> 0) then
  begin
  print_string "NO";
  print_endline
  end
else
  begin
    let f a (x, y) =
      if (a>=x) then (max a y)
      else a
    in
    let zas =
      List.fold_left f 0 tab
    in
    if zas>=m then
      begin
      print_string "YES";
      print_endline
      end
    else
    begin
      print_string "NO";
      print_endline
    end
  end
;;

open Printf
open Scanf

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

  let rec loop i reach =
    if reach >= m then true
    else if i = n then false
    else
      let (a,b) = tele.(i) in
      if a > reach then false
      else loop (i+1) (max reach b)
  in

  if loop 0 0 then printf "YES\n" else printf "NO\n"

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

let n = read_int ();;
let m = read_int ();;
let i = (ref 0);;
let tab = (ref [(0,0)]);;
while ((!i) < (n)) do
  let a = read_int ()
  in
  let b = read_int ()
  in
  tab := [(a, b)]@(!tab);
  i := (!i + 1)
done
let tab = (rev (!tab));;
if ((fst (List.hd tab)) <> 0) then
  begin
  print_string "NO";
  print_endline
  end
else
  begin
    let f a (x, y) =
      if (a>=x) then (max a (x+y))
      else a
    in
    let zas =
      List.fold_left f 0 tab
    in
    if zas>=m then
      begin
      print_string "YES";
      print_endline
      end
    else
    begin
      print_string "NO";
      print_endline
    end
  end
;;


Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!

The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.

If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.

let f mot =
	let flag = ref true and last = mot.[String.length mot - 1] in
	for i=0 to String.length mot - 1 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0) && (mot.[i] < last)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
	done;
	if !flag
		then for i=String.length mot - 1 downto 0 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
		done;
	!flag;;

let test n =
	let mot = string_of_int n in
		if f mot
			then -1
			else int_of_string mot;;

let final () =
	let m = Scanf.scanf "%s " (fun i -> i) in
		if f m
			then Printf.printf "-1"
			else Printf.printf "%s " m;;

final ();;

let int_of_char c = int_of_char c - int_of_char '0'
and char_of_int i = char_of_int (i + int_of_char '0')

let () =
  let n = read_line () in
  let last = int_of_char (n.[String.length n - 1]) in
  let best = ref (-1) in
  let even = ref (-1) in

  for i = 0 to String.length n - 1 do
    let c = int_of_char n.[i] in
    if c mod 2 = 0 then begin
      even := i;
      if !best = (-1) && c < last then
        best := i
    end
  done;

  if !best <> (-1) then even := !best;
  if !even <> (-1)
  then begin
    n.[String.length n - 1] <- n.[!even];
    n.[!even] <- char_of_int last;
    print_endline n
  end
  else
    print_endline "-1"

let f mot =
	let flag = ref true and last = mot.[String.length mot - 1] in
	for i=0 to String.length mot - 1 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0) && (mot.[i] > last)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
	done;
	if !flag
		then for i=String.length mot - 1 downto 0 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
		done;
	!flag;;

let final () =
	let m = Scanf.scanf "%s " (fun i -> i) in
		if f m
			then Printf.printf "-1"
			else Printf.printf "%s " m;;

final ();;


The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100) — the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1, a2, ..., an (16 ≤ ai ≤ 32768); number ai denotes the maximum data transfer speed on the i-th computer.

Print a single integer — the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.

NoteIn the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal.

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

let n=read_int() and k=read_int();;

let l=ref [];;
for i=1 to n do
   l:=(read_int())::(!l)
done;;

let rec inserer v=function
|[]->[v]
|h::t->if v>=h then v::h::t else h::(inserer v t);;

let rec tri=function
|[]->[]
|h::t->inserer h (tri t);;

let sol=tri(!l);;

let rec neme i=function
|[]->0
|h::t->if i=1 then h else neme (i-1) t;;

print_int(neme k sol);;

open Scanf
open Printf

let flip f a b = f b a in

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

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

let read_list n =
    let f l _ = ((read_int ()) :: l) in
    List.fold_left f [] (range 1 n) in

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

let (|>) a f = f a in

l |> (List.sort compare) |> List.rev |> (flip List.nth (k - 1)) |> (printf "%d\n");;

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 n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a
  in
    Printf.printf "%d\n" a.(n - k);


You are a coach of a group consisting of $$$n$$$ students. The $$$i$$$-th student has programming skill $$$a_i$$$. All students have distinct programming skills. You want to divide them into teams in such a way that:  No two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $$$1$$$);  the number of teams is the minimum possible. You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of students in the query. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$, all $$$a_i$$$ are distinct), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student.

For each query, print the answer on it — the minimum number of teams you can form if no two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $$$1$$$)

NoteIn the first query of the example, there are $$$n=4$$$ students with the skills $$$a=[2, 10, 1, 20]$$$. There is only one restriction here: the $$$1$$$-st and the $$$3$$$-th students can't be in the same team (because of $$$|a_1 - a_3|=|2-1|=1$$$). It is possible to divide them into $$$2$$$ teams: for example, students $$$1$$$, $$$2$$$ and $$$4$$$ are in the first team and the student $$$3$$$ in the second team.In the second query of the example, there are $$$n=2$$$ students with the skills $$$a=[3, 6]$$$. It is possible to compose just a single team containing both students.

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

let solve n =
	let t = Array.make n 0 in
	for i = 0 to (n - 1) do
		let a = read_int () in
		t.(i) <- a
	done;
	Array.sort compare t;
	let result = ref 1 in
		for i = 1 to (n - 1) do
			if t.(i) - t.(i - 1) = 1
				then result := 2
		done;
	!result

let () =
	let q = read_int () in
	for tests = 1 to q do
		let n = read_int () in
		printf "%d\n" (solve n)
	done;

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

let solve n =
	let t = Array.make (n + 1) 0 in
	for i = 0 to (n - 1) do
		let a = read_int () in
		t.(i) <- a
	done;
	Array.sort compare t;
	let result = ref 1 in
		for i = 1 to n - 1 do
			if t.(i) - t.(i - 1) = 1
				then result := 2
		done;
	!result
let () =
	let q = read_int () in
	for tests = 1 to q do
		let n = read_int () in
		printf "%d\n" (solve n)
	done;


The only difference between the two versions is that this version asks the maximal possible answer.Homer likes arrays a lot. Today he is painting an array $$$a_1, a_2, \dots, a_n$$$ with two kinds of colors, white and black. A painting assignment for $$$a_1, a_2, \dots, a_n$$$ is described by an array $$$b_1, b_2, \dots, b_n$$$ that $$$b_i$$$ indicates the color of $$$a_i$$$ ($$$0$$$ for white and $$$1$$$ for black).According to a painting assignment $$$b_1, b_2, \dots, b_n$$$, the array $$$a$$$ is split into two new arrays $$$a^{(0)}$$$ and $$$a^{(1)}$$$, where $$$a^{(0)}$$$ is the sub-sequence of all white elements in $$$a$$$ and $$$a^{(1)}$$$ is the sub-sequence of all black elements in $$$a$$$. For example, if $$$a = [1,2,3,4,5,6]$$$ and $$$b = [0,1,0,1,0,0]$$$, then $$$a^{(0)} = [1,3,5,6]$$$ and $$$a^{(1)} = [2,4]$$$.The number of segments in an array $$$c_1, c_2, \dots, c_k$$$, denoted $$$\mathit{seg}(c)$$$, is the number of elements if we merge all adjacent elements with the same value in $$$c$$$. For example, the number of segments in $$$[1,1,2,2,3,3,3,2]$$$ is $$$4$$$, because the array will become $$$[1,2,3,2]$$$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $$$0$$$.Homer wants to find a painting assignment $$$b$$$, according to which the number of segments in both $$$a^{(0)}$$$ and $$$a^{(1)}$$$, i.e. $$$\mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)})$$$, is as large as possible. Find this number.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$).

Output a single integer, indicating the maximal possible total number of segments.

(* When there's more than one in the block, WLOG they go to opposite streams.
   So all we have to do is decide what happens between big blocks.

   Case1: The two big blocks differ.  In this case we just
   leave the stuff between the blocks in one of the streams.

   Case2: The two big blocks are the same, say x.
   The only question becomes if it's possible to move one from the
   stream that is not x that is not between two identical ones.
*)

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

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

let () =
  let n = read_int() in
  let a = Array.init n read_int in

  let compressed = fold 0 (n-1) (
    fun i ac ->
      if i=0 || a.(i-1) <> a.(i) then ( (* first of a block *)
	let more_than_1 = i<n-1 && a.(i) = a.(i+1) in (*a block of more than 1 *)
	(a.(i),more_than_1)::ac
      ) else ac
  ) [] in

  let c = Array.of_list (List.rev compressed) in
  let n = Array.length c in
  let get i = if i<0 then (-1,true) else if i>=n then (-2,true) else c.(i) in

  let p = ref (-1) in
  let count = ref 0 in

  for j=0 to n do
    let i = !p in
    let (xi,_) = get i in
    let (xj,doub) = get j in
    let delta = if j=n then 0 else 1 in
    if doub then (
(*      printf "count = %d  doub %d\n" !count xj; *)
      p := j;
      count := !count + 2*delta + j-i-1;
      if xi = xj then (
	if i+1 = j then failwith "should not happen i+1=j";
	if exists (i+1) (j-1) (fun k ->
	  let (a,_) = get (k-1) in
	  let (b,_) = get k in
	  let (c,_) = get (k+1) in
	  a <> c && b <> xi
	) then () else (
	  count := !count - 1
	)
      )
    )
  done;

  printf "%d\n" !count

(* When there's more than one in the block, WLOG they go to opposite streams.
   So all we have to do is decide what happens between big blocks.

   Case1: The two big blocks differ.  In this case we just
   leave the stuff between the blocks in one of the streams.

   Case2: The two big blocks are the same, say x.
   The only question becomes if it's possible to move one from the
   stream that is not x that is not between two identical ones.
*)

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

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

let () =
  let n = read_int() in
  let a = Array.init n read_int in

  let compressed = fold 0 (n-1) (
    fun i ac ->
      if i=0 || a.(i-1) <> a.(i) then ( (* first of a block *)
	let more_than_1 = i<n-1 && a.(i) = a.(i+1) in (*a block of more than 1 *)
	(a.(i),more_than_1)::ac
      ) else ac
  ) [] in

  let c = Array.of_list (List.rev compressed) in
  let n = Array.length c in
  let get i = if i<0 then (-1,true) else if i>=n then (-2,true) else c.(i) in

  let p = ref (-1) in
  let count = ref 0 in

  for j=0 to n do
    let i = !p in
    let (xi,_) = get i in
    let (xj,doub) = get j in
    let delta = if j=n then 0 else 1 in
    if doub then (
      printf "count = %d  doub %d\n" !count xj;
      p := j;
      count := !count + 2*delta + j-i-1;
      if xi = xj then (
	if i+1 = j then failwith "should not happen i+1=j";
	if exists (i+1) (j-1) (fun k ->
	  let (a,_) = get (k-1) in
	  let (b,_) = get k in
	  let (c,_) = get (k+1) in
	  a <> c && b <> xi
	) then () else (
	  count := !count - 1
	)
      )
    )
  done;

  printf "%d\n" !count

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

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

let () =
  let n = read_int() in
  let a = Array.init n read_int in

  let compressed = fold 0 (n-1) (
    fun i ac ->
      if i=0 || a.(i-1) <> a.(i) then ( (* first of a block *)
	let more_than_1 = i<n-1 && a.(i) = a.(i+1) in (*a block of more than 1 *)
	(a.(i),more_than_1)::ac
      ) else ac
  ) [] in

  let delta x y = if x=y then 0 else 1 in

  let rec scan comp l1 l2 split1 split2 ac =
    (* l1 = last one in row 1.  split1 = boolean if row 1 was part
       of a split.  l2, split2 analogous.  *)

    match comp with
      | [] -> ac
      | (x,true)::t ->
	scan t x x true true (ac + (delta l1 x) + (delta l2 x))
      | (x,false)::t ->
	if x = l1 then scan t l1 x split1 false (ac + (delta l2 x))
	else if x = l2 then scan t x l2 false split2 (ac + (delta l1 x))
	else if split1 then scan t x l2 false split2 (ac + (delta l1 x))
	else scan t l1 x split1 false (ac + (delta l2 x))
  in

  let answer = scan compressed (-1) (-1) false false 0 in

  printf "%d\n" answer

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

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

let () =
  let n = read_int() in
  let a = Array.init n read_int in

(*  if n=1 then printf "1\n" *)

  let (comp_a,b) = fold 0 (n-1) (
    fun i (ac1,ac2) ->
      let ac1 = if i=0 || a.(i-1) <> a.(i) then a.(i)::ac1 else ac1 in
      let ac2 = if not (i=0 || a.(i-1) <> a.(i)) then a.(i)::ac2 else ac2 in
      (ac1,ac2)
  ) ([],[]) in

  let b = Array.of_list b in
  let nb = Array.length b in

  let comp_b = fold 0 (nb-1) (
    fun i ac ->
      if i=0 || b.(i-1) <> b.(i) then b.(i)::ac else ac
  ) [] in

  printf "%d\n" ((List.length comp_a) + (List.length comp_b))


Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:  The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:   given a row index i, flip all the values in the i-th row in A;  given a column index i, flip all the values in the i-th column in A;  find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?

The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:    1 i — flip the values of the i-th row;  2 i — flip the values of the i-th column;  3 — output the unusual square of A.  Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.

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

let n=read_int();;

let l=ref 0;;

for i=0 to n-1 do
   for j=0 to n-1 do
      let a=read_int() in if i=j then l:= !l+a
   done
done;;

let m=read_int();;

l:= ( !l mod 2);;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else p:=(!l):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

print_list !p;;

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

let n=read_int();;

let l=ref 0;;

let a=ref 0;;

for i=0 to n-1 do
   for j=0 to i do
      a:=read_int()
   done;
   for j=i+1 to n-1 do
      let b=read_int() in ()
   done;
   l:= !l+ !a;
done;;

let m=read_int();;

l:= (!l mod 2);;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else print_int !l
done;;

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

let n=read_int();;

let l=ref 0;;

let s=ref " ";;

let a=ref 0;;

for i=0 to n-1 do
   for j=0 to i do
      a:=read_int()
   done;
   for j=i+1 to n-1 do
      let b=read_int() in ()
   done;
   l:= !l+ !a;
done;;

let m=read_int();;

l:= (!l mod 2);;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else p:=(!l):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

print_list !p;;

let read_int()=Scanf.scanf " %d" (fun x->x);;
let split_spaces chaine =
  let res = ref [] in
  let temp = ref "" in
  for i = 0 to String.length chaine - 1 do
    if chaine.[i]=' '
    then
      begin
        res := !res @ [!temp];
        temp := "";
      end
    else
      temp := !temp ^ (String.sub chaine i 1);
  done;
  res := !res @ [!temp];
  !res;;
let n = int_of_string (input_line stdin);;
let mat = Array.init n (fun _ -> Array.map int_of_string (Array.of_list (split_spaces (input_line stdin))));;
let m=read_int();;

let aj tab=
let l=ref 0 in
   for i=0 to n-1 do
      l:= !l+tab.(i).(i)
   done;
!l mod 2;;

let chg a=mat.(a-1).(a-1)<-1-mat.(a-1).(a-1);;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in mat.(a-1).(a-1)<-1-mat.(a-1).(a-1) else p:=(aj mat):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

let read_int()=Scanf.scanf " %d" (fun x->x);;
let split_spaces chaine =
  let res = ref [] in
  let temp = ref "" in
  for i = 0 to String.length chaine - 1 do
    if chaine.[i]=' '
    then
      begin
        res := !res @ [!temp];
        temp := "";
      end
    else
      temp := !temp ^ (String.sub chaine i 1);
  done;
  res := !res @ [!temp];
  !res;;
let n = int_of_string (input_line stdin);;
let mat = Array.init n (fun _ -> Array.map int_of_string (Array.of_list (split_spaces (input_line stdin))));;
let m=read_int();;

let l=ref 0;;
for i=0 to n-1 do
   l:= !l+mat.(i).(i)
done;;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else p:=(!l):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

print_list !p;;


Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree. Also, each edge has its own cost.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).Each edge $$$i$$$ has an associated cost $$$c_i$$$ which is either $$$1$$$ or $$$2$$$ coins. Each move with edge $$$i$$$ costs $$$c_i$$$ coins.Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as four integers $$$v_i$$$, $$$u_i$$$, $$$w_i$$$ and $$$c_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6; 1 \le c_i \le 2$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects, $$$w_i$$$ is the weight of this edge and $$$c_i$$$ is the cost of this edge. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\sum n \le 10^5$$$).

For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most $$$S$$$.

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let arr_1 = Array.of_list !list_1 in
    let arr_2 = Array.of_list !list_2 in
    Array.fast_sort compare arr_1;
    Array.fast_sort compare arr_2;
    let id_1 = ref (Array.length arr_1 - 1) in
    let id_2 = ref (Array.length arr_2 - 1) in

    while !sum > s do
      if -1 = !id_1 then (
        sum := Int64.sub !sum arr_2.(!id_2);
        id_2 := !id_2 - 1;
        answer := !answer + 1
      ) else if -1= !id_2 then (
        sum := Int64.sub !sum arr_1.(!id_1);
        id_1 := !id_1 - 1
      ) else (
        if arr_1.(!id_1) >= arr_2.(!id_2) || !sum <= (Int64.add s arr_1.(!id_1)) then (
          sum := Int64.sub !sum arr_1.(!id_1);
          id_1 := !id_1 - 1
        ) else (
          if 0 != !id_1 then (
            if (Int64.add arr_1.(!id_1) arr_1.(!id_1 - 1)) >= arr_2.(!id_2) then (
              sum := Int64.sub !sum arr_1.(!id_1);
              id_1 := !id_1 - 1
            ) else (
              sum := Int64.sub !sum arr_2.(!id_2);
              id_2 := !id_2 - 1;
              answer := !answer + 1
            )
          )
          else (
            sum := Int64.sub !sum arr_2.(!id_2);
            id_2 := !id_2 - 1;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer

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

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let edges = Array.make n (0L, 0) in
    let set_1 = ref (SS.empty) in
    let set_2 = ref (SS.empty) in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;
          edges.(new_vert) <- (cost, add);

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let mult = Int64.mul (div2 cost) (Int64.of_int add) in

          if t = 1 then set_1 := SS.add (mult, new_vert) !set_1
          else set_2 := SS.add (mult, new_vert) !set_2
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let real_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      edges.(del_id) <- (cost_edge, cnt_edge);
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      sum := Int64.add !sum (Int64.neg del_value);
      new_set
    in

    let fake_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      new_set
    in

    if SS.cardinal !set_2 = 0 then (
      while !sum > s do
         set_1 := real_del_element !set_1;
         answer := !answer + 1
      done
    )
    else if SS.cardinal !set_1 = 0 then (
      while !sum > s do
        set_2 := real_del_element !set_2;
        answer := !answer + 2
      done
    )
    else (
      while !sum > s do
        let (cost_1, id_1) = SS.max_elt !set_1 in
        let (cost_2, id_2) = SS.max_elt !set_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          set_1 := real_del_element !set_1
        )
        else (
          let new_set_1 = fake_del_element !set_1 in
          let (cost_3, id_3) = SS.max_elt new_set_1 in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            set_1 := real_del_element !set_1;
          ) else (
            set_2 := real_del_element !set_2;
            answer := !answer + 1
          )
        );

        answer := !answer + 1
      done;
    );

    printf "%d\n" !answer
;;

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

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    if Sys.time() -. t > 2.9 then (
      sum := 0L
    );

    while !sum > s do
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

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

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let edges = Array.make n (0L, 0) in
    let set_1 = ref (SS.empty) in
    let set_2 = ref (SS.empty) in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;
          edges.(new_vert) <- (cost, add);

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let mult = Int64.mul (div2 cost) (Int64.of_int add) in

          if t = 1 then set_1 := SS.add (mult, new_vert) !set_1
          else set_2 := SS.add (mult, new_vert) !set_2
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let real_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      edges.(del_id) <- (cost_edge, cnt_edge);
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      sum := Int64.add !sum (Int64.neg del_value);
      new_set
    in

    let fake_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      new_set
    in

    if SS.cardinal !set_2 = 0 then (
      while !sum > s do
         set_1 := real_del_element !set_1;
         answer := !answer + 1
      done
    )
    else if SS.cardinal !set_1 = 0 then (
      set_2 := real_del_element !set_2;
      answer := !answer + 2
    )
    else (
      while !sum > s do
        let (cost_1, id_1) = SS.max_elt !set_1 in
        let (cost_2, id_2) = SS.max_elt !set_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          set_1 := real_del_element !set_1
        )
        else (
          let new_set_1 = fake_del_element !set_1 in
          let (cost_3, id_3) = SS.max_elt new_set_1 in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            set_1 := real_del_element !set_1;
          ) else (
            set_2 := real_del_element !set_2;
            answer := !answer + 1
          )
        );

        answer := !answer + 1
      done;
    );

    printf "%d\n" !answer
;;

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

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    while !sum > s do
      if Sys.time() -. t > 2.5 then (
        sum := 0L
      )
      else (
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

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

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let arr_1 = Array.of_list !list_1 in
    let arr_2 = Array.of_list !list_2 in
    Array.sort compare arr_1;
    Array.sort compare arr_2;
    let id_1 = ref 0 in
    let id_2 = ref 0 in

    while !sum > s do
      if Array.length arr_1 = !id_1 then (
        sum := Int64.sub !sum arr_2.(!id_2);
        id_2 := !id_2 + 1;
        answer := !answer + 1
      ) else if Array.length arr_2 = !id_2 then (
        sum := Int64.sub !sum arr_1.(!id_1);
        id_1 := !id_1 + 1
      ) else (
        if arr_1.(!id_1) >= arr_2.(!id_2) || !sum <= (Int64.add s arr_1.(!id_1)) then (
          sum := Int64.sub !sum arr_1.(!id_1);
          id_1 := !id_1 + 1
        ) else (
          if Array.length arr_1 != !id_1 + 1 then (
            if (Int64.add arr_1.(!id_1) arr_1.(!id_1 + 1)) >= arr_2.(!id_2) then (
              sum := Int64.sub !sum arr_1.(!id_1);
              id_1 := !id_1 + 1
            ) else (
              sum := Int64.sub !sum arr_2.(!id_2);
              id_2 := !id_2 + 1;
              answer := !answer + 1
            )
          )
          else (
            sum := Int64.sub !sum arr_2.(!id_2);
            id_2 := !id_2 + 1;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

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

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    if Sys.time() -. t > 2.95 then (
      sum := 0L
    );

    while !sum > s do
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

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

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    while !sum > s do
      if Sys.time() -. t > 2.9 then (
        sum := 0L
      )
      else (
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

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


The mobile application store has a new game called "Subway Roller".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.

Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets. Then follows the description of t sets of the input data.  The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.

For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.

NoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset.

let () = Scanf.scanf "%d\n" (fun t ->
    for test = 1 to t do
        (* number of columns and number of trains *)
        Scanf.scanf "%d %d\n" (fun n _ ->
            (* DP board, 3 rows by n columns, initially false
             * board.(i).(j) = true if it's possible to survive from that position *)
            let board = Array.make_matrix 3 n false
            and trains = Array.make_matrix 3 n false in
            (* starting position of our hero; the final answer is board.(start).(0) *)
            let start = ref 0 in

            let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in

            (* read the 3 rows of the problem description *)
            for i = 0 to 2 do
                Scanf.scanf "%s\n" (fun s ->
                    (* check whether the start is in this row *)
                    if s.[0] = 's' then start := i;
                    (* populate the trains matrix *)
                    String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);

                (* populate the base case: we win from the right-most column *)
                board.(i).(n - 1) <- true
            done;

            (* work leftwards from the rightmost column *)
            for j = n - 2 downto 0 do
                (* we move one cell to the right, then up, down or no movement vertically
                 * so we can win if there's no train to our right and there's a winning row
                 * that we can reach at col j+1
                 *
                 * for each step we've moved to the right, the trains have moved twice to the left
                 * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2
                 * will be there now, so we ensure we're not stepping into a train
                 *
                 * then we check that our decision of up, down or nothing will not be hit by a train,
                 * so we check 3j - 1 and 3j in the new row *)
                for i = 0 to 2 do
                    (* what if we moved up? *)
                    let up =
                        if i = 0 then false
                        else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+1)) || (train_at (i-1) (3*j+2)) || (train_at (i-1) (3*j+3)))
                    (* or if we didn't move? *)
                    and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (3*j+3)))
                    (* or if we moved down? *)
                    and dn =
                        if i = 2 then false
                        else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+1)) || (train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+3)))
                    in
                    board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))
                done
            done;

            print_endline (if board.(!start).(0) then "YES" else "NO"))
    done)

let () = Scanf.scanf "%d\n" (fun t ->
    for test = 1 to t do
        (* number of columns and number of trains *)
        Scanf.scanf "%d %d\n" (fun n _ ->
            (* DP board, 3 rows by n columns, initially false
             * board.(i).(j) = true if it's possible to survive from that position *)
            let board = Array.make_matrix 3 n false
            and trains = Array.make_matrix 3 n false in
            (* starting position of our hero; the final answer is board.(start).(0) *)
            let start = ref 0 in

            let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in

            (* read the 3 rows of the problem description *)
            for i = 0 to 2 do
                Scanf.scanf "%s\n" (fun s ->
                    (* check whether the start is in this row *)
                    if s.[0] = 's' then start := i;
                    (* populate the trains matrix *)
                    String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);

                (* populate the base case: we win from the right-most column *)
                board.(i).(n - 1) <- true
            done;

            (* work leftwards from the rightmost column *)
            for j = n - 2 downto 0 do
                (* we move one cell to the right, then up, down or no movement vertically
                 * so we can win if there's no train to our right and there's a winning row
                 * that we can reach at col j+1
                 *
                 * for each step we've moved to the right, the trains have moved twice to the left
                 * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2
                 * will be there now, so we ensure we're not stepping into a train
                 *
                 * then we check that our decision of up, down or nothing will not be hit by a train,
                 * so we check 3j - 1 and 3j in the new row *)
                for i = 0 to 2 do
                    (* what if we moved up? *)
                    let up =
                        if i = 0 then false
                        else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+2)) || (train_at (i-1) (3*j+3)))
                    (* or if we didn't move? *)
                    and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (3*j+3)))
                    (* or if we moved down? *)
                    and dn =
                        if i = 2 then false
                        else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+3)))
                    in
                    board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))
                done
            done;

            print_endline (if board.(!start).(0) then "YES" else "NO"))
    done)

let () = Scanf.scanf "%d\n" (fun t ->
    for test = 1 to t do
        (* number of columns and number of trains *)
        Scanf.scanf "%d %d\n" (fun n _ ->
            (* DP board, 3 rows by n columns, initially false
             * board.(i).(j) = true if it's possible to survive from that position *)
            let board = Array.make_matrix 3 n false
            and trains = Array.make_matrix 3 n false in
            (* starting position of our hero; the final answer is board.(start).(0) *)
            let start = ref 0 in

            let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in

            (* read the 3 rows of the problem description *)
            for i = 0 to 2 do
                Scanf.scanf "%s\n" (fun s ->
                    (* check whether the start is in this row *)
                    if s.[0] = 's' then start := i;
                    (* populate the trains matrix *)
                    String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);

                (* populate the base case: we win from the right-most column *)
                board.(i).(n - 1) <- true
            done;

            (* work leftwards from the rightmost column *)
            for j = n - 2 downto 0 do
                (* we move one cell to the right, then up, down or no movement vertically
                 * so we can win if there's no train to our right and there's a winning row
                 * that we can reach at col j+1
                 *
                 * for each step we've moved to the right, the trains have moved twice to the left
                 * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2
                 * will be there now, so we ensure we're not stepping into a train
                 *
                 * then we check that our decision of up, down or nothing will not be hit by a train,
                 * so we check 3j - 1 and 3j in the new row *)
                for i = 0 to 2 do
                    (* what if we moved up? *)
                    let up =
                        if i = 0 then false
                        else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+1)) || (train_at (i-1) (3*j+2)) || (train_at (i-1) (3*j+3)))
                    (* or if we didn't move? *)
                    and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (3*j+3)))
                    (* or if we moved down? *)
                    and dn =
                        if i = 2 then false
                        else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+2)) || (train_at (i+1) (3*j+3)))
                    in
                    board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))
                done
            done;

            print_endline (if board.(!start).(0) then "YES" else "NO"))
    done)

let () = Scanf.scanf "%d\n" (fun t ->
    for test = 1 to t do
        (* number of columns and number of trains *)
        Scanf.scanf "%d %d\n" (fun n _ ->
            (* DP board, 3 rows by n columns, initially false
             * board.(i).(j) = true if it's possible to survive from that position *)
            let board = Array.make_matrix 3 n false
            and trains = Array.make_matrix 3 n false in
            (* starting position of our hero; the final answer is board.(start).(0) *)
            let start = ref 0 in

            let train_at i j = if j >= n || j < 0 then false else trains.(i).(j) in

            (* read the 3 rows of the problem description *)
            for i = 0 to 2 do
                Scanf.scanf "%s\n" (fun s ->
                    (* check whether the start is in this row *)
                    if s.[0] = 's' then start := i;
                    (* populate the trains matrix *)
                    String.iteri (fun j c -> if not (c = '.' || c = 's') then trains.(i).(j) <- true) s);

                (* populate the base case: we win from the right-most column *)
                board.(i).(n - 1) <- true
            done;

            (* work leftwards from the rightmost column *)
            for j = n - 2 downto 0 do
                (* we move one cell to the right, then up, down or no movement vertically
                 * so we can win if there's no train to our right and there's a winning row
                 * that we can reach at col j+1
                 *
                 * for each step we've moved to the right, the trains have moved twice to the left
                 * so we adjust our index there accordingly: if we step onto cell j, the train at 2(j-1) + j = 3j - 2
                 * will be there now, so we ensure we're not stepping into a train
                 *
                 * then we check that our decision of up, down or nothing will not be hit by a train,
                 * so we check 3j - 1 and 3j in the new row *)
                for i = 0 to 2 do
                    (* what if we moved up? *)
                    let up =
                        if i = 0 then false
                        else board.(i-1).(j+1) && not ((train_at (i-1) (3*j+2)) || (train_at (i-1) (4*j)))
                    (* or if we didn't move? *)
                    and no = board.(i).(j+1) && not ((train_at i (3*j+2)) || (train_at i (4*j)))
                    (* or if we moved down? *)
                    and dn =
                        if i = 2 then false
                        else board.(i+1).(j+1) && not ((train_at (i+1) (3*j+2)) || (train_at (i+1) (4*j)))
                    in
                    board.(i).(j) <- (up || dn || no) && not (train_at i (3*j+1))
                done
            done;

            print_endline (if board.(!start).(0) then "YES" else "NO"))
    done)


Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.

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 h = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = 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 pos = ref 0 in
  let res = ref 0L in
  let g = ref 0 in
    while !pos < n do
      while !pos < n && !g <= h - a.(!pos) do
	g := !g + a.(!pos);
	incr pos;
      done;
      if !g < k then (
	res := !res +| 1L;
	g := 0;
      );
      res := !res +| Int64.of_int (!g / k);
      g := !g mod k;
    done;
    if !g > 0
    then res := !res +| 1L;
    Printf.printf "%Ld\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 long x = Int64.of_int x

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let h = long (read_int ()) in
  let k = long (read_int ()) in

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

  let rec loop i ac rem =
    (* i = next piece to put in, ac=time used so far, rem=amount in there *)

    let multi_step i ac rem =
      if rem < k then loop i (ac++1L) 0L
      else (
	let x = rem // k in
	loop i (ac++x) (rem -- x**k)
      )
    in
    if i<n then (
      if a.(i) ++ rem <= h then loop (i+1) ac (a.(i) ++ rem)
      else if rem > 0L then multi_step i ac rem
      else failwith "impossible"
    ) else (
      if rem > 0L then multi_step i ac rem
      else ac
    )
  in

  let answer = loop 0 0L 0L in

  printf "%Ld\n" answer


Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.

NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and m=read_int();;
let tab=Array.make (n+1) 1;;
for i=1 to m do
   let a=read_int() in
   if a=1 then (let b=read_int() and c=read_int() in tab.(b)<-0;tab.(c)<-0)
          else let b=read_int() in tab.(b)<-0
done;;
let vec=Array.copy tab;;
let s=ref 0;;
let t=ref 0;;
let rec doo1 i = if i=n then 0 else tab.(i)+doo1 (i+1);;
let rec doo2 i = if i>n-1 then 0 else if tab.(i)*tab.(i+1)=1 then 1+doo2 (i+2) else tab.(i)+doo2 (i+1);;
print_int (doo2 1);;
print_string " ";;
print_int (doo1 1);;


The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:  If x = 1, exit the function.  Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.

let f n =
    begin
        Printf.printf "%d" n;
        for i = 1 to n-1 do
            Printf.printf " %d" i
        done;
        print_endline "";
    end

let _ =
    Scanf.scanf " %d" f

let swap ary i j =
  let temp = ary.(i) in
  ary.(i) <- ary.(j);
  ary.(j) <- temp

let range x y =
  let ary = Array.make (y - x) 0 in
  let rec range n =
    if n == y then ary
    else begin
      ary.(n-x) <- n;
      range (n + 1)
    end
  in
  range x

let solve n =
  let ary = range 1 (n + 1) in
  let rec solve x =
    if x == 1 then ary
    else begin
      swap ary (x - 2) (x - 1);
      solve (x - 1)
    end
  in
  solve n

let rec print n ary =
  if n+1 >= Array.length ary then Printf.printf "%d\n" ary.(n)
  else begin
    Printf.printf "%d " ary.(n);
    print (n + 1) ary;
  end

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let ans = solve n in
  print 0 ans

let solve n =
  begin
    Printf.printf "%d" n;
    for i = 1 to n - 1 do
      Printf.printf " %d" i
    done;
    print_endline "";
  end

let _ =
  Scanf.scanf " %d" solve