Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers ti (1 ≤ ti ≤ 109), separated by spaces.

Print a single number — the maximum number of not disappointed people in the queue.

NoteValue 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.

open Num

let (|>) x f = f x
let ($) f g = fun x -> f (g x)

let solve l =
  let disappointed =
    l
    |> List.sort compare
    |> List.fold_left
         (fun (total, disappointed) time ->
            if time </ total
            then (total, disappointed + 1)
            else (total +/ time, disappointed))
         (num_of_int 0, 0)
    |> snd
  in
  List.length l - disappointed

let _ =
  ignore (read_int ());
  let l =
    read_line ()
    |> Str.split (Str.regexp " ")
    |> List.map (num_of_int $ int_of_string)
  in

  print_endline (string_of_int (solve l))

let rec f temps = function
	|t::q	-> if t<temps
			then f temps q
			else 1 + f (temps +. t) q
	| _	-> 0;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := (float i)::!l);
	done;
	Printf.printf "%d" (f 0. (List.sort compare !l));;

let (|>) x f = f x

let solve l =
  let disappointed =
    List.sort compare l
    |> List.fold_left
         (fun (total, disappointed) time ->
            if time < total
            then (total, disappointed + 1)
            else (total + time, disappointed))
         (0, 0)
    |> snd
  in
  List.length l - disappointed

let _ =
  ignore (read_int ());
  let l =
    read_line ()
    |> Str.split (Str.regexp " ")
    |> List.map int_of_string
  in

  print_endline (string_of_int (solve l))

let rec f temps = function
	|t::q	-> if t<temps
			then f temps q
			else 1 + f (temps + t) q
	| _	-> 0;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := i::!l);
	done;
	Printf.printf "%d" (f 0 (List.sort compare !l));;

let rec f decu pasdecu temps = function
	|t::q	-> if t<temps
			then f (t::decu) pasdecu temps q
			else f decu (t::pasdecu) (temps + t) q
	| _	-> (List.rev pasdecu) @ decu;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := i::!l);
	done;
	List.iter (fun i -> Printf.printf "%d " i) (f [] [] 0 (List.sort compare !l));;

let rec f decu pasdecu temps = function
	|t::q	-> if t<temps
			then f (t::decu) pasdecu temps q
			else f decu (t::pasdecu) (temps + t) q
	| _	-> List.length pasdecu;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := i::!l);
	done;
	Printf.printf "%d" (f [] [] 0 (List.sort compare !l));;


Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string $$$s = s_1 s_2 \dots s_{n}$$$ of length $$$n$$$ where each letter is either R, S or P.While initializing, the bot is choosing a starting index $$$pos$$$ ($$$1 \le pos \le n$$$), and then it can play any number of rounds. In the first round, he chooses "Rock", "Scissors" or "Paper" based on the value of $$$s_{pos}$$$:   if $$$s_{pos}$$$ is equal to R the bot chooses "Rock";  if $$$s_{pos}$$$ is equal to S the bot chooses "Scissors";  if $$$s_{pos}$$$ is equal to P the bot chooses "Paper"; In the second round, the bot's choice is based on the value of $$$s_{pos + 1}$$$. In the third round — on $$$s_{pos + 2}$$$ and so on. After $$$s_n$$$ the bot returns to $$$s_1$$$ and continues his game.You plan to play $$$n$$$ rounds and you've already figured out the string $$$s$$$ but still don't know what is the starting index $$$pos$$$. But since the bot's tactic is so boring, you've decided to find $$$n$$$ choices to each round to maximize the average number of wins.In other words, let's suggest your choices are $$$c_1 c_2 \dots c_n$$$ and if the bot starts from index $$$pos$$$ then you'll win in $$$win(pos)$$$ rounds. Find $$$c_1 c_2 \dots c_n$$$ such that $$$\frac{win(1) + win(2) + \dots + win(n)}{n}$$$ is maximum possible.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains string $$$s = s_1 s_2 \dots s_{n}$$$ ($$$1 \le n \le 2 \cdot 10^5$$$; $$$s_i \in \{\text{R}, \text{S}, \text{P}\}$$$) — the string of the bot. It's guaranteed that the total length of all strings in one test doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$n$$$ choices $$$c_1 c_2 \dots c_n$$$ to maximize the average number of wins. Print them in the same manner as the string $$$s$$$. If there are multiple optimal answers, print any of them.

NoteIn the first test case, the bot (wherever it starts) will always choose "Rock", so we can always choose "Paper". So, in any case, we will win all $$$n = 4$$$ rounds, so the average is also equal to $$$4$$$.In the second test case:   if bot will start from $$$pos = 1$$$, then $$$(s_1, c_1)$$$ is draw, $$$(s_2, c_2)$$$ is draw and $$$(s_3, c_3)$$$ is draw, so $$$win(1) = 0$$$;  if bot will start from $$$pos = 2$$$, then $$$(s_2, c_1)$$$ is win, $$$(s_3, c_2)$$$ is win and $$$(s_1, c_3)$$$ is win, so $$$win(2) = 3$$$;  if bot will start from $$$pos = 3$$$, then $$$(s_3, c_1)$$$ is lose, $$$(s_1, c_2)$$$ is lose and $$$(s_2, c_3)$$$ is lose, so $$$win(3) = 0$$$;  The average is equal to $$$\frac{0 + 3 + 0}{3} = 1$$$ and it can be proven that it's the maximum possible average.A picture from Wikipedia explaining "Rock paper scissors" game:

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
    let hist = Array.make 3 0 in
    for i=0 to n-1 do
      let x = match s.[i] with 'R' -> 0 | 'S' -> 1 | 'P' -> 2 | _ -> failwith "bad" in
      hist.(x) <- hist.(x) + 1
    done;

    let answer =
      if hist.(0) >= hist.(1) && hist.(0) >= hist.(2) then 'P'
      else if hist.(1) >= hist.(0) && hist.(1) >= hist.(2) then 'R'
      else 'S'
    in
    for i=1 to n do
      printf "%c" answer
    done;
    print_newline()
  done


When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.Find the length of the longest almost constant range.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Print a single number — the maximum length of an almost constant range of the given sequence.

NoteIn the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].

open Printf
open Scanf

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

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

  let equal_block_length n a =
    let rec loop i current_run best_run = if i=n then best_run
      else if a.(i-1) = a.(i) then
	let current_run = current_run+1 in
	let best_run = max best_run current_run in
	loop (i+1) current_run best_run
      else
	loop (i+1) 1 best_run
    in
    loop 1 1 1
  in

  let b = Array.init n (fun i -> a.(i)/2) in

  let c = Array.init n (fun i -> (a.(i)+1)/2) in

  let answer = max (equal_block_length n b) (equal_block_length n c) in

  printf "%d\n" answer


You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.

For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.

NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$.

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

let () =
  let t = read_int () in
  let ncompare a b : int =
    if a = b then
      0
    else if a < b then
      1
    else
      -1
  in
  let init n f =
    let rec init_aux acc = function
      | 0 -> acc
      | n -> init_aux ([f ()] @ acc) (n - 1)
    in init_aux [] n
  in
  let rec solve x a b =
    match a, b with
    | [], _ -> "YES"
    | _, [] -> "YES"
    | hd1 :: tl1,  hd2 :: tl2 ->
        if hd1 + hd2 > x then "NO" else solve x tl1 tl2
  in
  for i = 1 to t do
    let n = read_int () in
    let x = read_int () in
    let a = List.sort compare (init n read_int) in
    let b = List.sort ncompare (init n read_int) in
    Printf.printf "%s\n" (solve x a b)
  done

open Printf
open Scanf

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

let rec read_ints n =
  match n with
  | 0 -> []
  | x -> read_int () :: (read_ints (n-1))

(* let read_ints () =
 *   let line = read_line () in
 *   let ints = Str.split (Str.regexp " *") line in
 *   List.map int_of_string ints *)

let rec print_list = function
    [] -> ()
  | e::l -> print_int e ; print_string " " ; print_list l

let solve () =
  let n = read_int () in
  let x = read_int () in
  let a = List.sort compare (read_ints n) in
  let b = List.sort compare (read_ints n) in
  let c = List.map2 (+) a (List.rev b) in
  if
    (List.fold_left (fun m x -> if m >= x then m else x) (-1) c <= x)
  then
    print_endline "Yes"
  else print_endline "No"

let () =
  let x = read_int () in
  let rec loop n =
    match n with
    | 0 -> ()
    | x -> solve (); loop (n-1) in
  loop x


Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi.Vasya wonders what the numbers ai could be like. Of all the possible options he likes the one sequence with the minimum possible last number an. Help Vasya restore the initial sequence.It is guaranteed that such a sequence always exists.

The first line contains a single integer number n (1 ≤ n ≤ 300). Next n lines contain integer numbers b1, ..., bn  — the required sums of digits. All bi belong to the range 1 ≤ bi ≤ 300.

Print n integer numbers, one per line — the correct option for numbers ai, in order of following in sequence. The sequence should be strictly increasing. The sum of digits of the i-th number should be equal to bi.  If there are multiple sequences with least possible number an, print any of them. Print the numbers without leading zeroes.

open Printf
open Scanf

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

  (* fill in b.(0)...b.(i-1) so that it achieves the given sum with minimum value *)
  (* returns true it it works, false if it's impossible *)
  let fill_in b i sum =
    if sum<0 then false else
      let rec loop j remain =
	if i=j then remain=0 else
	  let d = min 9 remain in
	  b.(j) <- d;
	  loop (j+1) (remain - d)
      in

      loop 0 sum
  in

  (* return the smallest number > b whose digit sum is gs (goal sum) *)
  (* b is an array, where b.(0) is the 1s digit, etc *)
  (* sb is the sum of the digits in the b array *)
  let f gs b sb =
    let b' = Array.copy b in
    let rec scan i sum =  (* work on increasing position i.  sum=desired total for digits i,i-1...0 *)
      if sum<0 then scan (i+1) (sum+b.(i+1)) else
	let rec loop d = (* d=digit we're trying in position i. *)
	  if d>9 then false else (
	    b'.(i) <- d;
	    if fill_in b' i (sum-d) then true else loop (d+1)
	  )
	in

	if loop (b.(i)+1) then () else scan (i+1) (sum+b.(i+1))
    in

    scan 0 (gs-(sb-b.(0)));
    b'
  in

  let max_length = n + (300/9) + 2 in  (* maximum number of digits possible *)

  let rec loop i b = if i=n then () else
      let sb = if i=0 then 0 else sums.(i-1) in
      let b = f sums.(i) b sb in
      let rec ploop j front =
	if j < 0 then ()
	else if b.(j)=0 && front then ploop (j-1) true else (
	  printf "%d" b.(j);
	  ploop (j-1) false
	)
      in
      ploop (max_length-1) true;
      print_newline();
      loop (i+1) b
  in

  loop 0 (Array.make max_length 0)


n fish, numbered from 1 to n, live in a lake. Every day right one pair of fish meet, and the probability of each other pair meeting is the same. If two fish with indexes i and j meet, the first will eat up the second with the probability aij, and the second will eat up the first with the probability aji = 1 - aij. The described process goes on until there are at least two fish in the lake. For each fish find out the probability that it will survive to be the last in the lake.

The first line contains integer n (1 ≤ n ≤ 18) — the amount of fish in the lake. Then there follow n lines with n real numbers each — matrix a. aij (0 ≤ aij ≤ 1) — the probability that fish with index i eats up fish with index j. It's guaranteed that the main diagonal contains zeros only, and for other elements the following is true: aij = 1 - aji. All real numbers are given with not more than 6 characters after the decimal point.

Output n space-separated real numbers accurate to not less than 6 decimal places. Number with index i should be equal to the probability that fish with index i will survive to be the last in the lake.

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

let () =
  let n = read_int 0 in
  let a = Array.make_matrix n n 0.0 in
  for i = 0 to n-1 do
    for j = 0 to n-1 do
      a.(i).(j) <- read_float 0
    done
  done;
  let s = Array.make (1 lsl n) 0.0 in
  s.(1 lsl n - 1) <- 1.0;
  for i = 1 lsl n - 1 downto 1 do
    let pop = ref 0 in
    for j = 0 to n-1 do
      if i land 1 lsl j <> 0 then
        incr pop;
    done;
    for j = 0 to n-1 do
      if i land 1 lsl j <> 0 then
        for k = j+1 to n-1 do
          if i land 1 lsl k <> 0 then (
            let ij = i lxor 1 lsl k in
            let ik = i lxor 1 lsl j in
            let t = s.(i) /. ((!pop-1) * !pop / 2 |> float_of_int) in
            s.(ij) <- s.(ij) +. t *. a.(j).(k);
            s.(ik) <- s.(ik) +. t *. a.(k).(j)
          )
        done
    done
  done;
  for i = 0 to n-1 do
    Printf.printf "%f%c" s.(1 lsl i) (if i = n-1 then '\n' else ' ')
  done


Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which  two planks of length at least $$$k+1$$$ — the base of the ladder;  $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps.   You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.

NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:

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

let solve n a =
  let (Some x, Some y) = Array.fold_left (fun (x, y) z -> if Some z > x then (Some z, x) else if Some z > y then (x, Some z) else (x, y)) (None, None) a in
  min (n - 2) (y - 1)

let main () =
  let t = readInt () in
  for i=0 to t-1 do
    let n = readInt () in
    let a = Array.init n (fun _ -> readInt ()) in
    Printf.printf "%d\n" (solve n a)
  done

let () = main ()


The Little Elephant loves sortings.He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ≤ r.Help the Little Elephant find the minimum number of moves he needs to convert array a to an arbitrary array sorted in the non-decreasing order. Array a, consisting of n elements, is sorted in the non-decreasing order if for any i (1 ≤ i < n) ai ≤ ai + 1 holds.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of array a. The next line contains n integers, separated by single spaces — array a (1 ≤ ai ≤ 109). The array elements are listed in the line in the order of their index's increasing.

In a single line print a single integer — the answer to the problem. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the array is already sorted in the non-decreasing order, so the answer is 0.In the second sample you need to perform two operations: first increase numbers from second to third (after that the array will be: [3, 3, 2]), and second increase only the last element (the array will be: [3, 3, 3]).In the third sample you should make at least 6 steps. The possible sequence of the operations is: (2; 3), (2; 3), (2; 3), (3; 3), (3; 3), (3; 3). After that the array converts to [7, 7, 7, 47].

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let b = ref 0 in
  let s = ref Int64.zero in
  for i = 0 to n - 1 do
    let a = Scanf.scanf " %d" (fun x -> x) in
    if !b > a then s := Int64.add !s (Int64.of_int (!b - a));
    b := a
  done;
  print_string (Int64.to_string !s)
;;

#load "str.cma";;

let rec iter ls cur height =
  match ls with
	  [] -> cur
	| h::ls' ->
	  if height <= (Int64.add h cur) then iter ls' cur (Int64.add h cur)
	  else iter ls' (Int64.sub height h) height ;;

let solve ls =
  iter (List.tl ls) 0L (List.hd ls);;

let get_input () =
  let n = int_of_string (read_line ()) and
	  ls = List.map (fun x -> Int64.of_int (int_of_string x))
	(Str.split (Str.regexp "[ \t]+") (read_line ())) in
  (n, ls);;

let (n, ls) = get_input () in
if n == 1 then Printf.printf "0\n"
else Printf.printf "%Ld\n" (solve ls)

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let b = ref 0 in
  let s = ref 0 in
  for i = 0 to n - 1 do
    let a = Scanf.scanf " %d" (fun x -> x) in
    s := !s + max 0 (!b - a);
    b := a
  done;
  print_int !s
;;

#load "str.cma";;

let rec iter ls cur height =
  match ls with
	  [] -> cur
	| h::ls' ->
	  if height <= (h + cur) then iter ls' cur (h + cur)
	  else iter ls' ((height - h - cur) + cur) height ;;

let solve ls =
  iter (List.tl ls) 0 (List.hd ls);;

let get_input () =
  let n = int_of_string (read_line ()) and
	  ls = List.map int_of_string (Str.split (Str.regexp "[ \t]+") (read_line ())) in
  (n, ls);;

let (n, ls) = get_input () in
if n == 1 then Printf.printf "0\n"
else Printf.printf "%d\n" (solve ls)

#load "str.cma";;

let rec iter ls cur height =
  match ls with
	  [] -> cur
	| h::ls' ->
	  if height <= (h + cur) then iter ls' cur (h + cur)
	  else iter ls' ((height - h - cur) + cur) height ;;

let solve ls =
  iter (List.tl ls) 0 (List.hd ls);;

let get_input () =
  let n = int_of_string (read_line ()) and
	  ls = List.map int_of_string (Str.split (Str.regexp "[ \t]+") (read_line ())) in
  (n, ls);;

let (n, ls) = get_input () in
if n == 1 then Printf.printf "1\n"
else Printf.printf "%d\n" (solve ls)


You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can participate in no more than one replacing operation.Your task is to perform such sequence of replacements, that the given number a gets maximum value. You are allowed to use not all elements from s.

The first line contains positive integer a. Its length n is positive and doesn't exceed 105. The second line contains sequence of digits s. Its length m is positive and doesn't exceed 105. The digits in the sequence s are written consecutively without any separators. The given number a doesn't contain leading zeroes.

Print the maximum value that can be obtained from a after a series of replacements. You are allowed to use not all elements from s. The printed number shouldn't contain any leading zeroes.

open Array;;
open Char;;
let (|>) x f = f x
let identity x = x

let f _ = Scanf.scanf "%s\n" (fun s -> init (String.length s) (fun i-> s.[i]))
let fold_right m f a =
   let rec fold_ i acc =
                if i>=0 && acc < m
                then fold_ (i-1) (f a.(i) acc)
                else  acc
   in fold_ (length a - 1)
let main () =
  let acc = Scanf.scanf "%s\n" identity in
  let s = f () in
  let y a =
        let rec y' i =
                if i >= String.length acc
                then i
                else if compare a acc.[i] > 0
                     then (acc.[i]<-a; i)
                     else y' (i+1)
        in y'
  in
     fast_sort compare s;
     fold_right (String.length acc) y s 0;
     print_string acc
  ;;
main()

open Array;;
open Char;;
let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readInStr _ = Scanf.scanf "%d " identity
let readIntLn _ = Scanf.scanf "%d\n" identity

let f _ = Scanf.scanf "%s\n" (fun s -> init (String.length s) (fun i-> s.[i]))
let y s (acc, i) a =
     if i >= 0 && Char.compare s.(i) a > 0
     then (Printf.printf "%s " acc; (acc ^ (escaped s.(i)) , i-1))
     else (acc ^ (escaped a) , i)

let main () =
  let a = f () in
  let s = f () in
     fast_sort Char.compare s;
     fold_left (y s) ("", length s - 1) a |>fst|>print_string
  ;;
main()

open Array;;

let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readInStr _ = Scanf.scanf "%d " identity
let readIntLn _ = Scanf.scanf "%d\n" identity

let f _ = Scanf.scanf "%s\n" (fun s -> init (String.length s) (fun i-> s.[i]))
let y s (acc, i) a =
     if i >= 0 && Char.compare s.(i) a > 0
     then  (acc*10 + (Char.code s.(i)) - 48, i-1)
     else (acc*10 + (Char.code a) - 48, i)

let main () =
  let a = f () in
  let s = f () in
     fast_sort Char.compare s;
     fold_left (y s) (0, length s - 1) a |>fst|>print_int
  ;;
main()

open Array;;
open Char;;
let (|>) x f = f x
let identity x = x

let f _ = Scanf.scanf "%s\n" (fun s -> init (String.length s) (fun i-> s.[i]))
let fold_right m f a =
   let rec fold_ i acc =
                if i>0 && acc < m
                then fold_ (i-1) (f a.(i) acc)
                else  acc
   in fold_ (length a - 1)
let main () =
  let acc = Scanf.scanf "%s\n" identity in
  let s = f () in
  let y a =
        let rec y' i =
                if i >= String.length acc
                then i
                else if compare a acc.[i] > 0
                     then (acc.[i]<-a; i)
                     else y' (i+1)
        in y'
  in
     fast_sort compare s;
     fold_right (String.length acc) y s 0;
     print_string acc
  ;;
main()


Marin wants you to count number of permutations that are beautiful. A beautiful permutation of length $$$n$$$ is a permutation that has the following property: $$$$$$ \gcd (1 \cdot p_1, \, 2 \cdot p_2, \, \dots, \, n \cdot p_n) > 1, $$$$$$ where $$$\gcd$$$ is the greatest common divisor.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n \le 10^3$$$).

For each test case, print one integer — number of beautiful permutations. Because the answer can be very big, please print the answer modulo $$$998\,244\,353$$$.

NoteIn first test case, we only have one permutation which is $$$[1]$$$ but it is not beautiful because $$$\gcd(1 \cdot 1) = 1$$$.In second test case, we only have one beautiful permutation which is $$$[2, 1]$$$ because $$$\gcd(1 \cdot 2, 2 \cdot 1) = 2$$$.

(* https://codeforces.com/problemset/problem/1658/B *)
open Printf
open Scanf
module LL = Int64

let maxn = 1001
let q = 998244353L
let ( %% ) x y = LL.sub x ( LL.mul y (LL.div x y) )
let ( ** ) x y = LL.mul x y
let ( // ) x y = LL.div x y
let (!) x = LL.of_int x

let fac = Array.make maxn 1L;;
for i = 1 to maxn-1 do
    fac.(i) <- !i ** fac.(i-1) %% q
done

let solve n =
    if n mod 2 = 1
        then 0L
    else
        let m = n/2 in
        fac.(m) ** fac.(m) %% q

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

let modul x = Int64.sub x (Int64.mul (Int64.div x (Int64.of_int 998244353)) (Int64.of_int 998244353))

let rec  test x = match x with
  |2 -> Int64.of_int 1
  |r when r mod 2 = 0 -> let t = r/2 in
      modul(Int64.mul (modul (Int64.mul (Int64.of_int(t)) (Int64.of_int(t))))  (test (x-2)))
  |_ -> Int64.zero
;;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let num = int_of_string(input_line stdin) in
  print_endline (Int64.to_string (test num))
done;
;;

(* https://codeforces.com/problemset/problem/1658/B *)
open Printf
open Scanf

let maxn = 100
let q = 998244353

let fac : int array = Array.make 1001 1;;
for i = 1 to 1000 do
    fac.(i) <- i * fac.(i-1) mod q
done

let solve n =
    if n mod 2 = 1
        then 0
    else
        let m = n/2 in
        fac.(m) * fac.(m) mod q

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

(* https://codeforces.com/problemset/problem/1658/B *)
open Printf
open Scanf

let maxn = 100
let q = 998244353

let fac : int array = Array.make 1001 1;;
for i = 1 to 1000 do
    fac.(i) <- i * fac.(i-1) mod q
done

let solve n =
    if n mod 2 = 1
        then 0
    else
        let m = n/2 in
        fac.(m) * fac.(m) mod q

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


Recently Vova found $$$n$$$ candy wrappers. He remembers that he bought $$$x$$$ candies during the first day, $$$2x$$$ candies during the second day, $$$4x$$$ candies during the third day, $$$\dots$$$, $$$2^{k-1} x$$$ candies during the $$$k$$$-th day. But there is an issue: Vova remembers neither $$$x$$$ nor $$$k$$$ but he is sure that $$$x$$$ and $$$k$$$ are positive integers and $$$k > 1$$$.Vova will be satisfied if you tell him any positive integer $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$. It is guaranteed that at least one solution exists. Note that $$$k > 1$$$.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$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 10^9$$$) — the number of candy wrappers Vova found. It is guaranteed that there is some positive integer $$$x$$$ and integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

Print one integer — any positive integer value of $$$x$$$ so there is an integer $$$k>1$$$ that $$$x + 2x + 4x + \dots + 2^{k-1} x = n$$$.

NoteIn the first test case of the example, one of the possible answers is $$$x=1, k=2$$$. Then $$$1 \cdot 1 + 2 \cdot 1$$$ equals $$$n=3$$$.In the second test case of the example, one of the possible answers is $$$x=2, k=2$$$. Then $$$1 \cdot 2 + 2 \cdot 2$$$ equals $$$n=6$$$.In the third test case of the example, one of the possible answers is $$$x=1, k=3$$$. Then $$$1 \cdot 1 + 2 \cdot 1 + 4 \cdot 1$$$ equals $$$n=7$$$.In the fourth test case of the example, one of the possible answers is $$$x=7, k=2$$$. Then $$$1 \cdot 7 + 2 \cdot 7$$$ equals $$$n=21$$$.In the fifth test case of the example, one of the possible answers is $$$x=4, k=3$$$. Then $$$1 \cdot 4 + 2 \cdot 4 + 4 \cdot 4$$$ equals $$$n=28$$$.

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

let get n =
  let rec test k =
    let tmp = (1 lsl k) - 1 in
    if n mod tmp = 0 then n / tmp
    else test (k + 1) in
  test 2
;;

let _ =
  let t = scan_int () in
  for i = 1 to t do
    Printf.printf "%d\n" (get (scan_int ()))
  done
;;

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

let rec pow x = function
| 0 -> 1
| n -> x * pow x (n - 1);;

let rec solve n k =
   if n mod ((pow 2 k) - 1) = 0 then
      n / ((pow 2 k) - 1)
   else
      solve n (k + 1)
;;

for iTest = 1 to nbTests
do
   let nbBonbons = Scanf.scanf " %d" (fun x -> x) in

   print_int (solve nbBonbons 2);
   print_newline ()
done;;


DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b denotes taking a remainder after division a by b.However, each bucket can contain no more than one element. If DZY wants to insert an number into a bucket which is already filled, we say a "conflict" happens. Suppose the first conflict happens right after the i-th insertion, you should output i. If no conflict happens, just output -1.

The first line contains two integers, p and n (2 ≤ p, n ≤ 300). Then n lines follow. The i-th of them contains an integer xi (0 ≤ xi ≤ 109).

Output a single integer — the answer to the problem.

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

let solve p n arr =
  let htbl = Array.create p false in
  try
    for i = 0 to n - 1 do
      let h = arr.(i) mod p in
      match htbl.(h) with
      | false -> htbl.(h) <- true
      | true -> Printf.printf "%d\n" @@ i + 1; raise Exit
    done;
    Printf.printf "-1\n";
  with
  | Exit -> ()
;;

let () =
  Scanf.scanf "%d %d " (fun p n ->
    let arr = Array.create n 0 in
    for i = 0 to n - 1 do
      Scanf.scanf "%d " (fun x -> arr.(i) <- x);
    done;
    solve p n arr)
;;

(**D. The Child and Sequence*)

open Scanf;;
open Num;;
open Printf;;

let p,n = Scanf.bscanf Scanf.Scanning.stdin "%d %d " ( fun x y -> x,y );;

let hashv = Array.create p 0;;

exception BreakLoop;;

let j = ref 0;;
let rslt = ref (-1);;
try
  for i = 1 to n do
    j := !j + 1;
    let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
    let y = x mod p in
    match hashv.(y) with
    | 0 -> hashv.(y) <- 1
    | 1 -> raise BreakLoop
  done;
with  BreakLoop -> rslt := !j;;

printf "%d\n" !rslt;;


Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities numbered a1, a2, ..., ak.Unforunately the law of the country Masha lives in prohibits opening bakery in any of the cities which has storage located in it. She can open it only in one of another n - k cities, and, of course, flour delivery should be paid — for every kilometer of path between storage and bakery Masha should pay 1 ruble.Formally, Masha will pay x roubles, if she will open the bakery in some city b (ai ≠ b for every 1 ≤ i ≤ k) and choose a storage in some city s (s = aj for some 1 ≤ j ≤ k) and b and s are connected by some path of roads of summary length x (if there are more than one path, Masha is able to choose which of them should be used).Masha is very thrifty and rational. She is interested in a city, where she can open her bakery (and choose one of k storages and one of the paths between city with bakery and city with storage) and pay minimum possible amount of rubles for flour delivery. Please help Masha find this amount.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 105, 0 ≤ k ≤ n) — the number of cities in country Masha lives in, the number of roads between them and the number of flour storages respectively. Then m lines follow. Each of them contains three integers u, v and l (1 ≤ u, v ≤ n, 1 ≤ l ≤ 109, u ≠ v) meaning that there is a road between cities u and v of length of l kilometers . If k > 0, then the last line of the input contains k distinct integers a1, a2, ..., ak (1 ≤ ai ≤ n) — the number of cities having flour storage located in. If k = 0 then this line is not presented in the input.

Print the minimum possible amount of rubles Masha should pay for flour delivery in the only line. If the bakery can not be opened (while satisfying conditions) in any of the n cities, print  - 1 in the only line.

NoteImage illustrates the first sample case. Cities with storage located in and the road representing the answer are darkened.

open Scanf

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

type path = {
    start: int;
    stop: int;
    distance: int64;
}

let inf = 2000000000L

let find_nearest path_arr stops_arr =
    Array.fold_left (fun acc ele ->
        if stops_arr.(ele.start) != stops_arr.(ele.stop) && ele.distance < acc
        then ele.distance
        else acc) inf path_arr

let () =
    let n = read_int () in
    let m = read_int () in
    let k = read_int () in
    let data_arr = Array.init m (fun _ ->
        let start = read_int () in
        let stop = read_int () in
        let distance = read_int64 () in
        {start; stop; distance}
    ) in
    let stops_arr = Array.make (n+1) 0 in
    for i = 1 to k do
        let index = read_int () in
        stops_arr.(index) <- 1
    done;
    let v = find_nearest data_arr stops_arr in
    if v = inf then print_int (-1) else Printf.printf "%Ld" v


A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.

The first input line contains two integers n and k (1 ≤ n ≤ 5·105; 2 ≤ k ≤ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.

Print a single integer — the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.

open Scanf;;
open Printf;;
open Str;;

let split_by_space = split (regexp " +")

let rec head n ls =
  if n < 0 then invalid_arg "head : passed negative integer"
  else
    match (n, ls) with
      (0, _) -> []
    | (n, []) -> failwith "head : list is too short"
    | (n, x::xs) -> x :: (head (n - 1) xs)

let rec tail n ls =
  if n < 0 then invalid_arg "tail : passed negative integer"
  else
    match (n, ls) with
      (0, ls) -> ls
    | (n, []) -> failwith "tail : list is too short"
    | (n, x::xs) -> tail (n - 1) xs

module UF = struct
  type t = int array

  let make n = Array.make n (-1)

  let rec root x uf =
    if uf.(x) < 0 then x
    else (uf.(x) <- root uf.(x) uf; uf.(x))

  let union_set x y uf =
    let x = root x uf and
        y = root y uf in
    begin
      if x != y then
        let x, y = if uf.(y) < uf.(x) then y, x else x, y in
        begin
          uf.(x) <- uf.(x) + uf.(y);
          uf.(y) <- x
        end
    end;
    x != y

  let find_set x y uf = root x uf = root y uf

  let size x uf = - uf.(x)
end

let input () =
  let (n, k) = scanf "%d %d " (fun x y -> (x, y)) in
  let row = scanf "%s " (fun x -> x) in
  (n, k, row)

exception Exit of char
let get_other a b k =
  let a_code = Char.code 'A' in
  let ac = Char.code a - a_code and
      bc = Char.code b - a_code in
  try
    for i = 0 to k - 1 do
      if i <> ac && i <> bc then begin
        raise (Exit (Char.chr (i + a_code)))
      end
    done;
    '_'
  with
    Exit c -> c

type t = Left of int | Right of int

let solve (n, k, row) =
  if String.length row = 1 then
    (0, row)
  else if String.length row = 2 then begin
    let cnt = ref 0 in
    if row.[0] = row.[1] then begin
      row.[0] <- Char.chr ((Char.code (row.[1]) - Char.code 'A' + 1) mod k +
                             Char.code 'A');
      cnt := 1;
    end;
    (!cnt, row)
  end
  else if k > 2 then begin
    let cnt = ref 0 in
    for i = 1 to String.length row - 2 do
      if row.[i - 1] = row.[i] then begin
        row.[i] <- get_other row.[i - 1] row.[i + 1] k;
        cnt := !cnt + 1
      end
    done;
    let c1 = row.[String.length row - 2] and
        c2 = row.[String.length row - 1] in
    if c1 = c2 then begin
      row.[String.length row - 1] <-
        Char.chr (((Char.code c1 - Char.code 'A') + 1) mod k + Char.code 'A');
      cnt := !cnt + 1
    end;
    (!cnt, row)
  end
  else
    let count row b =
      let cnt = ref 0 in
      for i = 0 to String.length row - 1 do
      match (if b then i mod 2 else (i + 1) mod 2) with
        0 -> if row.[i] = 'B' then begin
          row.[i] <- 'A';
          cnt := !cnt + 1
        end
      | 1 -> if row.[i] = 'A' then begin
          row.[i] <- 'B';
          cnt := !cnt + 1
      end
      done;
      (!cnt, row) in
    let crow = String.copy row in
    let (cnt, row) = count row true in
    let (ccnt, crow) = count crow false in
    if cnt < ccnt then
      (cnt, row)
    else
      (ccnt, crow)
let () =
  let inp = input () in
  let (n, res) = solve inp in
  printf "%d\n%s\n" n res


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000). The following line contains a binary string of length n representing Kevin's results on the USAICO.

Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

NoteIn the first sample, Kevin can flip the bolded substring '10000011' and turn his string into '10011011', which has an alternating subsequence of length 5: '10011011'.In the second sample, Kevin can flip the entire string and still have the same score.

open Scanf

let read_int () = scanf " %d" (fun x -> x)
let read_string () = scanf " %s" (fun x -> x)
let n = read_int ()
let s = read_string ()

let longest_seq s =
    let last = ref '2'
    and cnt = ref 0 in
    begin
        for i = 0 to n - 1 do
            if s.[i] <> !last then
                begin
                    incr cnt;
                    last := s.[i]
                end
        done;
        !cnt
    end

let res = min n (longest_seq s + 2)
let _ = print_int res

open Printf;;
open Scanf;;

let n = read_int();;
let s = input_line stdin;;
let dp0 = Array.make (n+1) 0;;
let dp1 = Array.make (n+1) 0;;
let dp2 = Array.make (n+1) 0;;
for i=1 to n-1 do
    let aux1 = if s.[i]<>s.[i-1] then 1 + dp1.(i-1) else dp1.(i-1)
    and aux2 = if s.[i]<>s.[i-1] then dp0.(i-1) else 1 + dp0.(i-1)
    and aux3 = if s.[i]<>s.[i-1] then 1 + dp2.(i-1) else dp2.(i-1)
    and aux4 = if s.[i]<>s.[i-1] then dp1.(i-1) else 1 + dp1.(i-1)
    in  let res1 = max aux1 aux2
        and res2 = max aux3 aux4 in
    dp0.(i) <- if s.[i]<>s.[i-1] then 1 + dp0.(i-1) else dp0.(i-1);
    dp1.(i) <- res1;
    dp2.(i) <- res2;
done;;
printf "%d" (1 + max dp0.(n-1) (max dp1.(n-1) dp2.(n-1)));;

let n = read_int()
and s = input_line stdin;;

let rec solve i =
if (i=0) then (0,0,0) else
begin
    let (r0,r1,r2) = solve (i-1)
    and ib b = if(b) then 1 else 0 in
    (ib(s.[i]<>s.[i-1]) + r0,
    max (ib(s.[i]<>s.[i-1]) + r1) (ib(not(s.[i]<>s.[i-1])) + r0),
    max (ib(s.[i]<>s.[i-1]) + r2) (ib(not(s.[i]<>s.[i-1])) + r1))
end;;

let (a,b,c) = solve(n-1) in
Printf.printf "%d" (1 + max a (max b c));;

let n = read_int();;
let s = input_line stdin;;
let dp = Array.make_matrix (n+1) 3 0;;

let rec solve i =
if (i=0) then (0,0,0) else
begin
    let (r0,r1,r2) = solve (i-1)
    and ib b = if(b) then 1 else 0 in
    (ib(s.[i]<>s.[i-1]) + r0,
    max (ib(s.[i]<>s.[i-1]) + r1) (ib(not(s.[i]<>s.[i-1])) + r0),
    max (ib(s.[i]<>s.[i-1]) + r2) (ib(not(s.[i]<>s.[i-1])) + r1))
end;;

let (a,b,c) = solve(n-1);;
Printf.printf "%d" (1 + max a (max b c));;

open Printf;;
open Scanf;;

let n = read_int();;
let s = input_line stdin;;
let dp = Array.make_matrix (n+1) 3 0;;
for i=1 to n-1 do
    let aux1 = if s.[i]<>s.[i-1] then 1 + dp.(i-1).(1) else dp.(i-1).(1)
    and aux2 = if s.[i]<>s.[i-1] then dp.(i-1).(0) else 1 + dp.(i-1).(0)
    and aux3 = if s.[i]<>s.[i-1] then 1 + dp.(i-1).(2) else dp.(i-1).(2)
    and aux4 = if s.[i]<>s.[i-1] then dp.(i-1).(1) else 1 + dp.(i-1).(1)
    in  let res1 = max aux1 aux2
        and res2 = max aux3 aux4 in
    dp.(i).(0) <- if s.[i]<>s.[i-1] then 1 + dp.(i-1).(0) else dp.(i-1).(0);
    dp.(i).(1) <- res1;
    dp.(i).(2) <- res2;
done;;
printf "%d" (1 + max dp.(n-1).(0) (max dp.(n-1).(1) dp.(n-1).(2)));;

open Printf;;
open Scanf;;

let bi i = if(i=0) then false else true;;
let ib b = if(b) then 1 else 0;;

let n = read_int();;
let s = input_line stdin;;
let dp = Array.make_matrix (n+1) 3 0;;

for i=1 to n-1 do
    let aux1 = ib(s.[i]<>s.[i-1]) + dp.(i-1).(1)
    and aux2 = ib(not(s.[i]<>s.[i-1])) + dp.(i-1).(0)
    and aux3 = ib(s.[i]<>s.[i-1]) + dp.(i-1).(2)
    and aux4 = ib(not(s.[i]<>s.[i-1])) + dp.(i-1).(1)
    in  let res1 = max aux1 aux2
        and res2 = max aux3 aux4 in
    dp.(i).(0) <- ib(s.[i]<>s.[i-1]) + dp.(i-1).(0);
    dp.(i).(1) <- res1;
    dp.(i).(2) <- res2;
done;;
printf "%d" (1 + max dp.(n-1).(0) (max dp.(n-1).(1) dp.(n-1).(2)));;

let score_without w =
    let a = ref (w.[0]) and res = ref 1 in
         for i = 1 to String.length w - 1 do
             if w.[i] <> !a
                 then (incr res; a := w.[i]);
         done;
    !res

let score w =
    let l = String.length w and s = score_without w in
         s + min 2 (l - s)

let main () =
    let w = Scanf.scanf "%d %s" (fun _ w -> w) in
        Printf.printf "%d" (score w);;

main ();;

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

let () =
  let n = read_int() in
  let s = read_string() in

  let k = (* alternation length *)
    let rec loop prev i ac = if i=n then ac
      else if s.[i] = prev
      then loop prev (i+1) ac
      else loop s.[i] (i+1) (ac+1)
    in
    loop 'x' 0 0
  in

  let answer =
    if n=k then n
    else if n=k+1 then n
    else if n >= k+2 then k+2
    else failwith "impossible"
  in

  printf "%d\n" answer

open Printf;;
open Scanf;;

let n = read_int();;
let s = input_line stdin;;
let dp0 = Array.make (n+1) 0;;
let dp1 = Array.make (n+1) 0;;
let dp2 = Array.make (n+1) 0;;
for i=1 to n-1 do
    let aux1 = if s.[i]<>s.[i-1] then 1 + dp1.(i-1) else dp1.(i-1)
    and aux2 = if s.[i]<>s.[i-1] then dp0.(i-1) else 1 + dp0.(i-1)
    and aux3 = if s.[i]<>s.[i-1] then 1 + dp2.(i-1) else dp2.(i-1)
    and aux4 = if s.[i]<>s.[i-1] then dp1.(i-1) else 1 + dp1.(i-1)
    in  let res1 = max aux1 aux2
        and res2 = max aux3 aux4 in
    dp0.(i) <- if s.[i]<>s.[i-1] then 1 + dp0.(i-1) else dp0.(i-1);
    dp1.(i) <- res1;
    dp2.(i) <- res2;
done;;
printf "%d" (max dp0.(n-1) (max dp1.(n-1) dp2.(n-1)));;


Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarpus has already accidentally removed the user IDs corresponding to the requests from the database. Thus, it is now impossible to determine whether any two requests are made by the same person or by different people.But wait, something is still known, because that day a record was achieved — M simultaneous users online! In addition, Polycarpus believes that if a user made a request at second s, then he was online for T seconds after that, that is, at seconds s, s + 1, s + 2, ..., s + T - 1. So, the user's time online can be calculated as the union of time intervals of the form [s, s + T - 1] over all times s of requests from him.Guided by these thoughts, Polycarpus wants to assign a user ID to each request so that:  the number of different users online did not exceed M at any moment,  at some second the number of distinct users online reached value M,  the total number of users (the number of distinct identifiers) was as much as possible. Help Polycarpus cope with the test.

The first line contains three integers n, M and T (1 ≤ n, M ≤ 20 000, 1 ≤ T ≤ 86400) — the number of queries, the record number of online users and the time when the user was online after a query was sent. Next n lines contain the times of the queries in the format "hh:mm:ss", where hh are hours, mm are minutes, ss are seconds. The times of the queries follow in the non-decreasing order, some of them can coincide. It is guaranteed that all the times and even all the segments of type [s, s + T - 1] are within one 24-hour range (from 00:00:00 to 23:59:59).

In the first line print number R — the largest possible number of distinct users. The following n lines should contain the user IDs for requests in the same order in which the requests are given in the input. User IDs must be integers from 1 to R. The requests of the same user must correspond to the same identifiers, the requests of distinct users must correspond to distinct identifiers. If there are multiple solutions, print any of them. If there is no solution, print "No solution" (without the quotes).

NoteConsider the first sample. The user who sent the first request was online from 17:05:53 to 17:06:02, the user who sent the second request was online from 17:05:58 to 17:06:07, the user who sent the third request, was online from 17:06:01 to 17:06:10. Thus, these IDs cannot belong to three distinct users, because in that case all these users would be online, for example, at 17:06:01. That is impossible, because M = 2. That means that some two of these queries belonged to the same user. One of the correct variants is given in the answer to the sample. For it user 1 was online from 17:05:53 to 17:06:02, user 2 — from 17:05:58 to 17:06:10 (he sent the second and third queries), user 3 — from 22:39:47 to 22:39:56.In the second sample there is only one query. So, only one user visited the network within the 24-hour period and there couldn't be two users online on the network simultaneously. (The time the user spent online is the union of time intervals for requests, so users who didn't send requests could not be online in the network.)

open Printf
open Scanf

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

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_time () = bscanf Scanning.stdib " %d:%d:%d " (fun x y z -> 3600*x + 60*y + z)

let () =
  let n = read_int () in
  let m = read_int () in
  let t = read_int () in
  let query = Array.init n (fun _ -> read_time()) in

  let rec build_events i ac = if i=n then ac else
      let e = query.(i) in
      let ac = (e, true, i)::ac in (* entering *)
      let ac = (e+t, false, i)::ac in (* leaving *)
      build_events (i+1) ac
  in

  let events = List.sort compare (build_events 0 []) in

  let label = Array.make n 0 in

  let reachedm = ref false in

  let rec scan events nextlabel ninset set = match events with [] -> nextlabel
    | (e,true,i)::tail ->
      if ninset = m then (
	let (id,j) = Pset.max_elt set in
	let set = Pset.add (id,i) set in
	label.(i) <- id;
	scan tail nextlabel ninset set
      ) else (
	let id = nextlabel in
	let set = Pset.add (id,i) set in
	label.(i) <- id;
	let ninset = ninset+1 in
	reachedm := !reachedm || ninset = m;
	scan tail (nextlabel+1) ninset set
      )
    | (e,false,i)::tail ->
      let set = Pset.remove (label.(i), i) set in
      let (_,_,r) = Pset.split (label.(i), -1) set in
      let d = if Pset.is_empty r then 1 else
	  let (id,j) = Pset.min_elt r in
	  if id <> label.(i) then 1 else 0
      in
      scan tail nextlabel (ninset-d) set
  in

  let lab = scan events 1 0 Pset.empty in

  if not !reachedm then printf "No solution\n" else (
    printf "%d\n" (lab-1);

    for i=0 to n-1 do
      printf "%d\n" label.(i)
    done;
  )

open Printf
open Scanf

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

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_time () = bscanf Scanning.stdib " %d:%d:%d " (fun x y z -> 3600*x + 60*y + z)

let () =
  let n = read_int () in
  let m = read_int () in
  let t = read_int () in
  let query = Array.init n (fun _ -> read_time()) in

  let rec build_events i ac = if i=n then ac else
      let e = query.(i) in
      let ac = (e, true, i)::ac in (* entering *)
      let ac = (e+t, false, i)::ac in (* leaving *)
      build_events (i+1) ac
  in

  let events = List.sort compare (build_events 0 []) in

  let label = Array.make n 0 in

  let rec scan depth events nextlabel reachedm set = match events with [] -> (nextlabel, reachedm)
    | (e,true,i)::tail ->
      let depth = depth + 1 in
      if depth > m then (
	let (id,j) = Pset.min_elt set in
	let set = Pset.add (id,i) set in
	label.(i) <- id;
	scan depth tail nextlabel reachedm set
      ) else (
	let reachedm = reachedm || depth = m in
	let id = nextlabel in
	let set = Pset.add (id,i) set in
	label.(i) <- id;
	scan depth tail (nextlabel+1) reachedm set
      )
    | (e,false,i)::tail ->
      scan (depth-1) tail nextlabel reachedm set
  in

  let (lab,reachedm) = scan 0 events 1 false Pset.empty in

  if not reachedm then printf "No solution\n" else (
    printf "%d\n" (lab-1);

    for i=0 to n-1 do
      printf "%d\n" label.(i)
    done;
  )

open Printf
open Scanf

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

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_time () = bscanf Scanning.stdib " %d:%d:%d " (fun x y z -> 3600*x + 60*y + z)

let () =
  let n = read_int () in
  let m = read_int () in
  let t = read_int () in
  let query = Array.init n (fun _ -> read_time()) in

  let rec build_events i ac = if i=n then ac else
      let e = query.(i) in
      let ac = (e, true, i)::ac in (* entering *)
      let ac = (e+t, false, i)::ac in (* leaving *)
      build_events (i+1) ac
  in

  let events = List.sort compare (build_events 0 []) in

  let label = Array.make n 0 in

  let rec scan depth events nextlabel reachedm set = match events with [] -> (nextlabel, reachedm)
    | (e,true,i)::tail ->
      let depth = depth + 1 in
      if depth > m then (
	let (id,j) = Pset.min_elt set in
	let set = Pset.add (id,i) set in
	label.(i) <- id;
	scan depth tail nextlabel reachedm set
      ) else (
	let reachedm = reachedm || depth = m in
	let id = nextlabel in
	let set = Pset.add (id,i) set in
	label.(i) <- id;
	scan depth tail (nextlabel+1) reachedm set
      )
    | (e,false,i)::tail ->
      let set = Pset.remove (label.(i), i) set in
      scan (depth-1) tail nextlabel reachedm set
  in

  let (lab,reachedm) = scan 0 events 1 false Pset.empty in

  if not reachedm then printf "No solution\n" else (
    printf "%d\n" (lab-1);

    for i=0 to n-1 do
      printf "%d\n" label.(i)
    done;
  )


Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.

The first line contains one integer n (1 ≤ n ≤ 100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

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

let () =
    let l = read () in
    let gifter = Array.init l (fun x -> read ()) in
    let giftee = Array.make l 0 in
    let rec loop i =
    if i < l
    then
        (let j = (Array.get gifter i) - 1 in
        Array.set giftee j (i + 1);
        loop (i + 1))
    else
        Array.iter(Printf.printf "%d ") giftee
    in loop 0

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

let input () = Array.init (read ()) (fun n -> read ())

let solve gifter =
    let l = Array.length gifter in
    let giftee = Array.make l 0 in
    let rec loop i =
    if i < l
    then
        (let j = (Array.get gifter i) - 1 in
        Array.set giftee j (i + 1);
        loop (i + 1))
    else
        giftee
    in loop 0

let () = Array.iter(Printf.printf "%d ") (solve (input()))

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

let input () = Array.init (read ()) (fun n -> read ())

let solve gifter =
    let l = Array.length gifter in
    let giftee = Array.make l 0 in
    let rec loop i =
    if i < l
    then
        (let j = Array.get gifter i in
        Array.set giftee (j - 1) (i + 1);
        loop (i + 1))
    else
        giftee
    in loop 0

let () = Array.iter(Printf.printf "%d ") (solve (input()))

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

let n = read_int()
let a = Array.make n 0

let _ =
  for i=0 to n-1 do
    a.(i) <- read_int() -1
  done

let b = Array.make n 0

let _ =
  for i=0 to n-1 do
    b.(a.(i)) <- i
  done;

  for i=0 to n-1 do
    Printf.printf "%d" (b.(i)+1);
    if i<n-1 then Printf.printf " ";
  done;

  Printf.printf "\n"

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

let () =
  let n = read_int () in
  let arr = Array.make n 0 in
  for i = 0 to n-1 do
    let e = read_int () in
    (Array.set arr (e-1) i)
  done;
  Array.iter (fun x -> (Printf.printf "%d " (x + 1))) arr

let string_of_charlist cl =
    let rec iter cl str =
        match cl with
            [] -> str
          | r :: rest ->
                let s = Char.escaped r in
                iter rest (str ^ s)
    in iter cl ""

let charlist_of_string str =
    let n = String.length str in
    let rec iter i cl =
        if i < 0 then
            cl
        else
            let sc = str.[i] in
            iter (i-1) (sc :: cl)
    in iter (n-1) []

let split c s =
    let n = String.length s in
    let rec spliti i cl sl =
        if i < 0 then
            if cl = [] then
                sl
            else
                let cs = string_of_charlist cl in
                cs :: sl
        else if s.[i] = c then
            if cl = [] then
                spliti (i-1) cl sl
            else
                let cs = string_of_charlist cl in
                spliti (i-1) [] (cs :: sl)
        else
            spliti (i-1) (s.[i] :: cl) sl
    in spliti (n-1) [] []

let n = read_line ();;

let input = List.map int_of_string (split ' ' (read_line ()));;

let rec f i = function
    [] -> []
  | r :: rest -> (i, r) :: (f (i+1) rest);;

let hoge = f 1 input;;

let output =
    let fn (_, a) (_, b) = a <= b in
    let fm (a, b) = string_of_int a in
    let out = Sort.list fn hoge in
    let ou2 = List.map fm out in
    String.concat " " ou2;;

print_endline output;;

let rec split str sep =
	if str = "" then []
	else try
		let i = String.index str sep in
		let x = String.sub str 0 i in
		let xs = String.sub str (i+1) (String.length str - i - 1) in
		x::(split xs sep)
	with _ -> [str]
;;

let n = read_int () in
let nums = List.map int_of_string (split (read_line()) ' ') in
let p = Array.make n 0 in
let _ = for i = 0 to n-1 do
	Array.set p (List.nth nums i - 1) i
done in
for i = 0 to n-1 do
	print_string (string_of_int (p.(i) + 1) ^ " ")
done;;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make (n + 1) 0 in
    for i = 1 to n do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(k) <- i
    done;
    for i = 1 to n do
      Printf.printf "%d " a.(i);
    done;
    Printf.printf "\n"

let iteri f =
  let rec iteri' i = function
      [] -> ()
    | x::xs -> f i x; iteri' (i+1) xs
  in
    iteri' 0
let read_int () = Scanf.scanf "%d%c" (fun x c -> x)
let rec read_ints n =
  if n = 0 then []
  else let tmp = read_int () in tmp :: read_ints (n-1)
let print_array v = Array.iter (Printf.printf "%d ") v
let p x = prerr_int x; prerr_newline ()

;;

let _ =
    let n = read_int ()
    in
    let ans = Array.make n 0
    in
      iteri (fun i x -> ans.(x-1) <- i+1) (read_ints n);
      print_array ans

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

let input () = Array.init (read ()) (fun n -> read ())

let solve gifter =
    let l = Array.length gifter in
    let giftee = Array.make l 0 in
    let rec loop i =
    if i < l
    then
        (let j = Array.get gifter i in
        Array.set giftee (j - 1) j;
        loop (i + 1))
    else
        giftee
    in loop 0

let () = Array.iter(Printf.printf "%d ") (solve (input()))

open Str;;

print_string (read_line ());;


You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other.    The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \le a \le r_1$$$, $$$l_2 \le b \le r_2$$$ and $$$a \ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Each of the next $$$q$$$ lines contains four integers $$$l_{1_i}, r_{1_i}, l_{2_i}$$$ and $$$r_{2_i}$$$ ($$$1 \le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$$$) — the ends of the segments in the $$$i$$$-th query.

Print $$$2q$$$ integers. For the $$$i$$$-th query print two integers $$$a_i$$$ and $$$b_i$$$ — such numbers that $$$l_{1_i} \le a_i \le r_{1_i}$$$, $$$l_{2_i} \le b_i \le r_{2_i}$$$ and $$$a_i \ne b_i$$$. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any.

open Str

let twoPoints (l1:int) (r1:int) (l2:int) (r2:int) : int * int=
  if l1 <> l2 then (l1,l2)
  else if r1 > l1 then (r1, l2)
  else (l1,r2)

let rec repeat (n:int) f =
  if n > 0 then (f () ; repeat (n-1) f)

let oneiter () =
  let inp = read_line() in
  let [l1;r1;l2;r2] =
    List.map int_of_string (Str.split (Str.regexp " +") inp) in
  let (x,y) = twoPoints l1 r1 l2 r2 in
  print_string ((string_of_int x) ^ " " ^ (string_of_int y) ^ "\n")

let main () =
  let q = int_of_string (read_line ()) in
  repeat q oneiter

let () = main()

let q = int_of_string (input_line stdin);;

let output a b c d =
    let other = if a = c then d else c in
        Printf.printf "%d %d\n" a other ;;

let solve () = Scanf.scanf "%d %d %d %d " output ;;

for i = 1 to q do
    solve ()
done

let q = int_of_string (input_line stdin);;

let output a b c d =
    let min = Pervasives.min a c in
    let max = Pervasives.max b d in
        Printf.printf "%d %d\n" min max ;;

let solve () = Scanf.scanf "%d %d %d %d " output ;;

for i = 1 to q do
    solve ()
done

let q = int_of_string (input_line stdin);;

let output a b c d = Printf.printf "%d %d\n" a d ;;
let solve () = Scanf.scanf "%d %d %d %d " output ;;

for i = 1 to q do
    solve ()
done


The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \le l_i \le r_i \le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

The first line contains two space-separated integers $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) and $$$q$$$ ($$$1 \le q \le 2\cdot10^5$$$) — the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 2\cdot10^5$$$) — the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the $$$i$$$-th query.

In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

(* Codeforces 276C - Devochka max sum *)

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 rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;

let rec read_pairs_list n acc = match n with
	| 0 -> List.rev acc
	| _ ->
			let x = gr()-1 in
			let y = gr()-1 in
			read_pairs_list (n -1) ((x, y) :: acc);;

let n = gr();;
let q = gr();;
let a = readlist n [];;
let lr = read_pairs_list q [];;
let ocua = Array.make n 0;;
let ocu1000 = Array.make ((n /1000) +1) 0;;

let rec count_ocu lp = match lp with
	| [] -> ()
	| (l, r) :: tl ->
			begin
				let lt = l /1000 in
				let rt = r /1000 in
				if lt < rt -1 then begin
					for i = lt +1 to rt -1 do
						ocu1000.(i) <- ocu1000.(i) + 1
					done;
					for i = l to (lt +1) *1000 -1 do
						ocua.(i) <- ocua.(i) + 1
					done;
					for i = rt *1000 to r do
						ocua.(i) <- ocua.(i) + 1
					done
				end else
					for i = l to r do
						ocua.(i) <- ocua.(i) + 1
					done;
				count_ocu tl
			end;;

let rec use_thousands n = match n with
	| 0 -> ()
	| _ ->
			let n1 = n -1 in (
				ocua.(n1) <- ocua.(n1) + ocu1000.(n1 /1000);
				use_thousands n1
			);;

let rec cntmul sa sb cnt =
	match sa, sb with
	| [], [] -> cnt
	| ha :: ta, hb :: tb ->
			let ncnt = (Int64.add cnt (Int64.mul (Int64.of_int ha) (Int64.of_int hb))) in
			cntmul ta tb ncnt
	| _ -> raise (Failure "Different lengths sa sb");;

let main() =
	begin
		count_ocu lr;
		use_thousands (n -1);
		let sb = List.sort compare (Array.to_list ocua) in
		let sa = List.sort compare a in
		let sum_mul = cntmul sa sb Int64.zero in
		print_string ((Int64.to_string sum_mul) ^ "\n")
	end;;

main();;

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

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 rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) ++ a) 0L

let () =
  let (n,q) = read_pair() in

  let a = Array.init n (fun i -> read_long()) in

  let range = Array.init q (fun _ -> read_pair()) in

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

    for i=0 to q-1 do
      let (l,r) = range.(i) in
	count.(l-1) <- count.(l-1) ++ 1L;
	count.(r) <- count.(r) -- 1L;
    done;

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

    let () = count.(n) <- Int64.max_int in

    let () = Array.sort compare count in

    let () = Array.sort compare a in

    let answer = sum 0 (n-1) (fun i-> count.(i) ** a.(i)) in
      Printf.printf "%Ld\n" answer


You need to find a binary tree of size n that satisfies a given set of c constraints. Suppose that the nodes of the unknown binary tree are labeled using a pre-order traversal starting with 1. For the i-th constraint you are given two labels, ai and bi and a direction, left or right. In case of left direction, bi is an element of the subtree rooted at ai's left child. Similarly in the case of right direction bi is an element of the subtree rooted at ai's right child.

The first line of input contains two integers n and c. The next c lines contain 2 integers ai, bi (1 ≤ ai, bi ≤ n) and either "LEFT" or "RIGHT" denoting whether b is in the subtree rooted at ai's left child or in the subtree rooted at ai's right child. The problem consists of multiple subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.   In subproblem D1 (9 points), the constraints 1 ≤ n ≤ 100, 1 ≤ c ≤ 50 will hold.  In subproblem D2 (8 points), the constraints 1 ≤ n ≤ 1000000, 1 ≤ c ≤ 100000 will hold.

Output will be on a single line. Any binary tree that satisfies the constraints will be accepted. The tree's nodes should be printed out as n space separated labels representing an in-order traversal, using the pre-order numbers as labels of vertices. If there are no trees that satisfy the constraints, print "IMPOSSIBLE" (without quotes).

NoteConsider the first sample test. We need to find a tree with 3 nodes that satisfies the following two constraints. The node labeled 2 with pre-order traversal should be in the left subtree of the node labeled 1 with pre-order traversal; the node labeled 3 with pre-order traversal should be in the right subtree of the node labeled 1. There is only one tree with three nodes that satisfies these constraints and its in-order traversal is (2, 1, 3).Pre-order is the "root – left subtree – right subtree" order. In-order is the "left subtree – root – right subtree" order.For other information regarding in-order and pre-order, see http://en.wikipedia.org/wiki/Tree_traversal.

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 () =
  let n = read_int () in
  let c = read_int () in

  (* the following 3 arrays represent the input, and are not computed *)
  let lhi = Array.make (n+1) 0 in  (* lhi.(x) is the highest node required to be in the left subtree of x *)
  let rlo = Array.make (n+1) (n+1) in  (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)
  let rhi = Array.make (n+1) 0 in

  (* the following two arrays are computed *)
  let rtc = Array.init (n+1) (fun i -> i) in
  (* rtc.(x) (required to contain)
     We know that the subtree rooted at x must contain x,x+1 ... y
     for some y.  rtc.(x) is the minimum such y required by the
     constraints on the nodes x and greater. *)
  let l =   Array.make (n+1) 0 in  (* size of the left subtree of x *)

  try (
    for i=1 to c do
      let x = read_int() in
      let y = read_int() in
      if y <= x then raise (Failure "1");
      match read_string() with
	| "LEFT" ->
	  lhi.(x) <- max lhi.(x) y;
	| "RIGHT" ->
	  rlo.(x) <- min rlo.(x) y;
	  rhi.(x) <- max rhi.(x) y;
	| _ -> failwith "bad command"
    done;

    let rec set_rtc x elist = if x>1 then (
      rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));
      let rec loop elist =
	match elist with
	  | [] -> [(x,rtc.(x))]
	  | (a,b)::tail ->
	    if rtc.(x) < a then (x,rtc.(x))::elist else (
	      rtc.(x) <- max b rtc.(x);
	      loop tail
	    )
      in
      if rtc.(x) > x then set_rtc (x-1) (loop elist) else set_rtc (x-1) elist
    )
    in

    set_rtc (n-1) [];

    for x = 1 to n-1 do
      l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;
    done;

    for x = 1 to n-1 do
      if x + l.(x) >= rlo.(x) then raise (Failure "2");
    done;

    let rec inorder x s =
      if l.(x) > 0 then inorder (x+1) l.(x);
      printf "%d " x;
      let rsize = s - l.(x) - 1 in
      if rsize > 0 then inorder (x+l.(x)+1) rsize
    in
    inorder 1 n;
    print_newline();

  ) with Failure s -> printf "IMPOSSIBLE\n";

open Printf
open Scanf

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

let 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 c = read_int () in

  (* the following 3 arrays represent the input, and are not computed *)
  let lhi = Array.make (n+1) 0 in  (* lhi.(x) is the highest node required to be in the left subtree of x *)
  let rlo = Array.make (n+1) (n+1) in  (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)
  let rhi = Array.make (n+1) 0 in

  (* the following two arrays are computed *)
  let rtc = Array.init (n+1) (fun i -> i) in
  (* rtc.(x) (required to contain)
     We know that the subtree rooted at x must contain x,x+1 ... y
     for some y.  rtc.(x) is the minimum such y required by the
     constraints on the nodes x and greater. *)
  let l =   Array.make (n+1) 0 in  (* size of the left subtree of x *)

  try (
    for i=1 to c do
      let x = read_int() in
      let y = read_int() in
      if y <= x then raise (Failure "1");
      match read_string() with
	| "LEFT" ->
	  lhi.(x) <- max lhi.(x) y;
	| "RIGHT" ->
	  rlo.(x) <- min rlo.(x) y;
	  rhi.(x) <- max rhi.(x) y;
	| _ -> failwith "bad command"
    done;

    for x = n-1 downto 2 do
      rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));
      rtc.(x) <- maxf x rtc.(x) (Array.get rtc);
    done;

    for x = 1 to n-1 do
      l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;
    done;

    for x = 1 to n-1 do
      if x + l.(x) >= rlo.(x) then raise (Failure "2");
    done;

    let rec inorder x s =
      if l.(x) > 0 then inorder (x+1) l.(x);
      printf "%d " x;
      let rsize = s - l.(x) - 1 in
      if rsize > 0 then inorder (x+l.(x)+1) rsize
    in
    inorder 1 n;
    print_newline();

  ) with Failure s -> printf "IMPOSSIBLE\n";

open Printf
open Scanf

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

let 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 c = read_int () in

  let l =   Array.make (n+1) 0 in  (* size of the left subtree of x *)
  let lhi = Array.make (n+1) 0 in  (* lhi.(x) is the highest node required to be in the left subtree of x *)
  let rlo = Array.make (n+1) (n+1) in  (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)
  let rhi = Array.make (n+1) 0 in
  let rtc = Array.init (n+1) (fun i -> i) in
  (* rtc.(x) (required to contain)
     We know that the subtree rooted at x must contain x,x+1 ... y
     for some y.  rc.(x) is the minimum such y required by the
     constraints on the nodes x and greater. *)

  try (
    for i=1 to c do
      let x = read_int() in
      let y = read_int() in
      if y <= x then raise (Failure "1");
      match read_string() with
	| "LEFT" ->
	  lhi.(x) <- max lhi.(x) y;
	| "RIGHT" ->
	  rlo.(x) <- min rlo.(x) y;
	  rhi.(x) <- max rhi.(x) y;
	| _ -> failwith "bad command"
    done;

    for x = n-1 downto 2 do
      rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));
      let rec loop rtcx =
	rtc.(x) <- maxf x rtcx (Array.get rtc);
	if rtc.(x) > rtcx then loop rtc.(x)
      in
      loop rtc.(x);
    done;

    for x = 1 to n-1 do
      l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;
    done;

    for x = 1 to n-1 do
      if x + l.(x) >= rlo.(x) then raise (Failure "2");
    done;

    let rec inorder x s =
      if l.(x) > 0 then inorder (x+1) l.(x);
      printf "%d " x;
      let rsize = s - l.(x) - 1 in
      if rsize > 0 then inorder (x+l.(x)+1) rsize
    in
    inorder 1 n;
    print_newline();

  ) with Failure s -> printf "IMPOSSIBLE\n";

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 () =
  let n = read_int () in
  let c = read_int () in

  (* the following 3 arrays represent the input, and are not computed *)
  let lhi = Array.make (n+1) 0 in  (* lhi.(x) is the highest node required to be in the left subtree of x *)
  let rlo = Array.make (n+1) (n+1) in  (* everything in [rlo.(x), rhi.(x)] must be in the right subtree of x*)
  let rhi = Array.make (n+1) 0 in

  (* the following two arrays are computed *)
  let rtc = Array.init (n+1) (fun i -> i) in
  (* rtc.(x) (required to contain)
     We know that the subtree rooted at x must contain x,x+1 ... y
     for some y.  rtc.(x) is the minimum such y required by the
     constraints on the nodes x and greater. *)
  let l =   Array.make (n+1) 0 in  (* size of the left subtree of x *)

  try (
    for i=1 to c do
      let x = read_int() in
      let y = read_int() in
      if y <= x then raise (Failure "1");
      match read_string() with
	| "LEFT" ->
	  lhi.(x) <- max lhi.(x) y;
	| "RIGHT" ->
	  rlo.(x) <- min rlo.(x) y;
	  rhi.(x) <- max rhi.(x) y;
	| _ -> failwith "bad command"
    done;

    let rec set_rtc x elist = if x>2 then (
      rtc.(x) <- max rtc.(x) (max lhi.(x-1) (max lhi.(x) rhi.(x)));
      let rec loop elist =
	match elist with
	  | [] -> [(x,rtc.(x))]
	  | (a,b)::tail ->
	    if rtc.(x) < a then (x,rtc.(x))::elist else (
	      rtc.(x) <- max b rtc.(x);
	      loop tail
	    )
      in
      if rtc.(x) > x then set_rtc (x-1) (loop elist) else set_rtc (x-1) elist
    )
    in

    set_rtc (n-1) [];

    for x = 1 to n-1 do
      l.(x) <- if lhi.(x) = 0 then 0 else rtc.(x+1) - (x+1) + 1;
    done;

    for x = 1 to n-1 do
      if x + l.(x) >= rlo.(x) then raise (Failure "2");
    done;

    let rec inorder x s =
      if l.(x) > 0 then inorder (x+1) l.(x);
      printf "%d " x;
      let rsize = s - l.(x) - 1 in
      if rsize > 0 then inorder (x+l.(x)+1) rsize
    in
    inorder 1 n;
    print_newline();

  ) with Failure s -> printf "IMPOSSIBLE\n";


While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of one of them and not a subsequence of the other.A subsequence of some string is a sequence of characters that appears in the same order in the string, The appearances don't have to be consecutive, for example, strings "ac", "bc", "abc" and "a" are subsequences of string "abc" while strings "abbc" and "acb" are not. The empty string is a subsequence of any string. Any string is a subsequence of itself.

The first line contains string a, and the second line — string b. Both of these strings are non-empty and consist of lowercase letters of English alphabet. The length of each string is not bigger than 105 characters.

If there's no uncommon subsequence, print "-1". Otherwise print the length of the longest uncommon subsequence of a and b.

NoteIn the first example: you can choose "defgh" from string b as it is the longest subsequence of string b that doesn't appear as a subsequence of string a.

let () =
  Scanf.scanf "%s %s " @@ fun a b ->
  if a = b then
    print_endline "-1"
  else
    let la = String.length a and lb = String.length b in
    Printf.printf "%d\n" (max la lb)


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

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

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

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

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

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

module type Seg_tree_S = sig
  type t
  type elt

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

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

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

  let log2 a = log a /. log 2.

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

  let size = fst

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

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

end

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

module ST = Seg_tree(Monoid_bool)

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

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

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


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

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

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

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


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

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

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

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

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

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


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

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

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

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

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

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

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

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

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

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

(*#trace process_data;;*)

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

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

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

let res = Array.make 6 0;;

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

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

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

(*#trace process_data;;*)

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