You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is:  "()" is regular bracket sequence;  if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence;  if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 50$$$) — the length of $$$s$$$. It is guaranteed that $$$n$$$ is even. The second line of the test case containg the string $$$s$$$ consisting of $$$\frac{n}{2}$$$ opening and $$$\frac{n}{2}$$$ closing brackets.

For each test case, print the answer — the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.

NoteIn the first test case of the example, it is sufficient to move the first bracket to the end of the string.In the third test case of the example, it is sufficient to move the last bracket to the beginning of the string.In the fourth test case of the example, we can choose last three openning brackets, move them to the beginning of the string and obtain "((()))(())".

module A = Array
module C = Char
module I = Int64
module L = List
module Q = Queue
module S = String

let pf = Printf.printf
let sf = Scanf.scanf
let ssf = Scanf.sscanf

let read_int () = sf "%d " (fun x -> x)
let read_float () = sf "%f " (fun x -> x)
let read_char () = sf "%c" (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())
let read_list read n = for i = 1 to n do read () done
let read_line () = sf "%s\n" (fun x -> x)
let err s = raise (Failure s)

let inf = int_of_float 1e18
let eps = 1e-11

let count_dangling n xs =
  let rec loop dangling openb i =
    if i = n then dangling
    else if xs.[i] = '(' then loop dangling (openb + 1) (i + 1)
    else if openb == 0 then loop (dangling + 1) openb (i + 1)
    else loop dangling (openb - 1) (i + 1)
  in loop 0 0 0

let () =
  for i = 1 to (read_int ()) do
    let n = (read_int ()) in
    let s =  (read_line ()) in
    pf "%d\n" (count_dangling n s)
  done

open Printf

let main =
  let t = read_int() in
  for i = 1 to t do
    let _ = read_int() in
    let brackets = read_line() in

    let answer = ref 0 in
    let m = ref 0 in

    String.iter (fun c ->
      if c = '(' then
        m := !m + 1
      else if c = ')' then
        m := !m - 1;
        if !m < 0 then
          answer := max (!answer) (-(!m))
    ) brackets;
    printf "%d\n" (!answer)
  done


A well-known art union called "Kalevich is Alive!" manufactures objects d'art (pictures). The union consists of n painters who decided to organize their work as follows.Each painter uses only the color that was assigned to him. The colors are distinct for all painters. Let's assume that the first painter uses color 1, the second one uses color 2, and so on. Each picture will contain all these n colors. Adding the j-th color to the i-th picture takes the j-th painter tij units of time.Order is important everywhere, so the painters' work is ordered by the following rules:  Each picture is first painted by the first painter, then by the second one, and so on. That is, after the j-th painter finishes working on the picture, it must go to the (j + 1)-th painter (if j < n);  each painter works on the pictures in some order: first, he paints the first picture, then he paints the second picture and so on;  each painter can simultaneously work on at most one picture. However, the painters don't need any time to have a rest;  as soon as the j-th painter finishes his part of working on the picture, the picture immediately becomes available to the next painter. Given that the painters start working at time 0, find for each picture the time when it is ready for sale.

The first line of the input contains integers m, n (1 ≤ m ≤ 50000, 1 ≤ n ≤ 5), where m is the number of pictures and n is the number of painters. Then follow the descriptions of the pictures, one per line. Each line contains n integers ti1, ti2, ..., tin (1 ≤ tij ≤ 1000), where tij is the time the j-th painter needs to work on the i-th picture.

Print the sequence of m integers r1, r2, ..., rm, where ri is the moment when the n-th painter stopped working on the i-th picture.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let m=read_int() and n=read_int();;
let mat=Array.make_matrix (m+1) (n+1) 0;;
for i=1 to m do
   for j=1 to n do
      mat.(i).(j)<-read_int()
   done
done;;
let sol=Array.make (m+1) 0;;
for j=1 to n do
   let temp=ref (sol.(1)) in
   for i=1 to m do
      if !temp>=sol.(i) then
         begin
         temp:= !temp+mat.(i).(j);
         sol.(i)<- !temp
         end
      else
         begin
         temp:=sol.(i)+mat.(i).(j);
         sol.(i)<- !temp
         end
   done
done;;

for i=1 to m do
   print_int sol.(i);
   if i<>m then print_string " "
done;;


Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is a palindrome and remove it from the line. After the substring is removed, the remaining gemstones shift to form a solid line again. What is the minimum number of seconds needed to destroy the entire line?Let us remind, that the string (or substring) is called palindrome, if it reads same backwards or forward. In our case this means the color of the first gemstone is equal to the color of the last one, the color of the second gemstone is equal to the color of the next to last and so on.

The first line of input contains a single integer n (1 ≤ n ≤ 500) — the number of gemstones. The second line contains n space-separated integers, the i-th of which is ci (1 ≤ ci ≤ n) — the color of the i-th gemstone in a line.

Print a single integer — the minimum number of seconds needed to destroy the entire line.

NoteIn the first sample, Genos can destroy the entire line in one second.In the second sample, Genos can only destroy one gemstone at a time, so destroying three gemstones takes three seconds.In the third sample, to achieve the optimal time of two seconds, destroy palindrome 4 4 first and then destroy palindrome 1 2 3 2 1.

open Printf
open Scanf

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

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

  let mem = Array.make_matrix n n (-1) in

  for i=0 to n-1 do
    mem.(i).(i) <- 1
  done;

  let rec score i j = if i>j then 0 else if mem.(i).(j) >= 0 then mem.(i).(j) else
      let answer =
	if i+1 = j then
	  if c.(i) = c.(j) then 1 else 2
	else
	  let mm = ref n in
	  for k = i to j do
	    if c.(i) = c.(k) then
	      let noarch = if i=k || i+1=k then 1 else 0 in
	      mm := min !mm (noarch + (score (i+1) (k-1)) + (score (k+1) j))
	  done;
	  !mm
      in
      mem.(i).(j) <- answer;
(*      printf "score %d %d = %d\n" i j answer; *)
      answer
  in

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


Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword".You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≤ i ≤ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x ≠ a holds.

The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≤ k ≤ 105) — the required number of operations.

Print a single number — the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7).

NoteThe sought way in the first sample is:ab  →  a|b  →  ba  →  b|a  →  abIn the second sample the two sought ways are: ababab  →  abab|ab  →  ababab  ababab  →  ab|abab  →  ababab

exception Found of int

let _ =
  let m = 1000000007L in
  let sb = Scanf.Scanning.stdib in
  let a = Scanf.bscanf sb "%s " (fun s -> s) in
  let b = Scanf.bscanf sb "%s " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = String.length a in
  let s =
    try
      for i = 0 to n - 1 do
	try
	  for j = 0 to n - 1 do
	    let j' = i + j in
	    let j' = if j' >= n then j' - n else j' in
	      if a.[j] <> b.[j']
	      then raise Not_found
	  done;
	  raise (Found i)
	with
	  | Not_found -> ()
      done;
      -1
    with
      | Found s -> s
  in
  let p =
    try
      for i = 1 to n - 1 do
	if n mod i = 0 then (
	  try
	    for j = 0 to n - 1 - i do
	      if a.[j] <> a.[j + i]
	      then raise Not_found
	    done;
	    raise (Found i)
	  with
	    | Not_found -> ()
	)
      done;
      n
    with
      | Found s -> s
  in
    if s < 0
    then Printf.printf "0\n"
    else if s = 0 && k = 0
    then Printf.printf "1\n"
    else if k = 0
    then Printf.printf "0\n"
    else if s = 0 && k = 1
    then Printf.printf "%d\n" (n / p - 1)
    else if k = 1
    then Printf.printf "%d\n" (n / p)
    else (
	(*Printf.printf "asd %d %d\n" s p;*)
      let a = Array.make_matrix 2 (k + 1) 0L in
	a.(0).(0) <- 1L;
	for i = 1 to k do
	  a.(0).(i) <-
	    Int64.add
	    (Int64.mul a.(0).(i - 1) (Int64.of_int (n / p - 1)))
	    (Int64.mul a.(1).(i - 1) (Int64.of_int (n / p * (p - 1))));
	  a.(0).(i) <- Int64.rem a.(0).(i) m;
	  a.(1).(i) <-
	    Int64.add
	    (Int64.mul a.(0).(i - 1) (Int64.of_int (n / p)))
	    (Int64.mul a.(1).(i - 1) (Int64.of_int (n / p * (p - 2) + (n / p - 1))));
	  a.(1).(i) <- Int64.rem a.(1).(i) m;
	  (*Printf.printf "asd %d %Ld %Ld\n" i a.(0).(i) a.(1).(i);*)
	done;
	let res = if s = 0 then a.(0).(k) else a.(1).(k) in
	  Printf.printf "%Ld\n" res
    )


Two players A and B have a list of $$$n$$$ integers each. They both want to maximize the subtraction between their score and their opponent's score. In one turn, a player can either add to his score any element from his list (assuming his list is not empty), the element is removed from the list afterward. Or remove an element from his opponent's list (assuming his opponent's list is not empty).Note, that in case there are equal elements in the list only one of them will be affected in the operations above. For example, if there are elements $$$\{1, 2, 2, 3\}$$$ in a list and you decided to choose $$$2$$$ for the next turn, only a single instance of $$$2$$$ will be deleted (and added to the score, if necessary). The player A starts the game and the game stops when both lists are empty. Find the difference between A's score and B's score at the end of the game, if both of the players are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves. In this problem, it means that each player, each time makes a move, which maximizes the final difference between his score and his opponent's score, knowing that the opponent is doing the same.

The first line of input contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the sizes of the list. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^6$$$), describing the list of the player A, who starts the game. The third line contains $$$n$$$ integers $$$b_i$$$ ($$$1 \le b_i \le 10^6$$$), describing the list of the player B.

Output the difference between A's score and B's score ($$$A-B$$$) if both of them are playing optimally.

NoteIn the first example, the game could have gone as follows:   A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A takes his $$$1$$$.  B takes his $$$1$$$. Hence, A's score is $$$1$$$, B's score is $$$1$$$ and difference is $$$0$$$.There is also another optimal way of playing:  A removes $$$5$$$ from B's list.  B removes $$$4$$$ from A's list.  A removes $$$1$$$ from B's list.  B removes $$$1$$$ from A's list. The difference in the scores is still $$$0$$$.In the second example, irrespective of the moves the players make, they will end up with the same number of numbers added to their score, so the difference will be $$$0$$$.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done
	let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
end open MyInt64

let rec f u v i j =
	(* printf "[%s] (%Ld) v. [%s] (%Ld)\n"
		(string_of_list (Int64.to_string) u)
		i
		(string_of_list (Int64.to_string) v)
		j
	; *)
	match u,v with
	| h::t,hh::tt ->
		if h > hh then f v t j (i+h)
		else if h < hh then f tt u j i
		else (
			f tt u j i
		)
	| [],h::t -> f t u j i
	| h::t,[] -> f v t j (i+h)
	| [],[] -> (i,j)

let () =
	let n = get_i64 0 in
	let a,b = input_i64_array n,input_i64_array n
	in
	Array.sort compare a;
	Array.sort compare b;
	let a,b = Array.to_list a |> List.rev,Array.to_list b |> List.rev
	in
	f b a 0L 0L
	|> (fun (u,v) ->
		(* printf "%Ld,%Ld : %Ld\n" u v (u-v); *)
		printf "%Ld\n" (u-v)
	)


Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible. If this is possible, calculate the minimal cost.

The first line contains an integer n (1 ≤ n ≤ 300), number of cards. The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards. The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.

If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.

NoteIn first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.

(* calculate prime factors of x *)
let primes x =
  let rec reduce x p =
    if x mod p = 0
    then reduce (x / p) p
    else x
  in

  let rec aux a x p =
    (* termination condition *)
    if p * p > x
    then begin
      if x > 1
      then x :: a
      else a
    end

    (* loop condition *)
    else begin
      let y = reduce x p in
      if x = y
      then aux a x (succ p)
      else aux (p :: a) y (succ p)
    end
  in

  List.rev (aux [] x 2)

(* merge two option values *)
let merge a b ~f =
  match a, b with
  | None, x | x, None -> x
  | Some a, Some b -> Some (f a b)

(* monadic fmap into an option *)
let fmap a ~f =
  match a with
  | None -> None
  | Some a -> Some (f a)

let () = Scanf.scanf "%d\n" (fun n ->
  (* read jump lengths of cards *)
  let j = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x))
  (* read cost of cards *)
  and ws = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x))
  in

  (* fold over each of the cards as a base
   * choice to find the optimum cost in acc *)
  let cost = Array.fold_left (fun acc (x, w) ->
    (* get the prime factorisation of x *)
    let p = primes x in
    let np = List.length p in

    (* for every card, create a bitmask *)
    let m = Array.map (fun y ->
      let q = List.mapi (fun i p -> if y mod p <> 0 then 1 lsl i else 0) p in
      List.fold_left (lor) 0 q
    ) j in

    let mem = Array.make_matrix n (1 lsl np) None in

    let rec dp cur mask =
      (* termination condition, no more cards to process *)
      if cur = n
      then begin
        (* check that at least one card is not divisible
         * by each prime factor of x *)
        if mask = (1 lsl np) - 1
        then Some 0
        else None
      end else
      match mem.(cur).(mask) with
      | Some a -> a
      | None ->
          (* choose the cur card in the dp *)
          let l = fmap (dp (succ cur) (mask lor m.(cur))) ~f:((+) ws.(cur)) in
          (* don't choose cur card *)
          let r = dp (succ cur) mask in
          let a = merge l r ~f:min in
          mem.(cur).(mask) <- Some a;
          a
    in

    let a = dp 0 0 in
    merge acc (fmap a ~f:((+) w)) ~f:min
  ) None (Array.init n (fun i -> (j.(i), ws.(i))))
  in
  match cost with
  | None -> print_endline "-1"
  | Some c -> Printf.printf "%d\n" c
)


Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers from 0 to n - 1 in the counter-clockwise order. When you push a button, the first gear rotates clockwise, then the second gear rotates counter-clockwise, the the third gear rotates clockwise an so on.Besides, each gear has exactly one active tooth. When a gear turns, a new active tooth is the one following after the current active tooth according to the direction of the rotation. For example, if n = 5, and the active tooth is the one containing number 0, then clockwise rotation makes the tooth with number 1 active, or the counter-clockwise rotating makes the tooth number 4 active.Andrewid remembers that the real puzzle has the following property: you can push the button multiple times in such a way that in the end the numbers on the active teeth of the gears from first to last form sequence 0, 1, 2, ..., n - 1. Write a program that determines whether the given puzzle is real or fake.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of gears. The second line contains n digits a1, a2, ..., an (0 ≤ ai ≤ n - 1) — the sequence of active teeth: the active tooth of the i-th gear contains number ai.

In a single line print "Yes" (without the quotes), if the given Stolp's gears puzzle is real, and "No" (without the quotes) otherwise.

NoteIn the first sample test when you push the button for the first time, the sequence of active teeth will be 2 2 1, when you push it for the second time, you get 0 1 2.

let ri () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x) ;;
let n = ri() ;;
let r = ri() ;;
let rec chk i =
    if i = n then true
    else
        0 = (ri() + (if i mod 2 = 1 then r else -r) - i) mod n && chk(i+1)
;;

print_string(if chk 1 then "Yes" else "No")


Andre has very specific tastes. Recently he started falling in love with arrays.Andre calls an nonempty array $$$b$$$ good, if sum of its elements is divisible by the length of this array. For example, array $$$[2, 3, 1]$$$ is good, as sum of its elements — $$$6$$$ — is divisible by $$$3$$$, but array $$$[1, 1, 2, 3]$$$ isn't good, as $$$7$$$ isn't divisible by $$$4$$$. Andre calls an array $$$a$$$ of length $$$n$$$ perfect if the following conditions hold:   Every nonempty subarray of this array is good.  For every $$$i$$$ ($$$1 \le i \le n$$$), $$$1 \leq a_i \leq 100$$$. Given a positive integer $$$n$$$, output any perfect array of length $$$n$$$. We can show that for the given constraints such an array always exists.An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).

For every test, output any perfect array of length $$$n$$$ on a separate line.

NoteArray $$$[19, 33]$$$ is perfect as all $$$3$$$ its subarrays: $$$[19]$$$, $$$[33]$$$, $$$[19, 33]$$$, have sums divisible by their lengths, and therefore are good.

(*
  Dário was here
  13/11/2020
*)

let rec construct_list out v n =
  if n = 0 then out else (
    let space = if n = v then "" else " " in
    construct_list (out^space^(string_of_int v)) v (n-1)
  )

let _ =
  let tests = Scanf.scanf "%d " (fun a -> a) in

  for i=0 to (tests-1) do
    let n = Scanf.scanf "%d " (fun a -> a) in
    Printf.printf "%s\n" (construct_list "" n n)
  done


A sequence $$$a_1, a_2, \dots, a_n$$$ is called good if, for each element $$$a_i$$$, there exists an element $$$a_j$$$ ($$$i \ne j$$$) such that $$$a_i+a_j$$$ is a power of two (that is, $$$2^d$$$ for some non-negative integer $$$d$$$).For example, the following sequences are good:  $$$[5, 3, 11]$$$ (for example, for $$$a_1=5$$$ we can choose $$$a_2=3$$$. Note that their sum is a power of two. Similarly, such an element can be found for $$$a_2$$$ and $$$a_3$$$),  $$$[1, 1, 1, 1023]$$$,  $$$[7, 39, 89, 25, 89]$$$,  $$$[]$$$. Note that, by definition, an empty sequence (with a length of $$$0$$$) is good.For example, the following sequences are not good:  $$$[16]$$$ (for $$$a_1=16$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[4, 16]$$$ (for $$$a_1=4$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two),  $$$[1, 3, 2, 8, 8, 8]$$$ (for $$$a_3=2$$$, it is impossible to find another element $$$a_j$$$ such that their sum is a power of two). You are given a sequence $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.

The first line contains the integer $$$n$$$ ($$$1 \le n \le 120000$$$) — the length of the given sequence. The second line contains the sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $$$n$$$ elements, make it empty, and thus get a good sequence.

NoteIn the first example, it is enough to delete one element $$$a_4=5$$$. The remaining elements form the sequence $$$[4, 7, 1, 4, 9]$$$, which is good.

open Printf open Scanf
module Int64 = struct
	include Int64
	(* int *)
	let (+$) = (+)
	let (-$) = (-)
	let (/$) = (/)
	let ( *$) = ( * )
	(* int64 *)
	let (+) p q = Int64.add p q
	let (-) p q = Int64.sub p q
	let ( * ) p q = Int64.mul p q
	let (/) p q = Int64.div p q

	let labs p = if p < 0L then -1L*p else p
	let (~|) p = Int64.of_int p
	let (~|) p = Int64.to_int p

	let (+=) r v = r := !r + v
	let (-=) r v = r := !r - v
	let ( *=) r v= r := !r * v
	let (/=) r v = r := !r / v

	let input_i64_array n =
		Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 () = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 () = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 () = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 () = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 () = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let print_i64_endline n =
		n |> Int64.to_string |> print_endline
end open Int64

let () =
  let n = get_i64 ()
	in let ar = input_i64_array n
	in let table = Hashtbl.create 1200
	in let pows = Array.make 32 0L
		in let rec f0 i a =
			if i<=31 then
				let v = a*2L in
				pows.(i) <- v;
				f0 (i+$1) v
		in f0 0 1L;
	(* Array.iter (fun v -> printf "%Ld " v) pows;
	print_newline (); *)
	let update i f =
		let c = try
			let w = Hashtbl.find table i
			in w
		with | Not_found -> 0L
		in
		Hashtbl.add table i (f c)
	in
	Array.iter (fun v ->
		update v (fun c -> c+1L)
	) ar;
	(* Hashtbl.iter (fun u v -> printf "%Ld:%Ld; " u v) table;
	print_newline (); *)
	let count = ref 0L in
	Array.iter (fun v ->
		let f = ref false in
		Array.iter (fun a ->
			let w = a - v
			in if (Hashtbl.mem table w &&
				let p = Hashtbl.find table w
				in (p >= 2L || (p = 1L && w <> v))
			) then (
				(* printf "pair: %Ld,%Ld (remains %Ld)\n" v w (Hashtbl.find table w); *)
				f := true
			)
		) pows;
		(* update v (fun c -> c+=1L;!c); *)
		if not !f then count+=1L
	) ar;
	print_i64_endline !count

open Printf
let input_i64_array n =
	Array.init n (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
let get_int () = Scanf.scanf " %d" (fun v -> v)
let print_int_endline n = n |> string_of_int |> print_endline

module Int64 = struct
	include Int64
	let (+|) p q = Int64.add p q
	let (-|) p q = Int64.sub p q
	let ( *|) p q = Int64.mul p q
	let (/|) p q = Int64.div p q
	let (<|) p q =
		if Int64.compare p q < 0 then true
		else false
	let (>|) p q =
		if Int64.compare p q > 0 then true
		else false
	let (>=|) p q = not (p < q)
	let (<=|) p q = not (p > q)
	let labs p = if p <| 0L then -1L*|p else p
  let (~|) p = Int64.of_int p
end

let () =
  let n = get_int ()
  in let ar = input_i64_array n
  in let pows = Array.make 31 0L
  in let open Int64
  in
  let table = Hashtbl.create 32
  in let rec f0 i a =
    if i<=30 then
      let v = a*|2L in
      pows.(i) <- v;
      f0 (i+1) v
    else ()
  in f0 0 1L;
  let len = Array.length ar
  in let checked = Array.make len false
  in
  for i=0 to len-1 do
    Array.iter (fun v ->
      let w = v -| ar.(i) in
      if w >=| 1L then (
        try
          let j = Hashtbl.find table w
          in
          (* printf "(%d)+(%d)=%d+%d=%d\n"
            i j ar.(i) (v-ar.(i)) v
          ; *)
          checked.(i) <- true;
          checked.(j) <- true;
        with | Not_found -> ();
        Hashtbl.add table ar.(i) i
      )
    ) pows
  done;
  (* Hashtbl.iter (fun u v -> printf "%d:%d; " u v) table;
  print_newline (); *)
  Array.to_list checked
  |> List.filter (fun v -> not v)
  (* |> (fun l -> List.iter (fun v -> printf "%b;" v) l; print_endline ""; l) *)
  |> List.length
  |> print_int_endline

open Printf
let input_i64_array n =
	Array.init n (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
let get_int () = Scanf.scanf " %d" (fun v -> v)
let print_int_endline n = n |> string_of_int |> print_endline

module Int64 = struct
	include Int64
	let (+|) p q = Int64.add p q
	let (-|) p q = Int64.sub p q
	let ( *|) p q = Int64.mul p q
	let (/|) p q = Int64.div p q
	let (<|) p q =
		if Int64.compare p q < 0 then true
		else false
	let (>|) p q =
		if Int64.compare p q > 0 then true
		else false
	let (>=|) p q = not (p < q)
	let (<=|) p q = not (p > q)
	let labs p = if p <| 0L then -1L*|p else p
  let (~|) p = Int64.of_int p
end

let () =
  let n = get_int ()
  in let ar = input_i64_array n
  in let pows = Array.make 31 0L
  in let open Int64
  in
  let table = Hashtbl.create 32
  in let rec f0 i a =
    if i<=30 then
      let v = a*|2L in
      pows.(i) <- v;
      f0 (i+1) v
    else ()
  in f0 0 1L;
  let len = Array.length ar
  in let checked = Array.make len false
  in
  for i=0 to len-1 do
    Array.iter (fun v ->
      let w = v -| ar.(i) in
      if w >=| 1L then (
        try
          let ls = Hashtbl.find table w
          in match ls with
          | [] -> raise Not_found
          | j::t -> (
          (* printf "(%d)+(%d)=%d+%d=%d\n"
            i j ar.(i) (v-ar.(i)) v
          ; *)
            checked.(i) <- true;
            checked.(j) <- true;
            Hashtbl.add table w t;
          )
        with | Not_found -> ();
        try
          let ls = Hashtbl.find table ar.(i)
          in Hashtbl.add table ar.(i) (i::ls)
        with | Not_found -> (
          Hashtbl.add table ar.(i) [i]
        )
      )
    ) pows
  done;
  (* Hashtbl.iter (fun u v -> printf "%d:%d; " u v) table;
  print_newline (); *)
  Array.to_list checked
  |> List.filter (fun v -> not v)
  (* |> (fun l -> List.iter (fun v -> printf "%b;" v) l; print_endline ""; l) *)
  |> List.length
  |> print_int_endline

open Printf
let input_i64_array n =
	Array.init n (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
let get_int () = Scanf.scanf " %d" (fun v -> v)
let print_int_endline n = n |> string_of_int |> print_endline

module Int64 = struct
	include Int64
	let (+|) p q = Int64.add p q
	let (-|) p q = Int64.sub p q
	let ( *|) p q = Int64.mul p q
	let (/|) p q = Int64.div p q
	let (<|) p q =
		if Int64.compare p q < 0 then true
		else false
	let (>|) p q =
		if Int64.compare p q > 0 then true
		else false
	let (>=|) p q = not (p < q)
	let (<=|) p q = not (p > q)
	let labs p = if p <| 0L then -1L*|p else p
  let (~|) p = Int64.of_int p
end

let () =
  let n = get_int ()
  in let ar = input_i64_array n
  in let pows = Array.make 31 0L
  in let open Int64
  in
  let table = Hashtbl.create 32
  in let rec f0 i a =
    if i<=30 then
      let v = a*2 in
      pows.(i) <- ~|v;
      f0 (i+1) v
    else ()
  in f0 0 1;
  let len = Array.length ar
  in let checked = Array.make len false
  in
  for i=0 to len-1 do
    Array.iter (fun v ->
      if v -| ar.(i)>=|1L then (
        try
          let j = Hashtbl.find table (v-|ar.(i))
          in
          (* printf "(%d)+(%d)=%d+%d=%d\n"
            i j ar.(i) (v-ar.(i)) v
          ; *)
          checked.(i) <- true;
          checked.(j) <- true;
        with | Not_found -> ();
        Hashtbl.add table ar.(i) i
      )
    ) pows
  done;
  (* Hashtbl.iter (fun u v -> printf "%d:%d; " u v) table;
  print_newline (); *)
  Array.to_list checked
  |> List.filter (fun v -> not v)
  (* |> (fun l -> List.iter (fun v -> printf "%b;" v) l; print_endline ""; l) *)
  |> List.length
  |> print_int_endline

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

let () =
  let n = get_int ()
  in let ar = input_int_array n
  in let pows = Array.make 31 0
  in
  let table = Hashtbl.create 32
  in let rec f0 i a =
    if i<=30 then
      let v = a*2 in
      pows.(i) <- v;
      f0 (i+1) v
    else ()
  in f0 0 1;
  let len = Array.length ar
  in let checked = Array.make len false
  in
  for i=0 to len-1 do
    Array.iter (fun v ->
      if v-ar.(i)>=1 then (
        try
          let j = Hashtbl.find table (v-ar.(i))
          in
          (* printf "(%d)+(%d)=%d+%d=%d\n"
            i j ar.(i) (v-ar.(i)) v
          ; *)
          checked.(i) <- true;
          checked.(j) <- true;
        with | Not_found -> ();
        Hashtbl.add table ar.(i) i
      )
    ) pows
  done;
  (* Hashtbl.iter (fun u v -> printf "%d:%d; " u v) table;
  print_newline (); *)
  Array.to_list checked
  |> List.filter (fun v -> not v)
  (* |> (fun l -> List.iter (fun v -> printf "%b;" v) l; print_endline ""; l) *)
  |> List.length
  |> print_int_endline

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

let () =
  let n = get_int ()
  in let ar = input_int_array n
  in let pows = Array.make 31 0
  in
  let rec f0 i a =
    if i<=30 then
      let v = a*2 in pows.(i)<-v; f0 (i+1) v
    else ()
  in f0 0 1;
  let len = Array.length ar
  in
  let checked = Array.make len false
  in
  for i=0 to len-1 do
    for j=i+1 to len-1 do
      (* if not (checked.(i) || checked.(j)) then *)
        let sum = ar.(i)+ar.(j)
        in let p = log (float_of_int sum) /. log 2. |> int_of_float
        in
        printf "%d+%d=%d; p=%d; pows.(p)=%d; pows.(p+1)=%d\n" ar.(i) ar.(j) sum p pows.(p) pows.(p+1);
        if (p-1>=0 && pows.(p-1)=sum) || (p<=30 && pows.(p)=sum) then (
          checked.(i) <- true;
          checked.(j) <- true;
        )
    done
  done;
  Array.to_list checked
  |> List.filter (fun v -> not v)
  |> (fun l -> List.iter (fun v -> printf "%b;" v) l; print_endline ""; l)
  |> List.length
  |> print_int_endline


One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?

The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".

Print a single integer — the maximum possible size of beautiful string Nikita can get.

NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful.

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 s = read_string ()
	and wyn = ref 0 in
	let n = String.length s in

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

	for i = 1 to n do
		a.(i) <- a.(i - 1);
		b.(i) <- b.(i - 1);

		if s.[i - 1] = 'a' then
			a.(i) <- a.(i) + 1
		else
			b.(i) <- b.(i) + 1
	done;

	for i = 0 to n do
		for j = i + 1 to n do
			let bb = b.(i) + b.(n) - b.(j)
			and aa = a.(j) - a.(i) in

			wyn := max !wyn (n - bb - aa);
		done;
	done;

	for i = 1 to n do
		let aa = a.(n) - a.(i)
		and bb = b.(i) in
		wyn := max !wyn (n - aa - bb);
	done;

	printf "%d\n" !wyn;;

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

let () =
    let s = read_string () in
    let n = String.length s in
    let pref = Array.make n 0
    and cntA = ref 0
    and ans = ref 0 in
    for i = 0 to n - 1 do
        pref.(i) <- pref.(max 0 (i - 1)) + (if s.[i] = 'a' then 1 else 0);
        cntA := !cntA + (if s.[i] = 'a' then 1 else 0)
    done;
    let left = ref 0 in
    for i = 0 to n - 1 do
        let curA = ref 0
        and curB = ref 0 in
        for j = i to n - 1 do
            curA := !curA + (if s.[j] = 'a' then 1 else 0);
            curB := !curB + (if s.[j] = 'b' then 1 else 0);
            let right = !cntA - !left - !curA in
            ans := max !ans (!left + !curB + right)
        done;
        left := !left + (if s.[i] = 'a' then 1 else 0)
    done;
    printf "%d\n" (max !left !ans)

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 s = read_string ()
	and wyn = ref 0 in
	let n = String.length s in

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

	for i = 1 to n do
		a.(i) <- a.(i - 1);
		b.(i) <- b.(i - 1);

		if s.[i - 1] = 'a' then
			a.(i) <- a.(i) + 1
		else
			b.(i) <- b.(i) + 1
	done;

	for i = 0 to n do
		for j = i + 1 to n do
			let bb = b.(i) + b.(n) - b.(j)
			and aa = a.(j) - a.(i) in

			wyn := max !wyn (n - bb - aa);
		done;
	done;

	printf "%d\n" !wyn;;

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 s = read_string ()
	and wyn = ref 0 in
	let n = String.length s in

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

	for i = 1 to n do
		a.(i) <- a.(i - 1);
		b.(i) <- b.(i - 1);

		if s.[i - 1] = 'a' then
			a.(i) <- a.(i) + 1
		else
			b.(i) <- b.(i) + 1
	done;

	for i = 1 to n do
		for j = i + 1 to n do
			let bb = b.(i) + b.(n) - b.(j)
			and aa = a.(j) - a.(i) in

			wyn := max !wyn (n - bb - aa);
		done;
	done;

	printf "%d\n" !wyn;;

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

let () =
    let s = read_string () in
    let n = String.length s in
    let pref = Array.make n 0
    and cntA = ref 0
    and ans = ref 0 in
    for i = 0 to n - 1 do
        pref.(i) <- pref.(max 0 (i - 1)) + (if s.[i] = 'a' then 1 else 0);
        cntA := !cntA + (if s.[i] = 'a' then 1 else 0)
    done;
    let left = ref 0 in
    for i = 0 to n - 1 do
        let curA = ref 0
        and curB = ref 0 in
        for j = i to n - 1 do
            curA := !curA + (if s.[j] = 'a' then 1 else 0);
            curB := !curB + (if s.[j] = 'b' then 1 else 0);
            let right = !cntA - !left - !curA in
            ans := max !ans (!left + !curB + right)
        done;
        left := !left + (if s.[i] = 'a' then 1 else 0)
    done;
    printf "%d\n" !ans


This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions:   Only segments already presented on the picture can be painted;  The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment;  The numbers of points from the beginning of the tail to the end should strictly increase. Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.

First line of the input contains two integers n and m(2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number segments on the picture respectively.  Then follow m lines, each containing two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.

Print the maximum possible value of the hedgehog's beauty.

NoteThe picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3·3 = 9.

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

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

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

let rec loop n tab =
  if n >= 0 then
  let x = read n in
  tab.(x) <- true;
  loop (n-1) tab
  else ();;

let ( *| ) = Int64.mul;;

let _ =
  let (n, m) = read2 () in
  let g = Array.make (n+1) []
  and tab = Array.make (n+1) 1
  and wynik = ref Int64.zero in
  for i=1 to m do
    let (a,b) = read2 () in
    g.(a) <- b::g.(a);
    g.(b) <- a::g.(b)
  done;
  for i=1 to n do
    List.iter (fun x -> if x < i then tab.(i) <- max tab.(i) (tab.(x)+1) ) g.(i);
    if compare !wynik ( ( Int64.of_int tab.(i) ) *| ( Int64.of_int ( List.length g.(i) ) ) ) < 0 then
      wynik :=  ( ( Int64.of_int tab.(i) ) *| ( Int64.of_int ( List.length g.(i) ) ) ) ;
  done;
  Printf.printf "%Ld\n" !wynik;;

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

let () =
	let n = read_int ()
	and m = read_int ()
	and wyn = ref 0L in

	let g = Array.make (n + 1) []
	and dlugosc = Array.make (n + 1) 1L in

	for i = 1 to m do
		let a = read_int ()
		and b = read_int () in

		g.(a) <- b::g.(a);
		g.(b) <- a::g.(b);
	done;

	for i = 1 to n do
		let s = Int64.of_int (List.length g.(i)) in

		List.iter (fun x -> if x < i then dlugosc.(i) <- max dlugosc.(i) (Int64.add dlugosc.(x) 1L);) g.(i);

		wyn := max !wyn (Int64.mul dlugosc.(i) s)
	done;

	printf "%Ld\n" !wyn;;

open Printf
open Scanf
let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let long x = Int64.of_int x
let ( ++ ) a b = Int64.add a b
let ( ** ) a b = Int64.mul a b

let () =
    let n = read_int () and m = read_int () in
    let g = Array.make (n + 1) []
    and dp = Array.make (n + 1) 0L
    and ans = ref 0L in
    for i = 1 to m do
        let a = read_int () and b = read_int () in
        g.(a) <- b::g.(a);
        g.(b) <- a::g.(b)
    done;
    for i = 1 to n do
        dp.(i) <- max 1L (List.fold_left (fun acc x -> if x < i then max acc (dp.(x) ++ 1L) else acc) 0L g.(i));
        ans := max !ans (dp.(i) ** long ((List.length g.(i))))
    done;
    printf "%Ld\n" !ans

open Printf
open Scanf

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

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

let 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_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in

  let g = Array.make n [] in

  let add_edge (i,j) =
    g.(i) <- j::g.(i);
    g.(j) <- i::g.(j)
  in
  let d = Array.make n 0 in

  for i = 0 to m-1 do
    let u = -1+read_int() in
    let v = -1+read_int() in
    d.(u) <- d.(u) + 1;
    d.(v) <- d.(v) + 1;
    add_edge (u,v)
  done;

  let l = Array.make n 1 in

  for u = 0 to n-1 do
    l.(u) <- List.fold_left (fun ac v -> if u > v then max ac (1+l.(v)) else ac) 1 g.(u)
  done;

  let answer = maxf 0 (n-1) (fun v -> (long (l.(v))) ** (long d.(v))) in

  printf "%Ld\n" answer

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

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

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

let rec loop n tab =
  if n >= 0 then
  let x = read n in
  tab.(x) <- true;
  loop (n-1) tab
  else ();;

let _ =
  let (n, m) = read2 () in
  let g = Array.make (n+1) []
  and tab = Array.make (n+1) 1
  and wynik = ref 0 in
  for i=1 to m do
    let (a,b) = read2 () in
    g.(a) <- b::g.(a);
    g.(b) <- a::g.(b)
  done;
  for i=1 to n do
    List.iter (fun x -> if x < i then tab.(i) <- max tab.(i) (tab.(x)+1) ) g.(i);
    wynik := max !wynik ( tab.(i) * ( List.length g.(i) ) )
  done;
  Printf.printf "%d\n" !wynik;;

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

let () =
	let n = read_int ()
	and m = read_int ()
	and wyn = ref 0 in

	let g = Array.make (n + 1) []
	and dlugosc = Array.make (n + 1) 1 in

	for i = 1 to m do
		let a = read_int ()
		and b = read_int () in

		g.(a) <- b::g.(a);
		g.(b) <- a::g.(b);
	done;

	for i = 1 to n do
		let s = List.length g.(i) in

		List.iter (fun x -> if x < i then dlugosc.(i) <- max dlugosc.(i) (dlugosc.(x) + 1);) g.(i);

		wyn := max !wyn (dlugosc.(i) * s)
	done;

	printf "%d\n" !wyn;;


Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.He asks you to help to find the initial arrangement of the balls in the boxes.

The first line of the input contains two integers n and x (2 ≤ n ≤ 105, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a1, a2, ..., an, where integer ai (0 ≤ ai ≤ 109, ax ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.  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.

Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.

(* Codeforces 260C KorobkiBalls *)

open String;;
open Array;;
open Int64;;

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

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

let rec readarray i n ar =
	if i < n then begin
		ar.(i) <- (Int64.of_int (gr()));
		readarray (i +1) n ar
	end;;

let debug = false;;

let n = gr();;
let last = gr();;
let an = Array.make n Int64.zero;;

let rec step i cnt =
	if an.(i) = Int64.zero then an.(i) <- cnt
	else begin
		an.(i) <- Int64.pred an.(i);
		let ii = if i =0 then n -1 else i -1 in
		step ii (Int64.succ cnt)
	end;;

let rec find_min i mn =
	if i = n then mn
	else let mini = if an.(i) < mn then an.(i) else mn in
	find_min (i+1) mini;;

let rec substract_min i mn =
	if i = n then ()
	else begin
		an.(i) <- Int64.sub an.(i) mn;
		substract_min (i+1) mn
  end;;

let main () = begin
		readarray 0 n an;
(*		print_int n; print_string " ";
		print_int last; print_string " ";*)
		let mini = Int64.pred (find_min 0 an.(0)) in
		begin
		  substract_min 0 mini;
			let cnt = Int64.mul (Int64.of_int n) mini in
			step (last -1) cnt
		end;
		printarri64 an;
		print_newline()
	end;;

main();;

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

let n = read_int () ;;
let x = read_int () ;;

let a =
    let rec loop i f =
        if i = n then f []
        else
            let ai = read_int ()
            in loop (i + 1) (fun l -> f ((Int64.of_int ai) :: l))
    in loop 0 (fun x -> x) ;;

let split_list l n =
    let rec loop i f = function
        | [] -> (f [], [])
        | h :: t ->
            if i = n then (f [h], t)
            else loop (i + 1) (fun tl -> f (h :: tl)) t
    in loop 1 (fun x -> x) l ;;

let left, right = split_list a x ;;

(* Get the index and value of the smallest element from the right of a list *)
let get_right_min l =
    let f = fun (i, (index, value)) a ->
        if a <= value then (i + 1, (i, a)) else (i + 1, (index, value))
    in let i, (index, value) = List.fold_left f (0, (0, Int64.max_int)) l
    in index, value ;;

(* Determine which box was selected in the beginning with 0-based index *)
let start, value =
    let (ind1, val1), (ind2, val2) = (get_right_min left), (get_right_min right)
    in if val1 <= val2 then (ind1, val1) else (ind2 + x, val2) ;;

let original =
    (*
        Make sure to remove the leftover balls between (start, x - 1]. If
        start >= x then remove a ball between [0, x - 1] U (start, n). y
        represents the leftover balls.
    *)
    let y = if start >= x then x + n - start - 1 else x - start - 1
    in List.mapi
        (fun i ai ->
            if i = start then
                Int64.add (Int64.mul (Int64.of_int n) value) (Int64.of_int y)
            else
                if start < x && i > start && i < x ||
                   start >= x && (i >= 0 && i < x || i > start && i < n) then
                    Int64.sub ai (Int64.add value Int64.one)
                else Int64.sub ai value)
        a ;;

let rec print_list = function
    | [] -> ()
    | h :: t -> Printf.printf "%Ld " h; print_list t
in print_list original; Printf.printf "\n" ;;

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b

let () =
  let n = read_int() in
  let x = read_int() in
  let x = x-1 in

  let a = Array.make n 0 in

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

    let b = Array.copy a in

    let rec scan i count besti = if count = n then besti else
      scan ((i-1+n) mod n) (count+1) (if a.(i) < a.(besti) then i else besti)
    in

    let besti = scan x 0 x in

    let rec sublast i = if i = besti then () else (
      a.(i) <- a.(i) - 1;
      sublast ((i-1+n) mod n)
    )
    in

    let () = sublast x in

    let diff = sum 0 (n-1) (fun i -> b.(i) - a.(i)) in

    let repeat = a.(besti) in

    let pile = (Int64.of_int diff) ++ (Int64.of_int repeat) ** (Int64.of_int n) in

      for i=0 to n-1 do
	if i = besti then Printf.printf "%Ld " pile
	else Printf.printf "%d " (a.(i) - repeat)
      done;

      print_newline()

(* Codeforces 260C KorobkiBalls *)

open String;;
open Array;;

let gr () = Scanf.scanf " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line Pervasives.stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;

let rec readlist n acc = match n with
	| 0 -> List.rev acc
	| _ -> readlist (n -1) (gr() :: acc);;
let rec readarray i n ar =
	if i < n then begin
		ar.(i) <- gr(); readarray (i +1) n ar
	end;;

let debug = false;;

let n = gr();;
let last = gr();;
let an = Array.make n 0;;

let rec step i cnt =
	if an.(i) = 0 then an.(i) <- cnt
	else begin
		an.(i) <- an.(i) - 1;
		let ii = if i =0 then n -1 else i -1 in
		step ii (cnt +1)
	end;;

let rec find_min i mn =
	if i = n then mn
	else let mini = if an.(i) < mn then an.(i) else mn in
	find_min (i+1) mini;;

let rec substract_min i mn =
	if i = n then ()
	else begin
		an.(i) <- an.(i) - mn;
		substract_min (i+1) mn
  end;;

let main () = begin
		readarray 0 n an;
(*		print_int n; print_string " ";
		print_int last; print_string " ";*)
		let mini = (find_min 0 an.(0) - 1) in
		begin
		  substract_min 0 mini;
			let cnt = n *mini in
			step (last -1) cnt
		end;
		printarri an;
		print_newline()
	end;;

main();;

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

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

let () =
  let n = read_int() in
  let x = read_int() in
  let x = x-1 in

  let a = Array.make n 0 in

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

    let b = Array.copy a in

    let rec scan i count besti = if count = n then besti else
      scan ((i-1+n) mod n) (count+1) (if a.(i) < a.(besti) then i else besti)
    in

    let besti = scan x 0 x in

    let rec sublast i = if i = besti then () else (
      a.(i) <- a.(i) - 1;
      sublast ((i-1+n) mod n)
    )
    in

    let () = sublast x in

    let diff = sum 0 (n-1) (fun i -> b.(i) - a.(i)) in

    let repeat = a.(besti) in

    let pile = diff + repeat * n in

      for i=0 to n-1 do
	let ans = if i = besti then pile else a.(i) - repeat in
	  Printf.printf "%d " ans
      done;

      print_newline()

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

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

let () =
  let n = read_int() in
  let x = read_int() in
  let x = x-1 in

  let a = Array.make n 0 in

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

    let b = Array.copy a in

    let rec scan i count besti = if count = n then besti else
      scan ((i-1+n) mod n) (count+1) (if a.(i) < a.(besti) then i else besti)
    in

    let besti = scan x 0 x in

(*      Printf.printf "besti= %d\n" besti; *)

    let rec sublast i =
      a.(i) <- a.(i) - 1;
      if i = besti then () else sublast ((i-1+n) mod n)
    in

    let () = sublast x in
(*
      for i=0 to n-1 do
	Printf.printf "a.(%d) = %d\n" i a.(i)
      done;
*)
    let diff = sum 0 (n-1) (fun i -> b.(i) - a.(i)) in

(*      Printf.printf "diff = %d\n" diff; *)

    let repeat = a.(besti)+1 in

(*      Printf.printf "repeat = %d\n" repeat; *)

    let pile = diff + repeat * n -1 in

      for i=0 to n-1 do
	let ans = if i = besti then pile else a.(i) - repeat in
	  Printf.printf "%d " ans
      done;

      print_newline()


«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.

The first line contains one integer n (1 ≤ n ≤ 3000) — the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 3000) — indexes of these tests.

Output the required default value for the next test index.

let t = read_int() in
let arr = Array.append [|0|] (Array.map int_of_string (
	Array.of_list (Str.split (Str.regexp " ") (read_line()))
)) in
let _ = Array.sort compare arr in
	for i = 0 to t do
		try
		if arr.(i) + 1 <> arr.(i+1) then (print_int (arr.(i) + 1); exit 0)
		with _ -> (print_int (arr.(i) + 1); exit 0)
	done;;

let t = read_int() in
let arr = Array.map int_of_string (Array.of_list (Str.split (Str.regexp " ") (read_line()))) in
let _ = Array.sort compare arr in
	for i = 0 to t-1 do
		try
		if arr.(i) + 1 <> arr.(i+1) then (print_int (arr.(i) + 1); exit 0)
		with _ -> (print_int (arr.(i) + 1); exit 0)
	done;;

let t = read_int() in
let arr = Array.append [|0|] (Array.map int_of_string (
	Array.of_list (Str.split (Str.regexp " ") (read_line()))
)) in
let _ = Array.sort compare arr in
	for i = 0 to t-1 do
		try
		if arr.(i) + 1 <> arr.(i+1) then (print_int (arr.(i) + 1); exit 0)
		with _ -> (print_int (arr.(i) + 1); exit 0)
	done;;


Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $$$1$$$. If he manages to finish the level successfully then the number of clears increases by $$$1$$$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats $$$n$$$ times and wrote down $$$n$$$ pairs of integers — $$$(p_1, c_1), (p_2, c_2), \dots, (p_n, c_n)$$$, where $$$p_i$$$ is the number of plays at the $$$i$$$-th moment of time and $$$c_i$$$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.

The first line contains a single integer $$$T$$$ $$$(1 \le T \le 500)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of moments of time Polycarp peeked at the stats. Each of the next $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \le p_i, c_i \le 1000$$$) — the number of plays and the number of clears of the level at the $$$i$$$-th moment of time. Note that the stats are given in chronological order.

For each test case print a single line. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES". Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.The second test case is a nice example of a Super Expert level.In the third test case the number of plays decreased, which is impossible.The fourth test case is probably an auto level with a single jump over the spike.In the fifth test case the number of clears decreased, which is also impossible.Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;
let show_string s = print_string s;;

let t = scan_int ();;
for x = 1 to t do
	let n = scan_int () in
	let player = ref 0 in
	let clear = ref 0 in
	let test = ref true in
	for i = 0 to n-1 do
		let p, c = scan_int_pair () in
		if !player > p  || !clear > c || (p - !player) < (c - !clear) then
			test := false;
		player := p; clear := c
	done;
	if !test then show_string "YES\n" else show_string "NO\n"
done;;

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let a2 = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' &&	(pi' - pi) >= (ci' - ci)
    ) in
    let a1 = forall 0 (n-1) (fun i -> let (pi,ci) = stats.(i) in ci <= pi) in
    if a1 && a2 then printf "YES\n" else printf "NO\n"
  done

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let answer = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi' &&
	(pi' - pi) >= (ci' - ci')
    ) in
    if answer then printf "YES\n" else printf "NO\n"
  done

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let answer = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi'
    ) in
    if answer then printf "YES\n" else printf "NO\n"
  done

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let answer = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi' &&
	(pi' - pi) >= (ci' - ci)
    ) in
    if answer then printf "YES\n" else printf "NO\n"
  done


You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations:   Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation:   $$$x = 0$$$, $$$y = 6$$$;  $$$x = 0$$$, $$$y = 8$$$;  $$$x = -1$$$, $$$y = 7$$$;  $$$x = 1$$$, $$$y = 7$$$.   Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation:   $$$x = -1$$$, $$$y = 6$$$;  $$$x = 1$$$, $$$y = 8$$$.  Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^9$$$). The second line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print one integer — the minimum amount of dollars you have to spend.

NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend $$$391 + 555 + 391 = 1337$$$ dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money.

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

let delta x y = Int64.abs (Int64.sub x y);;

for i=1 to nbTests
do
   let x = Int64.of_int(Scanf.scanf " %d" (fun x -> x)) in
   let y = Int64.of_int(Scanf.scanf " %d" (fun x -> x)) in
   let a = Int64.of_int(Scanf.scanf " %d" (fun x -> x)) in
   let b = min (Int64.mul 2L a) (Int64.of_int (Scanf.scanf " %d" (fun x -> x))) in

   let enleve = Int64.add (max 0L (min x y)) (min 0L (max x y)) in

   let ans = 0L in
   let ans = Int64.add ans (Int64.mul b (delta enleve 0L)) in
   let ans = Int64.add ans (Int64.mul a (delta x enleve)) in
   let ans = Int64.add ans (Int64.mul a (delta y enleve)) in

   print_string (Int64.to_string ans);
   print_newline ()
done;;

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

for i=1 to nbTests
do
   let x = Scanf.scanf " %d" (fun x -> x) in
   let y = Scanf.scanf " %d" (fun x -> x) in
   let a = Scanf.scanf " %d" (fun x -> x) in
   let b = min (2 * a) (Scanf.scanf " %d" (fun x -> x)) in

   let enleve = (max 0 (min x y)) + (min 0 (max x y)) in

   print_int (b * (abs enleve) + a * abs(x - enleve) + a * abs(y - enleve));
   print_newline ()
done;;


Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai  ≤  bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!

The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola cans. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — volume of remaining cola in cans. The third line contains n space-separated integers that b1, b2, ..., bn (ai ≤ bi ≤ 109) — capacities of the cans.

Print "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteIn the first sample, there are already 2 cans, so the answer is "YES".

open Printf
open Scanf

let ( ++ ) a b = Int64.add a b
let short x = Int64.to_int x

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

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

let () =
  let n = read_long () |> short in
  let can = Array.init n (fun i -> (read_long(), 0L)) in

  for i=0 to n-1 do
    can.(i) <- (fst can.(i), read_long())
  done;

  let total = sum 0 (n-1) (fun i -> fst can.(i)) in

  Array.sort (fun a b -> - compare (snd a) (snd b)) can;

  let canvol = (snd can.(0)) ++ (snd can.(1)) in

  if total <= canvol then printf "YES\n" else printf "NO\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 sum i j f = fold i j (fun i a -> (f i) + a) 0
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_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let n = read_int () in
  let can = Array.init n (fun i -> (read_int(), 0)) in

  for i=0 to n-1 do
    can.(i) <- (fst can.(i), read_int())
  done;

  let total = sum 0 (n-1) (fun i -> fst can.(i)) in

  Array.sort (fun a b -> - compare (snd a) (snd b)) can;

  let canvol = (snd can.(0)) + (snd can.(1)) in

  if total <= canvol then printf "YES\n" else printf "NO\n"


This is an interactive problem.Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.Let's define $$$x$$$ as the distance to Mars. Unfortunately, Natasha does not know $$$x$$$. But it is known that $$$1 \le x \le m$$$, where Natasha knows the number $$$m$$$. Besides, $$$x$$$ and $$$m$$$ are positive integers.Natasha can ask the rocket questions. Every question is an integer $$$y$$$ ($$$1 \le y \le m$$$). The correct answer to the question is $$$-1$$$, if $$$x<y$$$, $$$0$$$, if $$$x=y$$$, and $$$1$$$, if $$$x>y$$$. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $$$t$$$, then, if the rocket answers this question correctly, then it will answer $$$t$$$, otherwise it will answer $$$-t$$$.In addition, the rocket has a sequence $$$p$$$ of length $$$n$$$. Each element of the sequence is either $$$0$$$ or $$$1$$$. The rocket processes this sequence in the cyclic order, that is $$$1$$$-st element, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$\ldots$$$. If the current element is $$$1$$$, the rocket answers correctly, if $$$0$$$ — lies. Natasha doesn't know the sequence $$$p$$$, but she knows its length — $$$n$$$.You can ask the rocket no more than $$$60$$$ questions.Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.Your solution will not be accepted, if it does not receive an answer $$$0$$$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).

The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \le m \le 10^9$$$, $$$1 \le n \le 30$$$) — the maximum distance to Mars and the number of elements in the sequence $$$p$$$.

NoteIn the example, hacking would look like this:5 2 31 0This means that the current distance to Mars is equal to $$$3$$$, Natasha knows that it does not exceed $$$5$$$, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...Really:on the first query ($$$1$$$) the correct answer is $$$1$$$, the rocket answered correctly: $$$1$$$;on the second query ($$$2$$$) the correct answer is $$$1$$$, the rocket answered incorrectly: $$$-1$$$;on the third query ($$$4$$$) the correct answer is $$$-1$$$, the rocket answered correctly: $$$-1$$$;on the fourth query ($$$5$$$) the correct answer is $$$-1$$$, the rocket answered incorrectly: $$$1$$$;on the fifth query ($$$3$$$) the correct and incorrect answer is $$$0$$$.

module MInt32 = struct
  let (+) = Int32.add
  let (-) = Int32.sub
  let ( * ) = Int32.mul
  let (/) = Int32.div
  let to_int = Int32.to_int
  let of_int = Int32.of_int
end

type ('a, 'b) result =
  | Left of 'a
  | Right of 'b

let int_bisearch_first_satisfying
    (callback: int -> bool) ((l, r): int * int): int option =
  let rec f l r =
    if l = r then if callback l then Some l else None
    else
      let m = MInt32.(to_int ((of_int l + of_int r) / 2l)) in
      if callback m then f l m else f (m + 1) r
  in f l r

let print_read (n: int): int =
  n |> string_of_int |> print_endline; flush stdout;
  Scanf.scanf " %d" (fun x -> x)

let determine_p (n: int): (int, bool array) result =
  let ret = Array.make n false in
  let rec f i =
    if i = n then false
    else (
      let t = print_read 1 in
      if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))
    )
  in if f 0 then Left 1 else Right ret

exception Found

let _ =
  (* m - max. distance *) (* n - #p *)
  let m, n = Scanf.scanf " %d %d" (fun x y -> x, y) in
  match determine_p n with
  | Left i -> ()
  | Right p ->
    try
      (* ATTENTION: use a counter *)
      let i = ref (-1) in
      let f x =
        i := !i + 1;
        match abs (print_read x + if p.(!i mod n) then 1 else -1) with
        | 0 -> true | 2 -> false | _ -> raise Found
      in int_bisearch_first_satisfying f (0, m) |> ignore
    with Found -> ()

type ('a, 'b) result =
  | Left of 'a
  | Right of 'b

let int_bisearch_first_satisfying
    (callback: int -> bool) ((l, r): int * int): int option =
  let rec f l r =
    if l = r then if callback l then Some l else None
    else let m = (l + r) / 2 in if callback m then f l m else f (m + 1) r
  in f l r

let print_read (n: int): int =
  n |> string_of_int |> print_endline; flush stdout;
  Scanf.scanf " %d" (fun x -> x)

let determine_p (n: int): (int, bool array) result =
  let ret = Array.make n false in
  let rec f i =
    if i = n then false
    else (
      let t = print_read 1 in
      if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))
    )
  in if f 0 then Left 1 else Right ret

exception Found

let _ =
  (* m - max. distance *) (* n - #p *)
  let m, n = Scanf.scanf " %d %d" (fun x y -> x, y) in
  match determine_p n with
  | Left i -> ()
  | Right p ->
    try
      (* ATTENTION: use a counter *)
      let i = ref (-1) in
      let f x =
        i := !i + 1;
        match abs (print_read x + if p.(!i mod n) then 1 else -1) with
        | 0 -> true | 2 -> false | _ -> raise Found
      in int_bisearch_first_satisfying f (0, m) |> ignore
    with Found -> ()

type ('a, 'b) result =
  | Left of 'a
  | Right of 'b

let int_bisearch_first_satisfying
    (callback: int -> bool) ((l, r): int * int): int option =
  let rec f l r =
    if l = r then if callback l then Some l else None
    else let m = (l + r) / 2 in if callback m then f l m else f (m + 1) r
  in f l r

let print_read (n: int): int =
  n |> string_of_int |> print_endline; flush stdout;
  Scanf.scanf " %d" (fun x -> x)

let determine_p (n: int): (int, bool array) result =
  let ret = Array.make n false in
  let rec f i =
    if i = n then false
    else (
      let t = print_read 0 in
      if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))
    )
  in if f 0 then Left 0 else Right ret

exception Found

let _ =
  (* m - max. distance *) (* n - #p *)
  let m, n = Scanf.scanf " %d %d" (fun x y -> x, y) in
  match determine_p n with
  | Left i -> ()
  | Right p ->
    try
      let f i =
        match abs (print_read i + if p.(i mod n) then 1 else -1) with
        | 0 -> true | 2 -> false | _ -> raise Found
      in int_bisearch_first_satisfying f (0, m) |> ignore
    with Found -> ()

type ('a, 'b) result =
  | Left of 'a
  | Right of 'b

let int_bisearch_first_satisfying
    (callback: int -> bool) ((l, r): int * int): int option =
  let rec f l r =
    if l = r then if callback l then Some l else None
    else let m = (l + r) / 2 in if callback m then f l m else f (m + 1) r
  in f l r

let print_read (n: int): int =
  n |> string_of_int |> print_endline; flush stdout;
  Scanf.scanf " %d" (fun x -> x)

let determine_p (n: int): (int, bool array) result =
  let ret = Array.make n false in
  let rec f i =
    if i = n then false
    else (
      let t = print_read 1 in
      if t = 0 then true else (ret.(i) <- t = 1; f (i + 1))
    )
  in if f 0 then Left 1 else Right ret

exception Found

let _ =
  (* m - max. distance *) (* n - #p *)
  let m, n = Scanf.scanf " %d %d" (fun x y -> x, y) in
  match determine_p n with
  | Left i -> ()
  | Right p ->
    try
      let f i =
        match abs (print_read i + if p.(i mod n) then 1 else -1) with
        | 0 -> true | 2 -> false | _ -> raise Found
      in int_bisearch_first_satisfying f (0, m) |> ignore
    with Found -> ()


You are given a following process. There is a platform with $$$n$$$ columns. $$$1 \times 1$$$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $$$n$$$ columns have at least one square in them, the bottom row is being removed. You will receive $$$1$$$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.

The first line of input contain 2 integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the length of the platform and the number of the squares. The next line contain $$$m$$$ integer numbers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le n$$$) — column in which $$$i$$$-th square will appear.

Print one integer — the amount of points you will receive.

NoteIn the sample case the answer will be equal to $$$2$$$ because after the appearing of $$$6$$$-th square will be removed one row (counts of the squares on the platform will look like $$$[2~ 3~ 1]$$$, and after removing one row will be $$$[1~ 2~ 0]$$$).After the appearing of $$$9$$$-th square counts will be $$$[2~ 3~ 1]$$$, and after removing one row it will look like $$$[1~ 2~ 0]$$$.So the answer will be equal to $$$2$$$.

(* Codeforces 962 A Equator - done *)

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

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

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

let rec count_vals cnts l = match l with
| [] -> ()
| h :: t ->
	let _ = cnts.(h - 1) <- (cnts.(h - 1) + 1) in
	count_vals cnts t;;

let rec minimum mn l = match l with
| [] -> mn
| h :: t ->
	let mn1 = if mn < h then mn else h in
	minimum mn1 t;;

let main() =
	let n = gr () in
	let m = gr () in
	let c = readlist m [] in
	let cnta = Array.make n 0 in
	let _ = count_vals cnta c in
	let cntl= Array.to_list cnta in
	let minv = minimum 1002 cntl in
	begin
		print_int minv;
		print_string "\n"
	end;;

main();;


In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing".For a long time our heroine had been searching the sea for crucians, but a great misfortune happened. Her teeth started to ache, and she had to see the local dentist, lobster Ashot. As a professional, Ashot quickly relieved Valerie from her toothache. Moreover, he managed to determine the cause of Valerie's developing caries (for what he was later nicknamed Cap).It turned that Valerie eats too many crucians. To help Valerie avoid further reoccurrence of toothache, Ashot found for each Valerie's tooth its residual viability. Residual viability of a tooth is a value equal to the amount of crucians that Valerie can eat with this tooth. Every time Valerie eats a crucian, viability of all the teeth used for it will decrease by one. When the viability of at least one tooth becomes negative, the shark will have to see the dentist again. Unhappy, Valerie came back home, where a portion of crucians was waiting for her. For sure, the shark couldn't say no to her favourite meal, but she had no desire to go back to the dentist. That's why she decided to eat the maximum amount of crucians from the portion but so that the viability of no tooth becomes negative. As Valerie is not good at mathematics, she asked you to help her to find out the total amount of crucians that she can consume for dinner.We should remind you that while eating one crucian Valerie uses exactly one row of teeth and the viability of each tooth from this row decreases by one.

The first line contains three integers n, m, k (1 ≤ m ≤ n ≤ 1000, 0 ≤ k ≤ 106) — total amount of Valerie's teeth, amount of tooth rows and amount of crucians in Valerie's portion for dinner. Then follow n lines, each containing two integers: r (1 ≤ r ≤ m) — index of the row, where belongs the corresponding tooth, and c (0 ≤ c ≤ 106) — its residual viability. It's guaranteed that each tooth row has positive amount of teeth.

In the first line output the maximum amount of crucians that Valerie can consume for dinner.

print_int (Scanf.scanf "%d %d %d\n" (fun n m k ->
	let ryads = Array.make m max_int in
	let _ = for i = 1 to n do
		Scanf.scanf "%d %d\n" (fun r z ->
			if z < ryads.(r-1) then (ryads.(r-1) <- z)
		)
	done in
	min k (Array.fold_left (+) 0 ryads)
));;


There is a river of width $$$n$$$. The left bank of the river is cell $$$0$$$ and the right bank is cell $$$n + 1$$$ (more formally, the river can be represented as a sequence of $$$n + 2$$$ cells numbered from $$$0$$$ to $$$n + 1$$$). There are also $$$m$$$ wooden platforms on a river, the $$$i$$$-th platform has length $$$c_i$$$ (so the $$$i$$$-th platform takes $$$c_i$$$ consecutive cells of the river). It is guaranteed that the sum of lengths of platforms does not exceed $$$n$$$.You are standing at $$$0$$$ and want to reach $$$n+1$$$ somehow. If you are standing at the position $$$x$$$, you can jump to any position in the range $$$[x + 1; x + d]$$$. However you don't really like the water so you can jump only to such cells that belong to some wooden platform. For example, if $$$d=1$$$, you can jump only to the next position (if it belongs to the wooden platform). You can assume that cells $$$0$$$ and $$$n+1$$$ belong to wooden platforms.You want to know if it is possible to reach $$$n+1$$$ from $$$0$$$ if you can move any platform to the left or to the right arbitrary number of times (possibly, zero) as long as they do not intersect each other (but two platforms can touch each other). It also means that you cannot change the relative order of platforms.Note that you should move platforms until you start jumping (in other words, you first move the platforms and then start jumping).For example, if $$$n=7$$$, $$$m=3$$$, $$$d=2$$$ and $$$c = [1, 2, 1]$$$, then one of the ways to reach $$$8$$$ from $$$0$$$ is follow:    The first example: $$$n=7$$$.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$d$$$ ($$$1 \le n, m, d \le 1000, m \le n$$$) — the width of the river, the number of platforms and the maximum distance of your jump, correspondingly. The second line of the input contains $$$m$$$ integers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le n, \sum\limits_{i=1}^{m} c_i \le n$$$), where $$$c_i$$$ is the length of the $$$i$$$-th platform.

If it is impossible to reach $$$n+1$$$ from $$$0$$$, print NO in the first line. Otherwise, print YES in the first line and the array $$$a$$$ of length $$$n$$$ in the second line — the sequence of river cells (excluding cell $$$0$$$ and cell $$$n + 1$$$). If the cell $$$i$$$ does not belong to any platform, $$$a_i$$$ should be $$$0$$$. Otherwise, it should be equal to the index of the platform ($$$1$$$-indexed, platforms are numbered from $$$1$$$ to $$$m$$$ in order of input) to which the cell $$$i$$$ belongs. Note that all $$$a_i$$$ equal to $$$1$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_1$$$, all $$$a_i$$$ equal to $$$2$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_2$$$, ..., all $$$a_i$$$ equal to $$$m$$$ should form a contiguous subsegment of the array $$$a$$$ of length $$$c_m$$$. The leftmost position of $$$2$$$ in $$$a$$$ should be greater than the rightmost position of $$$1$$$, the leftmost position of $$$3$$$ in $$$a$$$ should be greater than the rightmost position of $$$2$$$, ..., the leftmost position of $$$m$$$ in $$$a$$$ should be greater than the rightmost position of $$$m-1$$$. See example outputs for better understanding.

NoteConsider the first example: the answer is $$$[0, 1, 0, 2, 2, 0, 3]$$$. The sequence of jumps you perform is $$$0 \rightarrow 2 \rightarrow 4 \rightarrow 5 \rightarrow 7 \rightarrow 8$$$.Consider the second example: it does not matter how to place the platform because you always can jump from $$$0$$$ to $$$11$$$.Consider the third example: the answer is $$$[0, 0, 0, 0, 1, 1, 0, 0, 0, 0]$$$. The sequence of jumps you perform is $$$0 \rightarrow 5 \rightarrow 6 \rightarrow 11$$$.

open Printf

let print_list l ~f =
  let rec print_list' l to_string acc =
      match l with
      | [] -> acc ^ ""
      | hd::[] -> acc ^ sprintf "%s" (to_string hd)
      | hd::tl -> print_list' tl to_string (acc ^ sprintf "%s " (to_string hd));
  in
  print_list' l f ""

type river = {
    width: int;
    platforms: int list;
    tot_len: int
  }

let rec seq f t =
  if t < f then [1] else
  if f = t then t::[] else t::(seq f (t-1))

exception One of int list

let t river j = seq 1 (min j (river.width - river.tot_len))

let rec solve_one' river jump_dist sol trys=
  match river.platforms, trys with
  | [], _ -> if river.width >= 0 && river.width < jump_dist then Some sol else None
  | hd::tl, [] -> None
  | phd::ptl, thd::ttl -> let new_river ={width=river.width-((thd-1)+phd); platforms=ptl; tot_len=river.tot_len-phd} in
    solve_one' new_river jump_dist (thd::sol) (t new_river jump_dist)

let solve_one river jump_dist =
  solve_one' river jump_dist [] (t river jump_dist)

let rec solve_all' river jump_dist sol acc =
  match river.platforms with
  | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc
  | hd::tl -> List.concat (List.map (fun x -> solve_all' {width=river.width-((x-1)+hd); platforms=tl; tot_len=river.tot_len-x} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))

let solve_all river jump_dist = solve_all' river jump_dist [] []

let print_sol river sol =
  let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in
  let rec sol_list river sol cur_platform acc =
    match river.platforms, sol with
    | [], [] -> List.concat (acc @ [repeat 0 river.width])
    | plat::plats, cur::next ->  sol_list {width=river.width - (cur-1) - plat; platforms=plats; tot_len=0} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])
    | _, _ -> failwith "CANNOT HAPPEN"
  in
  print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))

let solve_input () =
  let open Str in
  let fst = split (regexp " ") (input_line stdin) in
  let snd = split (regexp " ") (input_line stdin) in
  let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in
  let platforms = List.map int_of_string snd in
  let river = {width=width;platforms=platforms;tot_len=List.fold_left (+) 0 platforms} in
  let sols = solve_one river jump in
  match sols with
  | Some v -> print_endline "YES"; print_sol river v
  | None -> print_endline "NO"

let sum l = List.fold_left (+) 0 l
let () =
  solve_input ()
  (* let platforms = [3;6;3;4;3;5;3;5;5;5;3;1;3;8;2;4;4;5;3;2] in
   * let river = {width=1000; platforms=platforms; tot_len=(sum platforms)}
   * and jump = 8 in
   * try
   *   let sol = solve_one river jump in
   *   match sol with
   *   | Some v -> print_endline "YES"; print_sol river v
   *   | None -> print_endline "NO"
   * with _ -> () *)

open Printf

let print_list l ~f =
  let rec print_list' l to_string acc =
      match l with
      | [] -> acc ^ ""
      | hd::[] -> acc ^ sprintf "%s" (to_string hd)
      | hd::tl -> print_list' tl to_string (acc ^ sprintf "%s " (to_string hd));
  in
  print_list' l f ""

type river = {
    width: int;
    platforms: int list;
    tot_len: int
  }

let rec seq f t =
  if f = t then f::[] else f::(seq (f+1) t)

exception One of int list

let t river j = seq 1 (min j (river.width - river.tot_len))

let rec solve_one' river jump_dist sol trys=
  match river.platforms, trys with
  | [], _ -> if river.width >= 0 && river.width < jump_dist then Some sol else None
  | hd::tl, [] -> None
  | phd::ptl, thd::ttl -> let new_river ={width=river.width-((thd-1)+phd); platforms=ptl; tot_len=river.tot_len-phd} in
    match solve_one' new_river jump_dist (thd::sol) (t new_river jump_dist) with
    | Some v -> Some v
    | None -> solve_one' river jump_dist sol ttl

let solve_one river jump_dist = solve_one' river jump_dist [] (t river jump_dist)

let rec solve_all' river jump_dist sol acc =
  match river.platforms with
  | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc
  | hd::tl -> List.concat (List.map (fun x -> solve_all' {width=river.width-((x-1)+hd); platforms=tl; tot_len=river.tot_len-x} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))

let solve_all river jump_dist = solve_all' river jump_dist [] []

let print_sol river sol =
  let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in
  let rec sol_list river sol cur_platform acc =
    match river.platforms, sol with
    | [], [] -> List.concat (acc @ [repeat 0 river.width])
    | plat::plats, cur::next ->  sol_list {width=river.width - (cur-1) - plat; platforms=plats; tot_len=0} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])
    | _, _ -> failwith "CANNOT HAPPEN"
  in
  print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))

let solve_input () =
  let open Str in
  let fst = split (regexp " ") (input_line stdin) in
  let snd = split (regexp " ") (input_line stdin) in
  let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in
  let platforms = List.map int_of_string snd in
  let river = {width=width;platforms=platforms;tot_len=List.fold_left (+) 0 platforms} in
  let sols = solve_one river jump in
  match sols with
  | Some v -> print_sol river v
  | None -> print_endline "NO"

let () =
  solve_input ()
  (* let river = {width=40; platforms=[1;2;1;10;5;15;1]}
   * and jump = 3 in
   * try
   *   let l = solve_all river jump in
   *   List.iter (fun x -> print_sol river x) l
   * with _ -> () *)

open Printf

let print_list l ~f =
  let rec print_list' l to_string acc =
      match l with
      | [] -> acc ^ "]"
      | hd::[] -> acc ^ sprintf "%s]" (to_string hd)
      | hd::tl -> print_list' tl to_string (acc ^ sprintf "%s " (to_string hd));
  in
  print_list' l f "["

type river = {
    width: int;
    platforms: int list
  }

let rec seq f t =
  if f = t then f::[] else f::(seq (f+1) t)

let rec solve' river jump_dist sol acc =
  match river.platforms with
  | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc
  | hd::tl -> List.concat (List.map (fun x -> solve' {width=river.width-((x-1)+hd); platforms=tl} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))

let print_sol river sol =
  let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in
  let rec sol_list river sol cur_platform acc =
    match river.platforms, sol with
    | [], [] -> List.concat (acc @ [repeat 0 river.width])
    | plat::plats, cur::next ->  sol_list {width=river.width - (cur-1) - plat; platforms=plats} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])
    | _, _ -> failwith "CANNOT HAPPEN"
  in
  print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))

let solve river jump_dist =
  solve' river jump_dist [] []

let solve_all () =
  let open Str in
  let fst = split (regexp " ") (input_line stdin) in
  let snd = split (regexp " ") (input_line stdin) in
  let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in
  let platforms = List.map int_of_string snd in
  let river = {width=width;platforms=platforms} in
  let sol = solve river jump in
  match sol with
  | [] -> print_endline "NO"
  | hd::tl -> print_sol river hd

let () =
  solve_all ()
  (* let river = {width=100; platforms=[1;2;1;10;5;15;1]}
   * and jump = 10 in
   * try
   *   let l = solve river jump in
   *   List.iter (fun x -> print_sol river x) l
   * with _ -> () *)

open Printf

let print_list l ~f =
  let rec print_list' l to_string acc =
      match l with
      | [] -> acc ^ ""
      | hd::[] -> acc ^ sprintf "%s" (to_string hd)
      | hd::tl -> print_list' tl to_string (acc ^ sprintf "%s " (to_string hd));
  in
  print_list' l f ""

type river = {
    width: int;
    platforms: int list
  }

let rec seq f t =
  if f = t then f::[] else f::(seq (f+1) t)

let rec solve' river jump_dist sol acc =
  match river.platforms with
  | [] -> if river.width >= 0 && river.width < jump_dist then sol::acc else acc
  | hd::tl -> List.concat (List.map (fun x -> solve' {width=river.width-((x-1)+hd); platforms=tl} jump_dist (x::sol) acc) (seq 1 (min river.width jump_dist)))

let print_sol river sol =
  let rec repeat i n = if n = 0 then [] else i :: repeat i (n-1) in
  let rec sol_list river sol cur_platform acc =
    match river.platforms, sol with
    | [], [] -> List.concat (acc @ [repeat 0 river.width])
    | plat::plats, cur::next ->  sol_list {width=river.width - (cur-1) - plat; platforms=plats} next (cur_platform+1) (acc @[repeat 0 (cur-1); repeat cur_platform plat])
    | _, _ -> failwith "CANNOT HAPPEN"
  in
  print_endline (print_list ~f:string_of_int (sol_list river sol 1 []))

let solve river jump_dist =
  solve' river jump_dist [] []

let solve_all () =
  let open Str in
  let fst = split (regexp " ") (input_line stdin) in
  let snd = split (regexp " ") (input_line stdin) in
  let (width,jump) = List.((int_of_string (hd fst), int_of_string (hd (tl (tl fst))))) in
  let platforms = List.map int_of_string snd in
  let river = {width=width;platforms=platforms} in
  let sol = solve river jump in
  match sol with
  | [] -> print_endline "NO"
  | hd::tl -> print_sol river hd

let () =
  solve_all ()
  (* let river = {width=100; platforms=[1;2;1;10;5;15;1]}
   * and jump = 10 in
   * try
   *   let l = solve river jump in
   *   List.iter (fun x -> print_sol river x) l
   * with _ -> () *)