A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make.

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of initial bouquets. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the number of flowers in each of the initial bouquets.

Print the maximum number of large bouquets Vasya can make.

NoteIn the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25.

open Printf
open Scanf

let (++) = Int64.add
let (--) = Int64.sub
let ( ** ) = Int64.mul
let (//) = Int64.div
let (%%) = Int64.rem
let landl = Int64.logand
let lorl = Int64.logor
let lnotl = Int64.lognot
let lxorl = Int64.logxor
let lsll = Int64.shift_left
let lsrl = Int64.shift_right_logical
let long = Int64.of_int
let succl = Int64.succ
let predl = Int64.pred

let read_int _ = scanf " %d " (fun x -> x)
let read_long _ = scanf " %Ld " (fun x -> x)
let read_str _ = scanf " %s " (fun x -> x)
let read_double _ = scanf " %f " (fun x -> x)

let m = 1_000_000_007L

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

let rec mod_pow a = function
  | 0L -> 1L
  | b -> (if b %% 2L = 0L then 1L else a) ** mod_pow (a ** a %% m) (b//2L) %% m

let () =
  let n = read_int () in
  let a = Array.(init n read_int |> to_list) in
  let oddc = List.(a |> filter (fun x -> x mod 2 == 1) |> length) in
  let m = min oddc (n-oddc) in
  printf "%d\n" @@ (oddc-m) / 3 + m


You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA".

let input () = Pervasives.read_line ()
let print str = Pervasives.print_endline str

let find a b str l =
    let rec loop i prev sawAB sawBA =
        if i < l
        then
            if sawAB = false
            then
                if str.[i] = b && prev = a
                then
                    loop (i + 1) 'Z' true sawBA
                else
                    loop (i + 1) str.[i] sawAB sawBA
            else
                if str.[i] = a && prev = b
                then
                    true
                else
                    loop (i + 1) str.[i] sawAB sawBA
        else
            false
    in loop 0 'Z' false false

let solve str =
    let l = String.length str in
    let result =
        (if (find 'A' 'B' str l) || (find 'B' 'A' str l)
        then
            "YES"
        else
            "NO")
    in print result

let () = solve (input ())

let input () = Pervasives.read_line ()
let print str = Pervasives.print_endline str

let find a b str l =
    let rec loop i prev sawAB sawBA =
        if i < l
        then
            if sawAB = false || sawBA = false
            then
                if str.[i] = b && prev = a && sawAB = false
                then
                    loop (i + 1) 'Z' true sawBA
                else
                    if str.[i] = a && prev = b && sawBA = false
                    then
                        loop (i + 1) 'Z' sawAB true
                    else
                        loop (i + 1) str.[i] sawAB sawBA
            else
                true
        else
            if sawAB && sawBA
            then
                true
            else
                false
    in loop 1 str.[0] false false

let solve str =
    let l = String.length str in
    let result =
        (if (find 'A' 'B' str l) || (find 'B' 'A' str l)
        then
            "YES"
        else
            "NO")
    in print result

let () = solve (input ())


Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains a single string $$$s$$$ ($$$1 \leq |s| \leq 50$$$) consisting of lowercase English letters.

For each test case, print the final string in a single line.

NoteIn the first test case: Alice makes the first move and must change the only letter to a different one, so she changes it to 'b'.In the second test case: Alice changes the first letter to 'a', then Bob changes the second letter to 'z', Alice changes the third letter to 'a' and then Bob changes the fourth letter to 'z'.In the third test case: Alice changes the first letter to 'b', and then Bob changes the second letter to 'y'.

open Printf
open Scanf

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

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let s = read_string() in
    let n = String.length s in
    for i=0 to n-1 do
      if i mod 2 = 0 then (
	if s.[i] = 'a' then printf "b" else printf "a"
      ) else (
	if s.[i] = 'z' then printf "y" else printf "z"
      )
    done;
    print_newline()
  done


The developers of Looksery have to write an efficient algorithm that detects faces on a picture. Unfortunately, they are currently busy preparing a contest for you, so you will have to do it for them. In this problem an image is a rectangular table that consists of lowercase Latin letters. A face on the image is a 2 × 2 square, such that from the four letters of this square you can make word "face". You need to write a program that determines the number of faces on the image. The squares that correspond to the faces can overlap.

The first line contains two space-separated integers, n and m (1 ≤ n, m ≤ 50) — the height and the width of the image, respectively. Next n lines define the image. Each line contains m lowercase Latin letters.

In the single line print the number of faces on the image.

NoteIn the first sample the image contains a single face, located in a square with the upper left corner at the second line and the second column:   In the second sample the image also contains exactly one face, its upper left corner is at the second row and the first column.In the third sample two faces are shown:   In the fourth sample the image has no faces on it.

open Printf
open Scanf

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

let () =
  let (n, m) = read_pair () in
  let board = Array.init n (fun _ -> read_string ()) in

  let count = ref 0 in

  let is_face l =
    let l = List.sort compare l in
    l = ['a'; 'c'; 'e'; 'f']
  in

  for i=0 to n-2 do
    for j = 0 to m-2 do
      if is_face [board.(i).[j]; board.(i+1).[j]; board.(i).[j+1]; board.(i+1).[j+1] ]
      then count := !count + 1
    done
  done;

  printf "%d\n" !count

(* iterate all 2x2 square *)
open Scanf
open Printf
let read_int() = bscanf Scanning.stdib " %d " (fun x->x)
let read_string() = bscanf Scanning.stdib " %s " (fun x->x)

let () =
  let n = read_int() in
  let m = read_int() in
  let img = Array.init n (fun _-> read_string()) in
  let ci c = int_of_char c in
  let face = 1 lsl (ci 'f') + 1 lsl (ci 'a') + 1 lsl (ci 'c') + 1 lsl (ci 'e') in
  let is_face a b c d = 1 lsl (ci a) + 1 lsl (ci b) + 1 lsl (ci c) + 1 lsl (ci d) == face in
  let count = ref 0 in
  for i=0 to n-2 do
	for j=0 to m-2 do
	  if is_face img.(i).[j] img.(i).[j+1] img.(i+1).[j] img.(i+1).[j+1] then
		count := !count + 1
	done
  done;
	printf "%d\n" !count

let ok mat =
	let compt = ref 0 in
	for i=0 to Array.length mat - 2 do
	for j=0 to String.length (mat.(0)) - 2 do
		if List.sort compare [(mat.(i)).[j];(mat.(i+1)).[j];(mat.(i)).[j+1];(mat.(i+1)).[j+1]] = ['a';'c';'e';'f']
			then incr compt;
	done;
	done;
	!compt

let () =
	let n = Scanf.scanf "%d %d " (fun i _ -> i) in
	let tab = Array.init n (fun i -> Scanf.scanf " %s" (fun j -> j)) in
		Printf.printf "%d" (ok tab)

open Printf
open Scanf

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

  let count = ref 0 in

  let is_face l =
    let l = List.sort compare l in
    l = ['a';'c';'e';'f']
  in

  for i=0 to n-2 do
    for j=0 to m-2 do
      if is_face [board.(i).[j]; board.(i+1).[j]; board.(i).[j+1]; board.(i+1).[j+1] ]
      then count := !count + 1
    done
  done;

  printf "%d\n" !count


You've got two rectangular tables with sizes na × ma and nb × mb cells. The tables consist of zeroes and ones. We will consider the rows and columns of both tables indexed starting from 1. Then we will define the element of the first table, located at the intersection of the i-th row and the j-th column, as ai, j; we will define the element of the second table, located at the intersection of the i-th row and the j-th column, as bi, j. We will call the pair of integers (x, y) a shift of the second table relative to the first one. We'll call the overlap factor of the shift (x, y) value:where the variables i, j take only such values, in which the expression ai, j·bi + x, j + y makes sense. More formally, inequalities 1 ≤ i ≤ na, 1 ≤ j ≤ ma, 1 ≤ i + x ≤ nb, 1 ≤ j + y ≤ mb must hold. If there are no values of variables i, j, that satisfy the given inequalities, the value of the sum is considered equal to 0. Your task is to find the shift with the maximum overlap factor among all possible shifts.

The first line contains two space-separated integers na, ma (1 ≤ na, ma ≤ 50) — the number of rows and columns in the first table. Then na lines contain ma characters each — the elements of the first table. Each character is either a "0", or a "1". The next line contains two space-separated integers nb, mb (1 ≤ nb, mb ≤ 50) — the number of rows and columns in the second table. Then follow the elements of the second table in the format, similar to the first table. It is guaranteed that the first table has at least one number "1". It is guaranteed that the second table has at least one number "1".

Print two space-separated integers x, y (|x|, |y| ≤ 109) — a shift with maximum overlap factor. If there are multiple solutions, print any of them.

let main =
  let (na, ma) = Scanf.scanf "%d %d " (fun a b -> (a,b)) in
  let a = Array.make na "" in
  for i = 0 to na-1 do
    a.(i) <- Scanf.scanf "%s " (fun s -> s);
  done;
  let (nb, mb) = Scanf.scanf "%d %d " (fun a b -> (a,b)) in
  let b = Array.make nb "" in
  for i = 0 to nb-1 do
    b.(i) <- Scanf.scanf "%s " (fun s -> s);
  done;

  let find_sum y x =
    let sum = ref 0 in
    for i = 0 to na-1 do
      for j = 0 to ma -1 do
	if i >= 0 && i <= na -1 && j >= 0 && j <= ma - 1 &&
	   y+i >= 0 && y + i <= nb - 1 && x+j >= 0 && x+j <= mb - 1 then begin
	     if a.(i).[j] = '1' && b.(y+i).[x+j] = '1' then incr sum
	   end
      done;
    done;
    !sum in

  let m = ref 0 in
  let mxy = ref (0,0) in
  for i = (-na) + 1 to nb - 1 do
    for j = (-ma) + 1 to mb - 1 do
      let s = find_sum i j in
      if s > !m then begin
	m := s;
	mxy := (i,j);
      end
    done;
  done;
  let (x,y) = !mxy in
  Printf.printf "%d %d\n" x y


Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second — from a2 to b2What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.

The first line of the input file contains integers n and x0 (1 ≤ n ≤ 100; 0 ≤ x0 ≤ 1000). The following n lines contain pairs of integers ai, bi (0 ≤ ai, bi ≤ 1000; ai ≠ bi).

Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.

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

let () =
  let n = read_int 0 in
  let x0 = read_int 0 in
  let l = ref 0 and r = ref 1000 in
  for i = 1 to n do
    let a = read_int 0 in
    let b = read_int 0 in
    let a,b = min a b, max a b in
    l := max !l a;
    r := min !r b
  done;
  Printf.printf "%d\n" (if !l > !r then
      -1
    else if x0 < !l then
      !l-x0
    else if !r < x0 then
      x0- !r
    else
      0)


The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or  - 1 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: .Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2k vectors in 2k-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?

The only line of the input contains a single integer k (0 ≤ k ≤ 9).

Print 2k lines consisting of 2k characters each. The j-th character of the i-th line must be equal to ' * ' if the j-th coordinate of the i-th vector is equal to  - 1, and must be equal to ' + ' if it's equal to  + 1. It's guaranteed that the answer always exists. If there are many correct answers, print any.

NoteConsider all scalar products in example:  Vectors 1 and 2: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( + 1) + ( - 1)·( - 1) = 0  Vectors 1 and 3: ( + 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 1 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 2 and 3: ( + 1)·( + 1) + ( - 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 2 and 4: ( + 1)·( + 1) + ( - 1)·( - 1) + ( + 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 3 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( + 1)·( - 1) + ( + 1)·( + 1) = 0

open Printf
open Scanf

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

let () =
  let k = read_int() in

  let v = Array.make (k+1) [||] in

  for i=0 to k do
    let d = 1 lsl i in
    v.(i) <- Array.make_matrix d d 0
  done;

  for i=1 to k do
    let d = 1 lsl i in
    let d' = d/2 in
    for j = 0 to d-1 do
      for l = 0 to d-1 do
	v.(i).(j).(l) <- v.(i-1).(j mod d').(l mod d');
	if j >= d' && l >= d' then v.(i).(j).(l) <- 1 - v.(i).(j).(l)
      done
    done
  done;

  let d = 1 lsl k in

  for j=0 to d-1 do
    for l=0 to d-1 do
      printf "%c" (if v.(k).(j).(l) = 0 then '*' else '+')
    done;
    print_newline()
  done


Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, if Jack uses the sequence 'right, left, break', when the sergeant yells: 'Left! Right! Left! Right! Left! Right!', Jack first makes a step with the right foot, then one with the left foot, then he is confused and stops for a moment, then again - this time according to the order - starts with the right foot, then uses the left foot, then - to the sergeant's irritation - he stops to catch his breath, to incorrectly start with the right foot again... Marching this way, Jack will make the step that he is supposed to in the given moment in only one third of cases.When the officers convinced him he should do something about it, Jack decided to modify the basic sequence of steps that he repeats. However, in order not to get too tired, he has decided that the only thing he'll do is adding any number of breaks in any positions of the original sequence (a break corresponds to stopping for the duration of one step). Of course, Jack can't make a step on the same foot twice in a row, if there is no pause between these steps. It is, however, not impossible that the sequence of steps he used so far is incorrect (it would explain a lot, actually).Help Private Jack! Given the sequence of steps he keeps repeating, calculate the maximal percentage of time that he can spend marching correctly after adding some breaks to his scheme.

The first line of input contains a sequence consisting only of characters 'L', 'R' and 'X', where 'L' corresponds to a step with the left foot, 'R' — with the right foot, and 'X' — to a break. The length of the sequence will not exceed 106.

Output the maximum percentage of time that Jack can spend marching correctly, rounded down to exactly six digits after the decimal point.

NoteIn the second example, if we add two breaks to receive LXXRXR, Jack will march: LXXRXRLXXRXRL... instead of LRLRLRLRLRLRL... and will make the correct step in half the cases. If we didn't add any breaks, the sequence would be incorrect — Jack can't step on his right foot twice in a row.

open Int64

let f a n =
  let rec go i p q f pair =
    if i >= n then
      p,q,f,pair
    else if a.[i] = 'X' then
      go (i+1) p (q+1) f pair
    else if a.[i] = (if q mod 2 = 0 then 'L' else 'R') then
      go (i+1) (p+1) (q+1) 0 pair
    else
      go (i+1) (p+1) (q+2) (1-f) (pair+f)
  in
  let p,q,f,pair = go 0 0 0 0 0 in
  let q,pair = if q mod 2 = 1 then q+1,pair+f else q,pair in
  let p,q = if p*2 > q then p-pair,q-pair*2 else p,q in
  div (mul (of_int p) 100000000L) (of_int q)

let () =
  let a = read_line () in
  let n = String.length a in
  let b = String.make (n*2) '.' in
  let m = ref 0 in
  for i = 0 to n-1 do
    if i > 0 && a.[i] = a.[i-1] && a.[i] != 'X' then (
      b.[!m] <- 'X';
      incr m;
    );
    b.[!m] <- a.[i];
    incr m
  done;
  let ans = if b.[0] = b.[!m-1] && b.[0] != 'X' then (
      b.[!m] <- 'X';
      max (f (b^"X") (!m+1)) (f ("X"^b) (!m+1))
    ) else
        f b !m
  in
  Printf.printf "%Ld.%06Ld\n" (div ans 1000000L) (rem ans 1000000L)

open Int64

let f a n =
  let rec go i p q f pair =
    if i >= n then
      p,q,f,pair
    else if a.[i] = 'X' then
      go (i+1) p (q+1) f pair
    else if a.[i] = (if q mod 2 = 0 then 'L' else 'R') then
      go (i+1) (p+1) (q+1) 0 pair
    else
      go (i+1) (p+1) (q+2) (1-f) (pair+f)
  in
  let p,q,f,pair = go 0 0 0 0 0 in
  let q,pair = if q mod 2 = 1 then q+1,pair+f else q,pair in
  let p,q = if p*2 > q then p-pair,q-pair*2 else p,q in
  div (mul (of_int p) 100000000L) (of_int q)

let () =
  let a = read_line () in
  let n = String.length a in
  let b = String.make (n*2) '.' in
  let m = ref 0 in
  for i = 0 to n-1 do
    if i > 0 && a.[i] = a.[i-1] && a.[i] != 'X' then (
      b.[!m] <- 'X';
      incr m;
    );
    b.[!m] <- a.[i];
    incr m
  done;
  let ans = if b.[0] = b.[!m-1] && b.[0] != 'X' then
      max (f (b^"X") (!m+1)) (f ("X"^b) (!m+1))
    else
      f b !m
  in
  Printf.printf "%Ld.%06Ld\n" (div ans 1000000L) (rem ans 1000000L)

open Int64

let f a n =
  let rec go i p q f pair =
    if i >= n then
      p,q,f,pair
    else if a.[i] = 'X' then
      go (i+1) p (q+1) f pair
    else if a.[i] = (if q mod 2 = 0 then 'L' else 'R') then
      go (i+1) (p+1) (q+1) 0 pair
    else
      go (i+1) (p+1) (q+2) (1-f) (pair+f)
  in
  let p,q,f,pair = go 0 0 0 0 0 in
  let q,pair = if q mod 2 = 1 then q+1,pair+f else q,pair in
  let p,q = if p*2 > q then p-pair,q-pair else p,q in
  div (mul (of_int p) 100000000L) (of_int q)

let () =
  let a = read_line () in
  let n = String.length a in
  let b = String.make (n*2) '.' in
  let m = ref 0 in
  for i = 0 to n-1 do
    if i > 0 && a.[i] = a.[i-1] && a.[i] != 'X' then (
      b.[!m] <- 'X';
      incr m;
    );
    b.[!m] <- a.[i];
    incr m
  done;
  let ans = if b.[0] = b.[!m-1] && b.[0] != 'X' then
      max (f (b^"X") (!m+1)) (f ("X"^b) (!m+1))
    else
      f b !m
  in
  Printf.printf "%Ld.%06Ld\n" (div ans 1000000L) (rem ans 1000000L)


You are standing at the point $$$0$$$ on a coordinate line. Your goal is to reach the point $$$n$$$. In one minute, you can move by $$$2$$$ or by $$$3$$$ to the left or to the right (i. e., if your current coordinate is $$$x$$$, it can become $$$x-3$$$, $$$x-2$$$, $$$x+2$$$ or $$$x+3$$$). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ lines describing the test cases follow. The $$$i$$$-th of these lines contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the goal of the $$$i$$$-th test case.

For each test case, print one integer — the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$ for the corresponding test case.

let rec loop t =
  if t > 0 then
    let n = read_int() in
    print_int ( if n > 3 then
                  (n + 2) / 3
                else
                  1 + (if n = 1 then 1 else 0));
    print_newline ();
    loop (t-1)
  else ()
;;

loop (read_int ());;


There are $$$n$$$ students numerated from $$$1$$$ to $$$n$$$. The level of the $$$i$$$-th student is $$$a_i$$$. You need to split the students into stable groups. A group of students is called stable, if in the sorted array of their levels no two neighboring elements differ by more than $$$x$$$.For example, if $$$x = 4$$$, then the group with levels $$$[1, 10, 8, 4, 4]$$$ is stable (because $$$4 - 1 \le x$$$, $$$4 - 4 \le x$$$, $$$8 - 4 \le x$$$, $$$10 - 8 \le x$$$), while the group with levels $$$[2, 10, 10, 7]$$$ is not stable ($$$7 - 2 = 5 > x$$$).Apart from the $$$n$$$ given students, teachers can invite at most $$$k$$$ additional students with arbitrary levels (at teachers' choice). Find the minimum number of stable groups teachers can form from all students (including the newly invited).For example, if there are two students with levels $$$1$$$ and $$$5$$$; $$$x = 2$$$; and $$$k \ge 1$$$, then you can invite a new student with level $$$3$$$ and put all the students in one stable group.

The first line contains three integers $$$n$$$, $$$k$$$, $$$x$$$ ($$$1 \le n \le 200\,000$$$, $$$0 \le k \le 10^{18}$$$, $$$1 \le x \le 10^{18}$$$) — the initial number of students, the number of students you can additionally invite, and the maximum allowed level difference. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^{18}$$$) — the students levels.

In the only line print a single integer: the minimum number of stable groups you can split the students into.

NoteIn the first example you can invite two students with levels $$$2$$$ and $$$11$$$. Then you can split the students into two stable groups:   $$$[1, 1, 2, 5, 8, 11, 12, 13]$$$,  $$$[20, 22]$$$. In the second example you are not allowed to invite new students, so you need $$$3$$$ groups:   $$$[1, 1, 5, 5, 20, 20]$$$  $$$[60, 70, 70, 70, 80, 90]$$$  $$$[420]$$$

let scan_int () = Scanf.scanf " %d" (fun x -> x)
let scan_lint () = Scanf.scanf " %Ld" (fun x -> x)
let n = scan_int()
let k = ref (scan_lint())
let x = scan_lint()

let () =
  let a = Array.make n 0L in
  for i = 0 to n - 1 do
    a.(i) <- scan_lint()
  done;
  Array.sort compare a;
  let d = Array.make (n - 1) 0L in
  for i = 0 to n - 2 do
    d.(i) <- Int64.sub a.(i + 1) a.(i)
  done;
  Array.sort compare d;
  let ans = ref n in
  for i = 0 to Array.length d - 1 do
    if d.(i) <= x then
      ans := !ans - 1
    else if !k > 0L then
      let di = Int64.sub d.(i) 1L in
      let c = Int64.div di x in
      let ok = !k >= c in
        if ok then k := (Int64.sub !k c);
        if ok then ans := !ans - 1;
  done;
  Printf.printf "%d\n" !ans;;

open Int64;;
open Array;;
let da x = ();;
let is_digit c =
  if (int_of_char c) >= (int_of_char '0')
  then if (int_of_char c) <= (int_of_char '9') then true
    else false
  else false;;
let digit c = (int_of_char c) - (int_of_char '0');;
let digitInt64 c = of_int(digit c);;
let readLine() = input_line stdin;;
let print_number x = print_string (to_string x ^ " ");;
let print_char c = print_string (Char.escaped c);;
let readChar() =
  let s = Bytes.create 1 in
  let () = da (input stdin s 0 1) in
  Bytes.get s 0;;
let readLong() =
  let number = ref 0L in
  let () =
    let quit_loop = ref false in
    while not !quit_loop do
      let c = readChar() in
      if is_digit c then
        number := add (mul !number 10L) (digitInt64 c)
      else
        quit_loop := true
    done in
  !number;;

let merge a b =
  let n = length a in
  let m = length b in
  let ret = make (n+m) 0L in
  let i = ref 0 in
  let j = ref 0 in
  let who = ref false in
  let ptr = ref 0 in
  while !ptr < (n+m) do
    let () =
      if !i < n then
        if !j < m then who := a.(!i) < b.(!j)
        else who := true
      else who := false in
    let () =
      if !who = true then ret.(!ptr) <- a.(!i)
      else ret.(!ptr) <- b.(!j) in
    let () =
      if !who = true then i := !i + 1
      else j := !j + 1 in
    ptr := !ptr + 1
  done;
  ret;;
let rec merge_sort a =
  if (length a) = 1 then a
  else
    let l = init ((length a + 1) / 2) (fun i -> a.(i)) in
    let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in
    merge (merge_sort l) (merge_sort r);;
let n = readLong() in
let k = ref (readLong()) in
let x = readLong() in
let a = Array.init (to_int n) (fun i -> readLong()) in
if n = 1L then print_number n
else
  let sorted = merge_sort a in
  let cost = make (to_int n-1) 0L in
  let () =
    for i = 1 to (length a - 1) do
      let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in
      if cost.(i-1) < 0L then cost.(i-1) <- 0L
    done in
  let sorted_cost = merge_sort cost in
  let answer = ref 1L in
  let () =
    for i = 0 to (length cost - 1) do
      if !k >= sorted_cost.(i) then
        k := Int64.sub !k sorted_cost.(i)
      else
        answer := Int64.add !answer 1L
    done in
  print_number !answer;;

open Int64;;
open Array;;
let merge a b =
  let n = length a in
  let m = length b in
  let ret = make (n+m) 0L in
  let i = ref 0 in
  let j = ref 0 in
  let who = ref false in
  let ptr = ref 0 in
  while !ptr < (n+m) do
    let () =
      if !i < n then
        if !j < m then who := a.(!i) < b.(!j)
        else who := true
      else who := false in
    let () =
      if !who = true then ret.(!ptr) <- a.(!i)
      else ret.(!ptr) <- b.(!j) in
    let () =
      if !who = true then i := !i + 1
      else j := !j + 1 in
    ptr := !ptr + 1
  done;
  ret;;
let rec merge_sort a =
  if (length a) = 1 then a
  else
    let l = init ((length a + 1) / 2) (fun i -> a.(i)) in
    let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in
    merge (merge_sort l) (merge_sort r);;
let readLong () = Scanf.scanf " %Ld" (fun i -> i);;
let print_number x = print_string (to_string x);;
let n = readLong() in
let k = ref (readLong()) in
let x = readLong() in
let a = Array.init (to_int n) (fun i -> readLong()) in
if n = 1L then print_number n
else
  let sorted = merge_sort a in
  let cost = make (to_int n-1) 0L in
  let () =
    for i = 1 to (length a - 1) do
      let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in
      if cost.(i-1) < 0L then cost.(i-1) <- 0L
    done in
  let sorted_cost = merge_sort cost in
  let answer = ref 1L in
  let () =
    for i = 0 to (length cost - 1) do
      if !k >= sorted_cost.(i) then
        k := Int64.sub !k sorted_cost.(i)
      else
        answer := Int64.add !answer 1L
    done in
  print_number !answer;;

let scan_int () = Scanf.scanf " %d" (fun x -> x)
let scan_lint () = Scanf.scanf " %Ld" (fun x -> x)
let n = scan_int()
let k = ref (scan_lint())
let x = scan_lint()

let () =
  let a = Array.make n 0L in
  for i = 0 to n - 1 do
    a.(i) <- scan_lint()
  done;
  let b = List.sort compare (Array.to_list a) in
  let d = Array.make (n - 1) 0L in
  for i = 1 to n - 2 do
    d.(i) <- Int64.sub (List.nth b i) (List.nth b (i - 1))
  done;
  let d = List.sort compare (Array.to_list d) in
  let ans = ref n in
  for i = 0 to List.length d - 1 do
    if (List.nth d i) <= x then
      ans := !ans - 1
    else if !k > 0L then
      let di = Int64.sub (List.nth d i) 1L in
      let c = Int64.div di x in
      let ok = !k >= c in
        if ok then k := (Int64.sub !k c);
        if ok then ans := !ans - 1;
  done;
  Printf.printf "%d\n" !ans;;

let scan_int () = Scanf.scanf " %d" (fun x -> x)
let scan_lint () = Scanf.scanf " %Ld" (fun x -> x)
let rec init n =
  if n = 0 then []
  else scan_lint() :: (init (n - 1))
let rec cal_diff l pos =
  if pos = List.length l then []
  else if pos = 0 then
    cal_diff l (pos + 1)
  else Int64.sub (List.nth l pos)  (List.nth l (pos - 1)) :: cal_diff l (pos + 1)
let get_diff l =  let sl = List.fast_sort compare l in List.sort compare (cal_diff sl 0)
let n = scan_int()
let k = ref (scan_lint())
let x = scan_lint()
let d = get_diff (init n)

let () =
  let ans = ref n in
  for i = 0 to List.length d - 1 do
    if (List.nth d i) <= x then
      ans := !ans - 1
    else
      let c = Int64.div (List.nth d i) x in
      let ok = !k >= c in
        if ok then k := (Int64.sub !k c);
        if ok then ans := !ans - 1;
  done;
  Printf.printf "%d\n" !ans;;

open Int64;;
open Array;;
let size = 1000;;
let s = Bytes.create size;;
let pos = ref 0;;
let ptr = ref 0;;
let read cnt =
  if !pos + cnt < size then
    let () = pos := !pos + (input stdin s !pos cnt) in
    true
  else
    false;;
let restart() =
  let () =
    for i = 1 to !pos - !ptr do
      Bytes.set s (i - 1) (Bytes.get s (i + !ptr))
    done in
  let () =
    pos := !pos - !ptr in
  ptr := 0;;
let da x = ();;
let is_digit c =
  if (int_of_char c) >= (int_of_char '0')
  then if (int_of_char c) <= (int_of_char '9') then true
    else false
  else false;;
let digit c = (int_of_char c) - (int_of_char '0');;
let digitInt64 c = of_int(digit c);;
let readLine() = input_line stdin;;
let print_number x = print_string (to_string x ^ " ");;
let print_char c = print_string (Char.escaped c);;
let check_reader() =
  let () =
    if !pos < size then da (read (size - !pos - 1)) in
  if !ptr >= 980 then restart();;
let skip() =
  let () = check_reader() in
  let quit_loop = ref false in
  while not !quit_loop do
    let c = Bytes.get s !ptr in
    let () =
      if is_digit c then quit_loop := true
      else ptr := !ptr + 1 in check_reader()
  done;;
let readLong() =
  let () = skip() in
  let quit_loop = ref false in
  let number = ref 0L in
  let () =
    while not !quit_loop do
      let c = Bytes.get s !ptr in
      if is_digit c then
        let () = number := add (mul !number  10L) (digitInt64 c) in
        ptr := !ptr + 1
      else
        quit_loop := true
    done in
  !number;;
let merge a b =
  let n = length a in
  let m = length b in
  let ret = make (n+m) 0L in
  let i = ref 0 in
  let j = ref 0 in
  let who = ref false in
  let ptr = ref 0 in
  while !ptr < (n+m) do
    let () =
      if !i < n then
        if !j < m then who := a.(!i) < b.(!j)
        else who := true
      else who := false in
    let () =
      if !who = true then ret.(!ptr) <- a.(!i)
      else ret.(!ptr) <- b.(!j) in
    let () =
      if !who = true then i := !i + 1
      else j := !j + 1 in
    ptr := !ptr + 1
  done;
  ret;;
let rec merge_sort a =
  if (length a) = 1 then a
  else
    let l = init ((length a + 1) / 2) (fun i -> a.(i)) in
    let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in
    merge (merge_sort l) (merge_sort r);;
let n = readLong() in
let k = ref (readLong()) in
let x = readLong() in
let a = Array.init (to_int n) (fun i -> readLong()) in
if n = 1L then print_number n
else
  let sorted = merge_sort a in
  let cost = make (to_int n-1) 0L in
  let () =
    for i = 1 to (length a - 1) do
      let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in
      if cost.(i-1) < 0L then cost.(i-1) <- 0L
    done in
  let sorted_cost = merge_sort cost in
  let answer = ref 1L in
  let () =
    for i = 0 to (length cost - 1) do
      if !k >= sorted_cost.(i) then
        k := Int64.sub !k sorted_cost.(i)
      else
        answer := Int64.add !answer 1L
    done in
  print_number !answer;;

open Int64;;
open Array;;
let size = 1000;;
let s = Bytes.create size;;
let pos = ref 0;;
let ptr = ref 0;;
let read cnt =
  if !pos + cnt < size then
    let nums = (input stdin s !pos cnt) in
    let () = pos := !pos + nums in
    true
  else
    false;;
let restart() =
  let () =
    for i = 1 to !pos - !ptr do
      Bytes.set s (i - 1) (Bytes.get s (i + !ptr))
    done in
  let () =
    pos := !pos - !ptr in
  ptr := 0;;
let da x = ();;
let is_digit c =
  if (int_of_char c) >= (int_of_char '0')
  then if (int_of_char c) <= (int_of_char '9') then true
    else false
  else false;;
let digit c = (int_of_char c) - (int_of_char '0');;
let digitInt64 c = of_int(digit c);;
let readLine() = input_line stdin;;
let print_number x = print_string (to_string x ^ " ");;
let print_char c = print_string (Char.escaped c);;
let check_reader() =
  let () =
    if !pos < size then da (read (size - !pos - 1)) in
  if !ptr >= 980 then restart();;
let skip() =
  let quit_loop = ref false in
  while not !quit_loop do
    let c = Bytes.get s !ptr in
    if is_digit c then quit_loop := true
    else ptr := !ptr + 1
  done;;
let readInt() =
  let () = check_reader() in
  let () = skip() in
  let quit_loop = ref false in
  let number = ref 0 in
  let () =
    while not !quit_loop do
      let c = Bytes.get s !ptr in
      if is_digit c then
        let () = number := !number * 10 + (digit c) in
        ptr := !ptr + 1
      else
        quit_loop := true
    done in
  !number;;
let readLong() =
  let () = check_reader() in
  let () = skip() in
  let quit_loop = ref false in
  let number = ref 0L in
  let () =
    while not !quit_loop do
      let c = Bytes.get s !ptr in
      if is_digit c then
        let () = number := add (mul !number  10L) (digitInt64 c) in
        ptr := !ptr + 1
      else
        quit_loop := true
    done in
  !number;;
let merge a b =
  let n = length a in
  let m = length b in
  let ret = make (n+m) 0L in
  let i = ref 0 in
  let j = ref 0 in
  let who = ref false in
  let ptr = ref 0 in
  while !ptr < (n+m) do
    let () =
      if !i < n then
        if !j < m then who := a.(!i) < b.(!j)
        else who := true
      else who := false in
    let () =
      if !who = true then ret.(!ptr) <- a.(!i)
      else ret.(!ptr) <- b.(!j) in
    let () =
      if !who = true then i := !i + 1
      else j := !j + 1 in
    ptr := !ptr + 1
  done;
  ret;;
let rec merge_sort a =
  if (length a) = 1 then a
  else
    let l = init ((length a + 1) / 2) (fun i -> a.(i)) in
    let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in
    merge (merge_sort l) (merge_sort r);;
let n = readLong() in
let k = ref (readLong()) in
let x = readLong() in
let a = Array.init (to_int n) (fun i -> readLong()) in
if n = 1L then print_number n
else
  let sorted = merge_sort a in
  let cost = make (to_int n-1) 0L in
  let () =
    for i = 1 to (length a - 1) do
      let () = cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x) in
      if cost.(i-1) < 0L then cost.(i-1) <- 0L
    done in
  let sorted_cost = merge_sort cost in
  let answer = ref 1L in
  let () =
    for i = 0 to (length cost - 1) do
      if !k >= sorted_cost.(i) then
        k := Int64.sub !k sorted_cost.(i)
      else
        answer := Int64.add !answer 1L
    done in
  print_number !answer;;

open Int64;;
open Array;;
let merge a b =
  let n = length a in
  let m = length b in
  let ret = make (n+m) 0L in
  let i = ref 0 in
  let j = ref 0 in
  let who = ref false in
  let ptr = ref 0 in
  while !ptr < (n+m) do
    let () =
      if !i < n then
        if !j < m then who := a.(!i) < b.(!j)
        else who := true
      else who := false in
    let () =
      if !who = true then ret.(!ptr) <- a.(!i)
      else ret.(!ptr) <- b.(!j) in
    let () =
      if !who = true then i := !i + 1
      else j := !j + 1 in
    ptr := !ptr + 1
  done;
  ret;;
let rec merge_sort a =
  if (length a) = 1 then a
  else
    let l = init ((length a + 1) / 2) (fun i -> a.(i)) in
    let r = init ((length a) / 2) (fun i -> a.(i + (length a + 1) / 2)) in
    merge (merge_sort l) (merge_sort r);;
let readLong () = Scanf.scanf " %Ld" (fun i -> i);;
let print_number x = print_string (to_string x);;
let n = readLong();;
let k = ref (readLong());;
let x = readLong();;
let a = Array.init (to_int n) (fun i -> readLong())
let sorted = merge_sort a;;
let cost = make (to_int n-1) 0L;;
for i = 1 to (length a - 1) do
  cost.(i-1) <- (Int64.div(Int64.sub(Int64.sub sorted.(i) sorted.(i-1)) 1L) x)
done;;
let sorted_cost = merge_sort cost;;
let answer = ref 1L;;
for i = 0 to (length cost - 1) do
  if !k >= sorted_cost.(i) then
    k := Int64.sub !k sorted_cost.(i)
  else
    answer := Int64.add !answer 1L
done;;
print_number !answer;;


Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa > pb, or pa = pb and ta < tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y + 1, y + 2, ..., y + x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y + x + 1-th place.Your task is to count what number of teams from the given list shared the k-th place.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1 ≤ pi, ti ≤ 50) — the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces.

In the only line print the sought number of teams that got the k-th place in the final results' table.

NoteThe final results' table for the first sample is:   1-3 places — 4 solved problems, the penalty time equals 10  4 place — 3 solved problems, the penalty time equals 20  5-6 places — 2 solved problems, the penalty time equals 1  7 place — 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is:  1 place — 5 solved problems, the penalty time equals 3  2-5 places — 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams.

let _ =
    let main () =
        let n, k = Scanf.sscanf (read_line ()) "%d %d" (fun n k -> n, k) in
        let rec loop i acc =
            if i = 0 then acc else loop (i - 1) (Scanf.sscanf (read_line ()) "%d %d" (fun a b -> (a, b) :: acc))
        in
        let l = loop n [] in
        let l = List.sort (fun (p0, t0) (p1, t1) -> compare (-p0, t0) (-p1, t1)) l in
        let r =
            let rec loop pt n hist = function
            | [] -> n :: hist
            | hd :: tl -> if hd = pt then loop pt (n + 1) hist tl
                                     else loop hd 1 (n :: hist) tl
            in
            match l with
            | [] -> failwith ""
            | pt :: tl -> loop pt 1 [] tl
        in
        let rec loop i = function
        | [] -> failwith ""
        | hd :: tl -> if i <= k && k < i + hd then Printf.printf "%d\n" hd else loop (i + hd) tl
        in
        loop 1 (List.rev r)
    in
    main ()


Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.

The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.

In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.

open Filename;;

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

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

let n = gr();;
let k = gr();;
let optv = ref (- 1001000000);;

let main() =
	begin
		for i = 1 to n do
				let f = gr () in
				let t = gr () in
				let v = if t > k then f - (t-k) else f in
				if v > !optv then
					optv := v
		done;
		print_int !optv; print_newline ()
	end;;

main();;

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

let () =
  let (n,k) = read_pair() in
  let best = ref 0 in
    for i=0 to n-1 do
      let (f,t) = read_pair() in
      let score = if t > k then f - (t-k) else f in
	if score > !best || i=0 then best := score
    done;
    Printf.printf "%d\n" !best


You are given a permutation $$$p$$$ of integers from $$$1$$$ to $$$n$$$, where $$$n$$$ is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type:   take two indices $$$i$$$ and $$$j$$$ such that $$$2 \cdot |i - j| \geq n$$$ and swap $$$p_i$$$ and $$$p_j$$$. There is no need to minimize the number of operations, however you should use no more than $$$5 \cdot n$$$ operations. One can show that it is always possible to do that.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$, $$$n$$$ is even) — the length of the permutation.  The second line contains $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) — the given permutation.

On the first line print $$$m$$$ ($$$0 \le m \le 5 \cdot n$$$) — the number of swaps to perform. Each of the following $$$m$$$ lines should contain integers $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$|a_i - b_i| \ge \frac{n}{2}$$$) — the indices that should be swapped in the corresponding swap. Note that there is no need to minimize the number of operations. We can show that an answer always exists.

NoteIn the first example, when one swap elements on positions $$$1$$$ and $$$2$$$, the array becomes sorted.In the second example, pay attention that there is no need to minimize number of swaps.In the third example, after swapping elements on positions $$$1$$$ and $$$5$$$ the array becomes: $$$[4, 5, 3, 1, 2, 6]$$$. After swapping elements on positions $$$2$$$ and $$$5$$$ the array becomes $$$[4, 2, 3, 1, 5, 6]$$$ and finally after swapping elements on positions $$$1$$$ and $$$4$$$ the array becomes sorted: $$$[1, 2, 3, 4, 5, 6]$$$.

let swap res p pp i j =
  let t = pp.(p.(i)) in
  pp.(p.(i)) <- pp.(p.(j));
  pp.(p.(j)) <- t;
  let t = p.(i) in
  p.(i) <- p.(j);
  p.(j) <- t;
  (i, j) :: res

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let pp = Array.make (n+1) 0 in
  let p = Array.init (n+1) (fun i -> if i = 0 then 0 else let x = Scanf.scanf "%d " (fun x -> x) in pp.(x) <- i; x) in
  let n2 = n/2 in
  let res = ref [] in

  for i = 0 to n-2 do
    let ii = n-i in
    let j = pp.(ii) in
    if (ii <> j) then
      if (ii - j) >=n2 then res := swap !res p pp ii j
      else if (j <= n2 && ii <= n2) then begin
        res := swap !res p pp j n;
        res := swap !res p pp n ii;
        res := swap !res p pp j n
      end else if (j <= n2 && ii > n2) then begin
        res := swap !res p pp j n;
        res := swap !res p pp n 1;
        res := swap !res p pp 1 ii;
        res := swap !res p pp j n
      end else if (ii > n2) then begin
        res := swap !res p pp j 1;
        res := swap !res p pp 1 ii
      end else begin
        res := swap !res p pp j 1;
        res := swap !res p pp 1 ii;
      end
  done;
  let ln = List.length !res in
  Printf.printf "%d\n" ln;
  List.iter (fun (x, y) -> Printf.printf "%d %d\n" x y) (!res |> List.rev)
;;

let swap res p pp i j =
  let t = pp.(p.(i)) in
  pp.(p.(i)) <- pp.(p.(j));
  pp.(p.(j)) <- t;
  let t = p.(i) in
  p.(i) <- p.(j);
  p.(j) <- t;
  (i, j) :: res

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let pp = Array.make (n+1) 0 in
  let p = Array.init (n+1) (fun i -> if i = 0 then 0 else let x = Scanf.scanf "%d " (fun x -> x) in pp.(x) <- i; x) in
  let n2 = n/2 in
  let res = ref [] in

  for i = 0 to n-2 do
    let ii = n-i in
    let j = pp.(ii) in
    if (ii <> j) then
      if (ii - j) >=n2 then res := swap !res p pp ii j
      else if (j <= n2 && ii <= n2) then begin
        res := swap !res p pp j n;
        res := swap !res p pp n ii;
        res := swap !res p pp j n
      end else if (j <= n2 && ii > n2) then begin
        res := swap !res p pp j n;
        res := swap !res p pp n 1;
        res := swap !res p pp 1 ii;
        res := swap !res p pp j n
      end else if (ii > n2) then begin
        res := swap !res p pp j 0;
        res := swap !res p pp 0 ii
      end else begin
        res := swap !res p pp j 0;
        res := swap !res p pp 0 ii;
      end
  done;
  let ln = List.length !res in
  Printf.printf "%d\n" ln;
  List.iter (fun (x, y) -> Printf.printf "%d %d\n" x y) (!res |> List.rev)
;;


Ashish has $$$n$$$ elements arranged in a line. These elements are represented by two integers $$$a_i$$$ — the value of the element and $$$b_i$$$ — the type of the element (there are only two possible types: $$$0$$$ and $$$1$$$). He wants to sort the elements in non-decreasing values of $$$a_i$$$.He can perform the following operation any number of times:  Select any two elements $$$i$$$ and $$$j$$$ such that $$$b_i \ne b_j$$$ and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of $$$a_i$$$ after performing any number of operations.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_i$$$ $$$(1 \le a_i \le 10^5)$$$  — the value of the $$$i$$$-th element. The third line containts $$$n$$$ integers $$$b_i$$$ $$$(b_i \in \{0, 1\})$$$  — the type of the $$$i$$$-th element.

For each test case, print "Yes" or "No" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value. You may print each letter in any case (upper or lower).

NoteFor the first case: The elements are already in sorted order.For the second case: Ashish may first swap elements at positions $$$1$$$ and $$$2$$$, then swap elements at positions $$$2$$$ and $$$3$$$.For the third case: The elements are already in sorted order.For the fourth case: No swap operations may be performed as there is no pair of elements $$$i$$$ and $$$j$$$ such that $$$b_i \ne b_j$$$. The elements cannot be sorted.For the fifth case: Ashish may swap elements at positions $$$3$$$ and $$$4$$$, then elements at positions $$$1$$$ and $$$2$$$.

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

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

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

    let is_sorted = forall 0 (n-2) (fun i -> a.(i) <= a.(i+1)) in
    let has_0 = exists 0 (n-1) (fun i -> b.(i) = 0) in
    let has_1 = exists 0 (n-1) (fun i -> b.(i) = 1) in

    if is_sorted || (has_0 && has_1) then printf "Yes\n" else printf "No\n"
  done


There is a straight line colored in white. n black segments are added on it one by one.After each segment is added, determine the number of connected components of black segments (i. e. the number of black segments in the union of the black segments). In particular, if one segment ends in a point x, and another segment starts in the point x, these two segments belong to the same connected component.

The first line contains a single integer n (1 ≤ n ≤ 200 000) — the number of segments. The i-th of the next n lines contains two integers li and ri (1 ≤ li < ri ≤ 109) — the coordinates of the left and the right ends of the i-th segment. The segments are listed in the order they are added on the white line.

Print n integers — the number of connected components of black segments after each segment is added.

NoteIn the first example there are two components after the addition of the first two segments, because these segments do not intersect. The third added segment intersects the left segment and touches the right segment at the point 4 (these segments belong to the same component, according to the statements). Thus the number of connected components of black segments is equal to 1 after that.

let read_int () = Scanf.scanf " %d" (fun x -> x);;
let n = read_int();;
let l = Array.make (2*n) (0,0,0);;
let qs = Array.init n (fun i -> let x = read_int() in let y = read_int() in
                        Array.set l (2*i) (x,i,0);
                        Array.set l (2*i+1) (y,i,1);
                        x,y);;
Array.sort Pervasives.compare l;;
let i = ref 0;;
let (last0,_,_) = l.(0);;
let last = ref last0;;
Array.iter (fun (v,ii,j) ->
    if(v <> !last) then (incr i; last := v);
    let (x,y) = qs.(ii) in
    if(j = 0) then Array.set qs ii (!i,y) else Array.set qs ii (x,!i);
    ()
  ) l;;
incr i;;

(* let fromX = Hashtbl.create 200000;;
 * S.iter (fun x -> Hashtbl.add fromX x !i; incr i) !allX;;
 *
 * let qs : (int*int) array = Array.map (fun (x,y) -> (Hashtbl.find fromX x, Hashtbl.find fromX y)) qs;; *)

let uf = Array.init !i (fun j -> j);;
let ur = Array.init !i (fun j -> 1);;
let ufr = Array.init !i (fun j -> j);;
let um = Array.init !i (fun j -> false);;
let ans = ref 0;;

let rec find i = if uf.(i) == i then i else (Array.set uf i (find uf.(i)); uf.(i));;

let mark i = let i = find i in
  if not um.(i) then (Array.set um i true; incr ans)
;;

let aux i j =
    Array.set uf i j;
    Array.set ufr j (max ufr.(i) ufr.(j));
    if(um.(i) && um.(j)) then decr ans;
    Array.set um j (um.(i) || um.(j));
    if ur.(j) = ur.(i) then Array.set ur j (ur.(j)+1)
;;

let unite i j =
  let i = find i in
  let j = find j in
  if i <> j then begin
    if(ur.(i) < ur.(j)) then aux i j
    else aux j i
  end;;

Array.iter (fun (x,y) -> begin
      let i = ref (find x) in
      mark !i;
      while y > ufr.(!i) do
        unite !i (ufr.(!i)+1);
        i := find !i
      done;
      Printf.printf "%d " !ans
    end) qs;;
  Printf.printf "\n"


You are given a permutation $$$p_1, p_2, \dots, p_n$$$. A permutation of length $$$n$$$ is a sequence such that each integer between $$$1$$$ and $$$n$$$ occurs exactly once in the sequence.Find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if $$$a=[4, 2, 7, 5]$$$ then its median is $$$4$$$ since after sorting the sequence, it will look like $$$[2, 4, 5, 7]$$$ and the left of two middle elements is equal to $$$4$$$. The median of $$$[7, 1, 2, 9, 6]$$$ equals $$$6$$$ since after sorting, the value $$$6$$$ will be in the middle of the sequence.Write a program to find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le m \le n$$$) — the length of the given sequence and the required value of the median. The second line contains a permutation $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). Each integer between $$$1$$$ and $$$n$$$ occurs in $$$p$$$ exactly once.

NoteIn the first example, the suitable pairs of indices are: $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$ and $$$(2, 4)$$$.

open Printf open Scanf
module Int64 = struct
	include Int64
	(* int *)
	let (+$) = (+)
	let (-$) = (-)
	let (/$) = (/)
	let ( *$) = ( * )
	(* int64 *)
	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 labs p = if p < 0L then -1L*p else p
	let (~~|) p = Int64.of_int p
	let (~|) p = Int64.to_int p

	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 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
end open Int64

let () =
	let n,m = get_2_i64 ()
	in let ar = input_i64_array n
	in
	let idx =
		let idx = ref 0 in
		Array.iteri (fun i v -> if v=m then idx:=i) ar;
		!idx;
	in
	let c = Array.make 500010 0L
	in let ofs = 250000
	in let sum,ans = ref ~~| ofs,ref 0L
	in c.(ofs) <- 1L;
	for i=0 to idx-$1 do
		if ar.(i) < m then sum+= -1L else if ar.(i) > m then sum+= 1L;
		c.(~| !sum) <- c.(~| !sum) + 1L;
	done;
	for i=idx to ~|n-$1 do
		if ar.(i) < m then sum+= -1L else if ar.(i) > m then sum+= 1L;
		ans += (c.(~| !sum) + c.((~| !sum) -$ 1));
	done;
	!ans |> print_i64_endline


The tycoon of a winery empire in Mondstadt, unmatched in every possible way. A thinker in the Knights of Favonius with an exotic appearance.This time, the brothers are dealing with a strange piece of wood marked with their names. This plank of wood can be represented as a string of $$$n$$$ characters. Each character is either a 'D' or a 'K'. You want to make some number of cuts (possibly $$$0$$$) on this string, partitioning it into several contiguous pieces, each with length at least $$$1$$$. Both brothers act with dignity, so they want to split the wood as evenly as possible. They want to know the maximum number of pieces you can split the wood into such that the ratios of the number of occurrences of 'D' to the number of occurrences of 'K' in each chunk are the same.Kaeya, the curious thinker, is interested in the solution for multiple scenarios. He wants to know the answer for every prefix of the given string. Help him to solve this problem!For a string we define a ratio as $$$a:b$$$ where 'D' appears in it $$$a$$$ times, and 'K' appears $$$b$$$ times. Note that $$$a$$$ or $$$b$$$ can equal $$$0$$$, but not both. Ratios $$$a:b$$$ and $$$c:d$$$ are considered equal if and only if $$$a\cdot d = b\cdot c$$$. For example, for the string 'DDD' the ratio will be $$$3:0$$$, for 'DKD' — $$$2:1$$$, for 'DKK' — $$$1:2$$$, and for 'KKKKDD' — $$$2:4$$$. Note that the ratios of the latter two strings are equal to each other, but they are not equal to the ratios of the first two strings.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$) — the length of the wood. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. Every character of $$$s$$$ will be either 'D' or 'K'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$.

For each test case, output $$$n$$$ space separated integers. The $$$i$$$-th of these numbers should equal the answer for the prefix $$$s_{1},s_{2},\dots,s_{i}$$$.

NoteFor the first test case, there is no way to partition 'D' or 'DDK' into more than one block with equal ratios of numbers of 'D' and 'K', while you can split 'DD' into 'D' and 'D'.For the second test case, you can split each prefix of length $$$i$$$ into $$$i$$$ blocks 'D'.

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 read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let s = read_string () in
    let h = Hashtbl.create 10 in
    let rec loop i d k = if i=n then () else (
      (* processing index i, (d,k) = number seen already *)
      let (d,k) = if s.[i] = 'D' then (d+1,k) else (d,k+1) in
      let g = gcd d k in
      let c = try Hashtbl.find h (d/g, k/g) with Not_found -> 0 in
      Hashtbl.replace h (d/g,k/g) (c+1);
      printf "%d " (c+1);
      loop (i+1) d k
    ) in

    loop 0 0 0;
    print_newline()
  done


Hands that shed innocent blood!There are n guilty people in a line, the i-th of them holds a claw with length Li. The bell rings and every person kills some of people in front of him. All people kill others at the same time. Namely, the i-th person kills the j-th person if and only if j < i and j ≥ i - Li.You are given lengths of the claws. You need to find the total number of alive people after the bell rings.

The first line contains one integer n (1 ≤ n ≤ 106) — the number of guilty people. Second line contains n space-separated integers L1, L2, ..., Ln (0 ≤ Li ≤ 109), where Li is the length of the i-th person's claw.

Print one integer — the total number of alive people after the bell rings.

NoteIn first sample the last person kills everyone in front of him.

open Printf
open Scanf

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

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

  let rec scan i reach ac = if i<0 then ac else (
    let ac = if reach > i then ac+1 else ac in
    let reach = min reach (i - claw.(i)) in
    scan (i-1) reach ac
  ) in

  printf "%d\n" (scan (n-1) n 0)


Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.

The only input line contains three space-separated integers b, n and c (2 ≤ b < 10106, 1 ≤ n < 10106, 1 ≤ c ≤ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.

In the only line output the amount of numbers written on the same page as the last number.

NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.

let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib " %Ld" (fun x -> x)
let read_str _ = Scanf.bscanf Scanf.Scanning.stdib " %s" (fun x -> x)
let (|>) x f = f x
let flip f x y = f y x

open Int64

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

let phi x =
  let rec go acc x i =
    if i**i > x then
      acc, x
    else if x%%i = 0L then
      let rec go2 x =
        if x%%i <> 0L then
          x
        else
          go2 (x//i)
      in
      go (acc--acc//i) (go2 x) (i++1L)
    else
      go acc x (i++1L)
  in
  let r,x = go x x 2L in
  if x > 1L then
    r--r//x
  else
    r

let f a p =
  let rec go acc i =
    if i >= String.length a then
      acc
    else
      let acc' = (acc**10L ++ (int_of_char a.[i] - 48 |> of_int)) %%p in
      go acc' (i+1)
  in
  go 0L 0

let powmod a n p =
  let rec go r a n =
    if n = 0L then
      r
    else if logand n 1L <> 0L then
      go (r**a%%p) (a**a%%p) (n//2L)
    else
      go r (a**a%%p) (n//2L)
  in
  go 1L a n

let () =
  let bb = read_str 0 in
  let nn = read_str 0 in
  let c = read_int64 0 in
  let phi_c = phi c in

  let b = f bb c in
  let n = if String.length nn >= 10 then
      f nn phi_c ++ phi_c
    else
      let n = of_string nn in
      if n--1L >= phi_c then
        n%%phi_c++phi_c
      else
        n
  in
  powmod b (n--1L) c ** (b++c--1L) %% c
  |> (fun x -> if x = 0L then c else x)
  |> Printf.printf "%Ld\n"

let read_int64 _ = Scanf.bscanf Scanf.Scanning.stdib " %Ld" (fun x -> x)
let read_str _ = Scanf.bscanf Scanf.Scanning.stdib " %s" (fun x -> x)
let (|>) x f = f x
let flip f x y = f y x

open Int64

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

let phi x =
  let rec go acc x i =
    if i**i > x then
      acc, x
    else if x%%i = 0L then
      let rec go2 x =
        if x%%i <> 0L then
          x
        else
          go2 (x//i)
      in
      go (acc--acc//i) (go2 x) (i++1L)
    else
      go acc x (i++1L)
  in
  let r,x = go x x 2L in
  if x > 1L then
    r--r//x
  else
    r

let f a p =
  let rec go acc i =
    if i >= String.length a then
      acc
    else
      let acc' = (acc**10L ++ (int_of_char a.[i] - 48 |> of_int)) %%p in
      go acc' (i+1)
  in
  go 0L 0

let powmod a n p =
  let rec go r a n =
    if n = 0L then
      r
    else if logand n 1L <> 0L then
      go (r**a%%p) (a**a%%p) (n//2L)
    else
      go r (a**a%%p) (n//2L)
  in
  go 1L a n

let () =
  let bb = read_str 0 in
  let nn = read_str 0 in
  let c = read_int64 0 in
  let phi_c = phi c in

  let b = f bb c in
  let b1 = b++c--1L in
  let n = f nn phi_c in
  let n1 = n++phi_c--1L in
  powmod b n1 c ** b1 %% c
  |> (fun x -> if x = 0L then c else x)
  |> Printf.printf "%Ld\n"


Wilbur the pig really wants to be a beaver, so he decided today to pretend he is a beaver and bite at trees to cut them down.There are n trees located at various positions on a line. Tree i is located at position xi. All the given positions of the trees are distinct.The trees are equal, i.e. each tree has height h. Due to the wind, when a tree is cut down, it either falls left with probability p, or falls right with probability 1 - p. If a tree hits another tree while falling, that tree will fall in the same direction as the tree that hit it. A tree can hit another tree only if the distance between them is strictly less than h. For example, imagine there are 4 trees located at positions 1, 3, 5 and 8, while h = 3 and the tree at position 1 falls right. It hits the tree at position 3 and it starts to fall too. In it's turn it hits the tree at position 5 and it also starts to fall. The distance between 8 and 5 is exactly 3, so the tree at position 8 will not fall.As long as there are still trees standing, Wilbur will select either the leftmost standing tree with probability 0.5 or the rightmost standing tree with probability 0.5. Selected tree is then cut down. If there is only one tree remaining, Wilbur always selects it. As the ground is covered with grass, Wilbur wants to know the expected total length of the ground covered with fallen trees after he cuts them all down because he is concerned about his grass-eating cow friends. Please help Wilbur.

The first line of the input contains two integers, n (1 ≤ n ≤ 2000) and h (1 ≤ h ≤ 108) and a real number p (0 ≤ p ≤ 1), given with no more than six decimal places. The second line of the input contains n integers, x1, x2, ..., xn ( - 108 ≤ xi ≤ 108) in no particular order.

Print a single real number — the expected total length of the ground covered by trees when they have all fallen down. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteConsider the first example, we have 2 trees with height 2.    There are 3 scenarios:  1. Both trees falls left. This can either happen with the right tree falling left first, which has  probability (also knocking down the left tree), or the left tree can fall left and then the right tree can fall left, which has  probability. Total probability is .  2. Both trees fall right. This is analogous to (1), so the probability of this happening is .  3. The left tree fall left and the right tree falls right. This is the only remaining scenario so it must have  probability.  Cases 1 and 2 lead to a total of 3 units of ground covered, while case 3 leads to a total of 4 units of ground covered. Thus, the expected value is .

open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac +. (f i))
let comp x = 1.0 -. x
let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_float () = bscanf Scanning.stdib " %f " (fun x -> x)

let () =
  let n = read_int () in
  let h = read_int () in
  let pl = read_float () in
  let x = Array.init n (fun _ -> read_int()) in
  Array.sort compare x;

  let pr = comp pl in

  let topple_left = Array.make n 0 in
  let topple_right = Array.make n (n-1) in

  for i=1 to n-1 do
    topple_left.(i) <- if x.(i) - x.(i-1) < h then topple_left.(i-1) else i;
    let j = n-1-i in
    topple_right.(j) <- if x.(j+1) - x.(j) < h then topple_right.(j+1) else j;
  done;

  let p = Array.make_matrix n (4*n) 0.0 in
  let int = Array.make ((n+1)*4) 0.0 in
  let inc i j ldir rdir x =
    if i <= j then
      let ind = 4*j + 2*ldir + rdir in
      p.(i).(ind) <- x +. p.(i).(ind)
  in

  let incx i ldir rdir x =
    let ind = 4*i + 2*ldir + rdir in
    int.(ind) <- x +. int.(ind)
  in

  let geti i ldir rdir = int.(4*i + 2*ldir + rdir) in
  let getp i j ldir rdir = p.(i).(4*j + 2*ldir + rdir) in

  inc 0 (n-1) 0 1 1.0;

  for i=0 to n-1 do
    for j=n-1 downto i do
      for ldir = 0 to 1 do
    for rdir = 0 to 1 do
      let pstate = getp i j ldir rdir in
      let xl = pstate *. 0.5 *. pl in
      let xr = pstate *. 0.5 *. pr in
      inc (i+1) j 0 rdir xl;
      incx i ldir 0 xl;
      if i=j then incx (j+1) 0 rdir xl;
      inc i (j-1) ldir 1 xr;
      incx (j+1) 1 rdir xr;
      if i=j then incx i ldir 1 xr;
      inc (topple_right.(i)+1) j 1 rdir xr;
      incx i ldir 1 xr;
      if topple_right.(i) >= j then incx (j+1) 1 rdir xr;
      inc i (topple_left.(j)-1) ldir 0 xl;
      incx (j+1) 0 rdir xl;
      if topple_left.(j) <= i then incx i ldir 0 xl;
    done
      done
    done
  done;

  let evaluate_gap i =
    let d = if i=0 || i=n then h else x.(i) - x.(i-1) in
    if d < h then
      (comp (geti i 0 1)) *. (float d)
    else
      (geti i 1 0) *. (float (min d (2*h))) +. ((geti i 0 0) +. (geti i 1 1)) *. (float h)
  in

  printf "%1.9f\n" (sum 0 n evaluate_gap 0.0)

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 sum i j f = fold i j (fun i a -> (f i) +. a) 0.0

let comp x = 1.0 -. x

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

let () =
  let n = read_int () in
  let h = read_int () in
  let pl = read_float () in
  let x = Array.init n (fun _ -> read_int()) in
  Array.sort compare x;

  let pr = comp pl in

  let topple_left = Array.make n 0 in
  (* topple_left.(i) is the furthest one to the left that topples
     as a result of toppling i to the left *)
  let topple_right = Array.make n (n-1) in

  for i=1 to n-1 do
    topple_left.(i) <- if x.(i) - x.(i-1) < h then topple_left.(i-1) else i;
    let j = n-1-i in
    topple_right.(j) <- if x.(j+1) - x.(j) < h then topple_right.(j+1) else j;
  done;

  let p = Array.make_matrix n (4*n) 0.0 in
  (* p.(i).(j).(lfalldir).(rfalldir) is the probability of the situation
     where the upright trees are [i,j] and the one to the left of this
     fell in direction lfalldir (0=left, 1=right) and the one to the
     right fell in rfalldir. *)

  let int = Array.make ((n+1)*4) 0.0 in
  (* represents the interval (numbered starting from 0 on the left)
     Stores the probability for each of the four ways the interval
     can be resolved.  Actually, for short intervals only the
     resolution (0,1) i.e. (left, right) is used *)

  let inc i j ldir rdir x =
    if i <= j then
      let ind = 4*j + 2*ldir + rdir in
      p.(i).(ind) <- x +. p.(i).(ind)
  in

  let incx i ldir rdir x =
    let ind = 4*i + 2*ldir + rdir in
    int.(ind) <- x +. int.(ind)
  in

  let geti i ldir rdir = int.(4*i + 2*ldir + rdir) in
  let getp i j ldir rdir = p.(i).(4*j + 2*ldir + rdir) in

  inc 0 (n-1) 0 1 1.0;

  for d=n-1 downto 0 do
    for i=0 to n-1-d do
      let j = i+d in
      for ldir = 0 to 1 do
	for rdir = 0 to 1 do
	  let pstate = getp i j ldir rdir in
	  let xl = pstate *. 0.5 *. pl in
	  let xr = pstate *. 0.5 *. pr in
	  (* i falls to the left *)
	  inc (i+1) j 0 rdir xl;
	  incx i ldir 0 xl;
	  if i=j then incx (j+1) 0 rdir xl;
	  (* j falls to the right *)
	  inc i (j-1) ldir 1 xr;
	  incx (j+1) 1 rdir xr;
	  if i=j then incx i ldir 1 xr;
	  (* i falls to the right *)
	  inc (topple_right.(i)+1) j 1 rdir xr;
	  incx i ldir 1 xr;
	  if topple_right.(i) >= j then incx (j+1) 1 rdir xr;
	  (* j falls to the left *)
	  inc i (topple_left.(j)-1) ldir 0 xl;
	  incx (j+1) 0 rdir xl;
	  if topple_left.(j) <= i then incx i ldir 0 xl;
	done
      done
    done
  done;

  let evaluate_gap i =
    let d = if i=0 || i=n then h else x.(i) - x.(i-1) in
    if d < h then
      (comp (geti i 0 1)) *. (float d)
    else
      (geti i 1 0) *. (float (min d (2*h))) +. ((geti i 0 0) +. (geti i 1 1)) *. (float h)
  in

  printf "%1.9f\n" (sum 0 n evaluate_gap)

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 sum i j f = fold i j (fun i a -> (f i) +. a) 0.0

let comp x = 1.0 -. x

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

let () =
  let n = read_int () in
  let h = read_int () in
  let pr = read_float () in
  let x = Array.init n (fun _ -> read_int()) in
  Array.sort compare x;

  let g = Array.make_matrix (n+1) (n+1) (-1.0) in
  (* g.(a).(b) is the probability that an interval with
     a trees on the left and b trees on the right survives. *)

  let pl = comp pr in

  g.(0).(1) <- pr;
  g.(1).(0) <- pl;
  g.(0).(0) <- 1.0;

  let rec compg a b =
    if g.(a).(b) >= 0.0 then g.(a).(b) else
      let answer = match (a,b) with
	| (0,_) -> 0.5 *. (pr *. (compg 0 (b-1)) +. pr)
	| (_,0) -> 0.5 *. (pl *. (compg (a-1) 0) +. pl)
	| (_,_) -> 0.5 *. (pl *. (compg (a-1) b) +. pr *. (compg a (b-1)))
      in
      g.(a).(b) <- answer;
      answer
  in

  let rec find_blocks i j ac = if j=n-1 then (i,j)::ac else
      (* i....j is an initial part of a block *)
      if x.(j+1) < h + x.(j)
      then find_blocks i (j+1) ac
      else find_blocks (j+1) (j+1) ((i,j)::ac)
  in

  let block = Array.of_list (List.rev (find_blocks 0 0 [])) in
  let nb = Array.length block in

  (*
  for i=0 to nb-1 do
    printf "block: (%d,%d) " (fst block.(i)) (snd block.(i))
  done;
  print_newline();

  for a=0 to n do
    for b=0 to n-a do
      printf "g.(%d).(%d) = %f\n" a b (compg a b)
    done
  done;
  *)
  let e_internal_coverage (i,j) =
    sum (i+1) j (fun k ->
      let len = float (x.(k) - x.(k-1)) in
      len *. (comp (compg (k-i) (j+1-k)))
    )
  in

  let e_total_coverage =
    sum 0 (nb-1) (fun k -> e_internal_coverage block.(k))
  in

  let e_boundary_coverage =
    sum 1 (nb-1) (fun k ->
      let (i,j) = block.(k) in
      let (i',j') = block.(k-1) in
      let lp = comp (compg 0 (j-i+1)) in
      let rp = comp (compg (j'-i'+1) 0) in
      lp *. rp *. (float (min (x.(i) - x.(j')) (2*h))) +.
	(comp lp) *. rp *. (float h) +.
	lp *. (comp rp) *. (float h)
    )
  in

  let e_ends =
    let (i,j) = block.(0) in
    let e_left_end = (comp (compg 0 (j-i+1))) *. (float h) in
    let (i,j) = block.(nb-1) in
    let e_right_end = (comp (compg (j-i+1) 0)) *. (float h) in
    e_left_end +. e_right_end
  in

  let answer = e_total_coverage +. e_boundary_coverage +. e_ends in

  printf "%1.9f\n" answer


There is a straight snowy road, divided into n blocks. The blocks are numbered from 1 to n from left to right. If one moves from the i-th block to the (i + 1)-th block, he will leave a right footprint on the i-th block. Similarly, if one moves from the i-th block to the (i - 1)-th block, he will leave a left footprint on the i-th block. If there already is a footprint on the i-th block, the new footprint will cover the old one.  At the beginning, there were no footprints. Then polar bear Alice starts from the s-th block, makes a sequence of moves and ends in the t-th block. It is known that Alice never moves outside of the road. You are given the description of Alice's footprints. Your task is to find a pair of possible values of s, t by looking at the footprints.

The first line of the input contains integer n (3 ≤ n ≤ 1000). The second line contains the description of the road — the string that consists of n characters. Each character will be either "." (a block without footprint), or "L" (a block with a left footprint), "R" (a block with a right footprint). It's guaranteed that the given string contains at least one character not equal to ".". Also, the first and the last character will always be ".". It's guaranteed that a solution exists.

Print two space-separated integers — the values of s and t. If there are several possible solutions you can print any of them.

NoteThe first test sample is the one in the picture.

open String
open Printf
open Scanf
let solve : (string -> int * int) = function
      | str when (not (contains str 'L')) -> (index str 'R' + 1, rindex str 'R' + 2)
      | str when (not (contains str 'R')) -> (rindex str 'L' + 1, index str 'L')
      | str -> (index str 'R' + 1, rindex str 'R' + 1);;
let (s,t) = scanf "%d %s" (fun _ -> solve);;
Printf.printf "%d %d\n" s t

open String
open Printf
open Scanf
let solve : (string -> int * int) = function
      | str when not (contains str 'L') -> index str 'R' + 1, rindex str 'R' + 2
      | str when not (contains str 'R') -> rindex str 'L' + 1, index str 'L'
      | str -> index str 'R' + 1, rindex str 'R' + 1;;
let s,t = scanf "%d %s" (fun _ -> solve);;
printf "%d %d\n" s t


The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.Let's consider a rectangular image that is represented with a table of size n × m. The table elements are integers that specify the brightness of each pixel in the image.A feature also is a rectangular table of size n × m. Each cell of a feature is painted black or white.To calculate the value of the given feature at the given image, you must perform the following steps. First the table of the feature is put over the table of the image (without rotations or reflections), thus each pixel is entirely covered with either black or white cell. The value of a feature in the image is the value of W - B, where W is the total brightness of the pixels in the image, covered with white feature cells, and B is the total brightness of the pixels covered with black feature cells.Some examples of the most popular Haar features are given below.   Your task is to determine the number of operations that are required to calculate the feature by using the so-called prefix rectangles.A prefix rectangle is any rectangle on the image, the upper left corner of which coincides with the upper left corner of the image.You have a variable value, whose value is initially zero. In one operation you can count the sum of pixel values at any prefix rectangle, multiply it by any integer and add to variable value.You are given a feature. It is necessary to calculate the minimum number of operations required to calculate the values of this attribute at an arbitrary image. For a better understanding of the statement, read the explanation of the first sample.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — the number of rows and columns in the feature. Next n lines contain the description of the feature. Each line consists of m characters, the j-th character of the i-th line equals to "W", if this element of the feature is white and "B" if it is black.

Print a single number — the minimum number of operations that you need to make to calculate the value of the feature.

6 8
BBBBBBBB
BBBBBBBB
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW

NoteThe first sample corresponds to feature B, the one shown in the picture. The value of this feature in an image of size 6 × 8 equals to the difference of the total brightness of the pixels in the lower and upper half of the image. To calculate its value, perform the following two operations:  add the sum of pixels in the prefix rectangle with the lower right corner in the 6-th row and 8-th column with coefficient 1 to the variable value (the rectangle is indicated by a red frame);  add the number of pixels in the prefix rectangle with the lower right corner in the 3-rd row and 8-th column with coefficient  - 2 and variable value.  Thus, all the pixels in the lower three rows of the image will be included with factor 1, and all pixels in the upper three rows of the image will be included with factor 1 - 2 =  - 1, as required.

open Printf
open Scanf

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

  let count = ref 0 in

  let count_boundary (a,b) =
    if a = b then 0 else 1
  in

  let count_middle (a,b,c,d) =
    if a=b && c=d then 0
    else if a=c && b=d then 0
    else 1
  in

  for i=0 to n-1 do
    for j=0 to m-1 do
      count := !count + (
	if i=n-1 && j=m-1 then 1
	else if i=n-1 then count_boundary (board.(i).[j], board.(i).[j+1])
	else if j=m-1 then count_boundary (board.(i).[j], board.(i+1).[j])
	else count_middle (board.(i).[j], board.(i).[j+1], board.(i+1).[j], board.(i+1).[j+1])
      )
    done
  done;

  printf "%d\n" !count


You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations:  Write parity(a) to the end of a. For example, .  Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.

The first line contains the string a and the second line contains the string b (1 ≤ |a|, |b| ≤ 1000). Both strings contain only the characters "0" and "1". Here |x| denotes the length of the string x.

Print "YES" (without quotes) if it is possible to turn a into b, and "NO" (without quotes) otherwise.

NoteIn the first sample, the steps are as follows: 01011 → 1011 → 011 → 0110

open String
let a = read_line ();;
let b = read_line ();;
let count str c =
   let rec f p a =
      if p = length str
      then a
      else f (p+1) (a + if get str p = c then 1 else 0)
   in f 0 0;;
let n1a = count a '1';;
let n1a = n1a + n1a mod 2;;
let n1b = count b '1';;
if n1a >= n1b
then print_string "YES\n"
else print_string "NO\n"


There are $$$n$$$ pillars aligned in a row and numbered from $$$1$$$ to $$$n$$$.Initially each pillar contains exactly one disk. The $$$i$$$-th pillar contains a disk having radius $$$a_i$$$.You can move these disks from one pillar to another. You can take a disk from pillar $$$i$$$ and place it on top of pillar $$$j$$$ if all these conditions are met:  there is no other pillar between pillars $$$i$$$ and $$$j$$$. Formally, it means that $$$|i - j| = 1$$$;  pillar $$$i$$$ contains exactly one disk;  either pillar $$$j$$$ contains no disks, or the topmost disk on pillar $$$j$$$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $$$n$$$ disks on the same pillar simultaneously?

The first line contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of pillars. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_i$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the radius of the disk initially placed on the $$$i$$$-th pillar. All numbers $$$a_i$$$ are distinct.

Print YES if it is possible to place all the disks on the same pillar simultaneously, and NO otherwise. You may print each letter in any case (YES, yes, Yes will all be recognized as positive answer, NO, no and nO will all be recognized as negative answer).

NoteIn the first case it is possible to place all disks on pillar $$$3$$$ using the following sequence of actions:  take the disk with radius $$$3$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$1$$$ and place it on top of pillar $$$2$$$;  take the disk with radius $$$2$$$ from pillar $$$4$$$ and place it on top of pillar $$$3$$$;  take the disk with radius $$$1$$$ from pillar $$$2$$$ and place it on top of pillar $$$3$$$.

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

let solve n a =
  let rec go i = if i >= n then n else if a.(i) = n then i else go (i+1)
  in
  let ix = go 0 in
  let rec dec i d =
    if i < 0 || i >= n then true
    else if a.(i) > a.(i-d) then false
    else dec (i + d) d
  in dec (ix-1) (-1) && dec (ix+1) 1

let main () =
  let n = readInt () in
  let a = Array.init n (fun _ -> readInt ()) in
  print_endline (if solve n a then "YES" else "NO")

let () = main ()


Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

The first line of the input contains one integer, n (1 ≤ n ≤ 100 000). The next line contains n space separated integers given to Wet Shark. Each of these integers is in range from 1 to 109, inclusive.

Print the maximum possible even sum that can be obtained if we use some of the given integers.

NoteIn the first sample, we can simply take all three integers for a total sum of 6.In the second sample Wet Shark should take any four out of five integers 999 999 999.

let ( ++ ) = Int64.add
let ( %% ) = Int64.rem
let zero = Int64.zero
let two = Int64.of_int 2

let read () = Scanf.scanf "%d " (fun n -> n)
let read_l () = Scanf.scanf "%Ld " (fun n -> n)
let print int = Printf.printf "%Ld\n" int

let input () =
    let n = read () in
    let rec loop i even odd =
        if i < n
        then
            let int = read_l () in
            if int %% two = zero
            then
                loop (i + 1) (int :: even) odd
            else
                loop (i + 1) even (int :: odd)
        else
            (even, odd)
    in loop 0 [] []

let get_sum list =
    let l = List.length list in
    if l <= 1
    then
        zero
    else
        if l mod 2 = 0
        then
            List.fold_left (fun acc n -> acc ++ n) zero list
        else
            List.fold_left (fun acc n -> acc ++ n) zero (List.tl list)

let solve (even, odd)=
    let odd_sorted = List.sort (Pervasives.compare) odd in
    let sum_even = List.fold_left (fun acc n -> acc ++ n) zero even in
    let sum_odd = get_sum odd_sorted in
    sum_even ++ sum_odd

let () = print (solve (input ()))

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 rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

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 total = sum 0 (n-1) (fun i -> a.(i)) 0L in

  let inf = Int64.max_int in

  let is_odd x = x%% 2L = 1L in

  let min_odd = minf 0 (n-1) (fun i -> if is_odd a.(i) then a.(i) else inf) in

  let answer = if not (is_odd total) then total else total -- min_odd in

  printf "%Ld\n" answer


Given the integer $$$n$$$ — the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of $$$3$$$ platforms for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places respectively. The platform for the $$$1$$$-st place must be strictly higher than for the $$$2$$$-nd place, and the platform for the $$$2$$$-nd place must be strictly higher than for the $$$3$$$-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block).    Example pedestal of $$$n=11$$$ blocks: second place height equals $$$4$$$ blocks, first place height equals $$$5$$$ blocks, third place height equals $$$2$$$ blocks.Among all possible pedestals of $$$n$$$ blocks, deduce one such that the platform height for the $$$1$$$-st place minimum as possible. If there are several of them, output any of them.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case contains a single integer $$$n$$$ ($$$6 \le n \le 10^5$$$) — the total number of blocks for the pedestal. All $$$n$$$ blocks must be used. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$10^6$$$.

For each test case, output $$$3$$$ numbers $$$h_2, h_1, h_3$$$ — the platform heights for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places on a pedestal consisting of $$$n$$$ blocks ($$$h_1+h_2+h_3=n$$$, $$$0 < h_3 < h_2 < h_1$$$).  Among all possible pedestals, output the one for which the value of $$$h_1$$$ minimal. If there are several of them, output any of them.

NoteIn the first test case we can not get the height of the platform for the first place less than $$$5$$$, because if the height of the platform for the first place is not more than $$$4$$$, then we can use at most $$$4 + 3 + 2 = 9$$$ blocks. And we should use $$$11 = 4 + 5 + 2$$$ blocks. Therefore, the answer 4 5 2 fits. In the second set, the only suitable answer is: 2 3 1.

open String
open Printf

let read_ints() = Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp " +") (read_line())));;
let n = read_int();;

for i = 0 to (n - 1) do
    let num = read_int() and
        fi = ref 3 and
        se = ref 2 and
        th = ref 1 in
    let many = ((num - 6) / 3) and
        rest = ref((num - 6) mod 3)
        in
        fi := !fi + many;
        se := !se + many;
        th := !th + many;
        while !rest > 0 do
            if !rest > 0 then (
                fi := !fi + 1;
                rest := !rest - 1
            );
            if !rest > 0 then (
                se := !se + 1;
                rest := !rest - 1
            );
            if !rest > 0 then (
                th := !th + 1;
                rest := !rest - 1
            )
        done;
        print_int !se;
        print_string " ";
        print_int !fi;
        print_string " ";
        print_int !th;
        print_newline()
done

open String
open Printf

let read_ints() = Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp " +") (read_line())));;
let n = read_int();;

for i = 0 to (n - 1) do
    let num = read_int() and
        fi = ref 3 and
        se = ref 2 and
        th = ref 1 in
    let many = ((num - 6) / 3) and
        rest = ref((num - 6) mod 3)
        in
        fi := !fi + many;
        se := !se + many;
        th := !th + many;
        while !rest > 0 do
            if !rest > 0 then (
                fi := !fi + 1;
                rest := !rest - 1
            );
            if !rest > 0 then (
                se := !se + 1;
                rest := !rest - 1
            );
            if !rest > 0 then (
                th := !th + 1;
                rest := !rest - 1
            )
        done;
        printf "%d %d %d" !se !fi !th
done


You are given string s consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.The following definition of a regular bracket sequence is well-known, so you can be familiar with it.Let's define a regular bracket sequence (RBS). Empty string is RBS. Let s1 and s2 be a RBS then the strings <s1>s2, {s1}s2, [s1]s2, (s1)s2 are also RBS.For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.Determine the least number of replaces to make the string s RBS.

The only line contains a non empty string s, consisting of only opening and closing brackets of four kinds. The length of s does not exceed 106.

If it's impossible to get RBS from s print Impossible. Otherwise print the least number of replaces needed to get RBS from s.

open Printf

let rec over a b f k =
  if a >= b then k
  else over (a + 1) b f (f a k)

let group = function
  | '[' | ']' -> 0
  | '(' | ')' -> 1
  | '<' | '>' -> 2
  | '{' | '}' -> 3
  | _ -> assert false

let () =
  let s = input_line stdin in
  let x =
    over 0 (String.length s) (fun i x ->
        match s.[i], x with
        | _, None ->
          None
        | ('[' | '<' | '(' | '{'), Some (n, q) ->
          Some (n, group s.[i] :: q)
        | r, Some (n, []) ->
          None
        | r, Some (n, t :: ts) when group r = t ->
          Some (n, ts)
        | r, Some (n, t :: ts) when group r <> t ->
          Some ((n + 1), ts)
        | _ -> assert false
      ) (Some (0, []))
  in
  match x with
  | None -> printf "Impossible\n"
  | Some (_, _ :: _) -> printf "Impossible\n"
  | Some (n, []) -> printf "%d\n" n

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let n = String.length s in
  let a = Array.make n 0 in
  let pos = ref 0 in
  let push x =
    a.(!pos) <- x;
    incr pos
  in
  let res = ref 0 in
  let pop x =
    if !pos <= 0 then (
      Printf.printf "Impossible\n";
      exit 0;
    );
    if a.(!pos - 1) <> x
    then incr res;
    decr pos;
  in
    for i = 0 to n - 1 do
      let c = s.[i] in
	match c with
	  | '(' -> push 0
	  | '{' -> push 1
	  | '<' -> push 2
	  | '[' -> push 3
	  | ')' -> pop 0
	  | '}' -> pop 1
	  | '>' -> pop 2
	  | ']' -> pop 3
	  | _ -> assert false
    done;
    if !pos <> 0
    then Printf.printf "Impossible\n"
    else Printf.printf "%d\n" !res