You are given n points on a line with their coordinates xi. Find the point x so the sum of distances to the given points is minimal.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of points on the line. The second line contains n integers xi ( - 109 ≤ xi ≤ 109) — the coordinates of the given n points.

Print the only integer x — the position of the optimal point on the line. If there are several optimal points print the position of the leftmost one. It is guaranteed that the answer is always the integer.

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

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

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

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


A sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Given two integers $$$n$$$ and $$$k$$$, construct a permutation $$$a$$$ of numbers from $$$1$$$ to $$$n$$$ which has exactly $$$k$$$ peaks. An index $$$i$$$ of an array $$$a$$$ of size $$$n$$$ is said to be a peak if $$$1 < i < n$$$ and $$$a_i \gt a_{i-1}$$$ and $$$a_i \gt a_{i+1}$$$. If such permutation is not possible, then print $$$-1$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Then $$$t$$$ lines follow, each containing two space-separated integers $$$n$$$ ($$$1 \leq n \leq 100$$$) and $$$k$$$ ($$$0 \leq k \leq n$$$) — the length of an array and the required number of peaks.

Output $$$t$$$ lines. For each test case, if there is no permutation with given length and number of peaks, then print $$$-1$$$. Otherwise print a line containing $$$n$$$ space-separated integers which forms a permutation of numbers from $$$1$$$ to $$$n$$$ and contains exactly $$$k$$$ peaks.  If there are multiple answers, print any.

NoteIn the second test case of the example, we have array $$$a = [2,4,1,5,3]$$$. Here, indices $$$i=2$$$ and $$$i=4$$$ are the peaks of the array. This is because $$$(a_{2} \gt a_{1} $$$, $$$a_{2} \gt a_{3})$$$ and $$$(a_{4} \gt a_{3}$$$, $$$a_{4} \gt a_{5})$$$.

open Printf
open Scanf

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,k) = read_pair() in
    match (n,k) with
      | (1,0) -> printf "1\n"
      | (2,0) -> printf "1 2\n"
      | (2,_) | (1,_) -> printf "-1\n"
      | _ -> (
	let m = (n-1)/2 in
	if k > m then printf "-1\n" else (
	  let p = Array.init n (fun i -> i+1) in
	  let swap i j =
	    let (pi,pj) = (p.(i),p.(j)) in
	    p.(i) <- pj;
	    p.(j) <- pi
	  in

	  for l = 0 to k-1 do
	    let j = n-1 - 2*l in
	    let i = j-1 in
	    swap i j
	  done;
	  for i=0 to n-1 do
	    printf "%d " p.(i)
	  done;
	  print_newline()
	)
      )
  done

open Printf
open Scanf

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,k) = read_pair() in
    match (n,k) with
      | (1,0) -> printf "1\n"
      | (2,0) -> printf "1 2\n"
      | (2,_) | (1,_) -> printf "-1\n"
      | _ -> (
	let m = n/2 in
	if k > m then printf "-1\n" else (
	  let p = Array.init n (fun i -> i+1) in
	  let swap i j =
	    let (pi,pj) = (p.(i),p.(j)) in
	    p.(i) <- pj;
	    p.(j) <- pi
	  in

	  for l = 0 to k-1 do
	    let j = n-1 - 2*l in
	    let i = j-1 in
	    swap i j
	  done;
	  for i=0 to n-1 do
	    printf "%d " p.(i)
	  done;
	  print_newline()
	)
      )
  done


Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.

The first line contains the single integer n (1 ≤ n ≤ 1000) — the number of contests where the coder participated. The next line contains n space-separated non-negative integer numbers — they are the points which the coder has earned. The points are given in the chronological order. All points do not exceed 10000.

Print the single number — the number of amazing performances the coder has had during his whole history of participating in the contests.

NoteIn the first sample the performances number 2 and 3 are amazing.In the second sample the performances number 2, 4, 9 and 10 are amazing.

let rdint =
    let l = ref 0 in
    let i = ref 0 in
    let s = String.create 65536 in
    let refill () =
        let n = input stdin s 0 65536 in
        i := 0;
        l := n in
    refill ();

    fun () ->
        let rec loop2 j k t f =
            let fin j t f =
                let _ = i := j in
                t * f in

            if j = k then (
                let _ = refill () in
                if !l > 0 then loop2 !i !l t f else fin j t f
            ) else if s.[j] >= '0' && s.[j] <= '9' then
                loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f
            else fin j t f in

        let rec loop1 j k =
            if j = k then (
                let _ = refill () in
                if !l > 0 then loop1 !i !l else 0
            ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)
            else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1
            else loop1 (j + 1) k in
        loop1 !i !l

let main () =
    let rec loop i min0 max0 acc =
        if i = 0 then Printf.printf "%d\n" acc else
            let k = rdint () in
            let acc = if k < min0 || k > max0 then acc + 1 else acc in
            loop (i - 1) (min min0 k) (max max0 k) acc
    in
    let n = rdint() in
    let s = rdint() in
    loop (n - 1) s s 0
;;
main ()

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

let solve () =
    let n = read () in
    let first = read () in
    let rec loop i count max min =
        if i < n
        then
            let score = read () in
            if score < min
            then
                loop (i + 1) (count + 1) max score
            else
                if score > max
                then
                    loop (i + 1) (count + 1) score min
                else
                    loop (i + 1) count max min
        else
            count
    in loop 1 0 first first

let print result = Printf.printf "%d\n" result
let () = print (solve ())

let read_int () = Scanf.scanf " %d" (fun x -> x) in
let n = read_int() in
  let f = read_int() in
  let mmin = ref f and mmax = ref f in
  let count = ref 0 in
  for i = 1 to n-1 do
  let next = read_int() in
  if next > !mmax then begin
  mmax := next;
  incr count;
  end else if next < !mmin then begin
  mmin := next;
  incr count;
  end;
  done;
  print_int !count;
  print_newline();;


This is an interactive problem. In the output section below you will see the information about flushing the output.Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.Integer x > 1 is called prime if it has exactly two distinct divisors, 1 and x. If integer x > 1 is not prime, it's called composite.You can ask up to 20 queries about divisors of the hidden number. In each query you should print an integer from interval [2, 100]. The system will answer "yes" if your integer is a divisor of the hidden number. Otherwise, the answer will be "no".For example, if the hidden number is 14 then the system will answer "yes" only if you print 2, 7 or 14.When you are done asking queries, print "prime" or "composite" and terminate your program.You will get the Wrong Answer verdict if you ask more than 20 queries, or if you print an integer not from the range [2, 100]. Also, you will get the Wrong Answer verdict if the printed answer isn't correct.You will get the Idleness Limit Exceeded verdict if you don't print anything (but you should) or if you forget about flushing the output (more info below).

After each query you should read one string from the input. It will be "yes" if the printed integer is a divisor of the hidden number, and "no" otherwise.

Up to 20 times you can ask a query — print an integer from interval [2, 100] in one line. You have to both print the end-of-line character and flush the output. After flushing you should read a response from the input. In any moment you can print the answer "prime" or "composite" (without the quotes). After that, flush the output and terminate your program. To flush you can use (just after printing an integer and end-of-line):    fflush(stdout) in C++;  System.out.flush() in Java;  stdout.flush() in Python;  flush(output) in Pascal;  See the documentation for other languages.  Hacking. To hack someone, as the input you should print the hidden number — one integer from the interval [2, 100]. Of course, his/her solution won't be able to read the hidden number from the input.

NoteThe hidden number in the first query is 30. In a table below you can see a better form of the provided example of the communication process.The hidden number is divisible by both 2 and 5. Thus, it must be composite. Note that it isn't necessary to know the exact value of the hidden number. In this test, the hidden number is 30.59 is a divisor of the hidden number. In the interval [2, 100] there is only one number with this divisor. The hidden number must be 59, which is prime. Note that the answer is known even after the second query and you could print it then and terminate. Though, it isn't forbidden to ask unnecessary queries (unless you exceed the limit of 20 queries).

(*
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
4
9
25
49

*)

let _ =
   let tab =
[|
3;
5;
7;
11;
13;
17;
19;
23;
29;
31;
37;
41;
43;
47;
4;
9;
25;
49
|] in
   let cpt = ref (Printf.printf "2\n"; flush stdout; Scanf.scanf "%s" (fun i -> if i = "yes" then 1 else 0)) in
      Array.iter (fun i -> Printf.printf "%d\n" i; flush stdout; Scanf.scanf " %s" (fun i -> if i = "yes" then incr cpt)) tab;
      if !cpt < 2
      then Printf.printf "prime"
      else Printf.printf "composite";
      flush stdout

open Printf
open String

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 primes_small = [2; 3; 5; 7]
let primes_big = [11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47]
let squares = [4; 9; 25; 49]

let () =

  let try_a_d d =
    printf "%d\n%!" d;
    let s = read_line() in
    match s with "yes" -> true | "no" -> false | _ -> failwith "bad input"
  in

  let countlist li = List.fold_left (
    fun ac e -> if try_a_d e then ac+1 else ac
  ) 0 li in

  let nsmall = countlist primes_small in
  let nbig = countlist primes_big in
  let nsquares = countlist squares in

  if nsmall = 0 then printf "prime\n"
  else if nsmall >= 2 || nsquares > 0 then printf "composite\n"
  else if nbig = 0 then printf "prime\n"
  else printf "composite\n"

open Printf
open String

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 primes_small = [2; 3; 5; 7]
let primes_big = [11; 13; 17; 19; 23; 29; 31; 37; 41; 43; 47]
let squares = [4; 9; 25; 49]

let () =

  let try_a_d d =
    printf "%d\n%!" d;
    let s = read_line() in
    match s with "yes" -> true | "no" -> false | _ -> failwith "bad input"
  in

  let countlist li = List.fold_left (
    fun ac e -> if try_a_d e then 1 else 0
  ) 0 li in

  let nsmall = countlist primes_small in
  let nbig = countlist primes_big in
  let nsquares = countlist squares in

  if nsmall = 0 then printf "prime\n"
  else if nsmall >= 2 || nsquares > 0 then printf "composite\n"
  else if nbig = 0 then printf "prime\n"
  else printf "composite\n"


A permutation p is an ordered group of numbers p1,   p2,   ...,   pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1,   p2,   ...,   pn.Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: .

The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n).

Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them.

NoteRecord |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0.In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2.In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.

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

let ident x = x ;;
let ident2 x y = (x, y) ;;
let ident3 x y z = (x, y, z) ;;
let ident4 x y z w = (x, y, z, w) ;;
let ident5 x y z w v = (x, y, z, w, v) ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  if skip = 0 then failwith "fold_for";
  let cmp = if skip > 0 then (<) else (>) in

  let rec iter cur acc =
    if not @@ cmp cur max then acc
    else iter (cur + skip) (f acc cur) in

  iter min init
;;

let iter_for ?(skip=1) min max ~f =
  fold_for ~skip:skip min max ~init:() ~f:(fun _ i -> f i)
;;

let input_n n fmt ~f =
  fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf fmt f :: acc) |> List.rev
;;

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

let () =
  let n, k = Scanf.scanf "%d %d" ident2 in
  if k = 0 then begin
    iter_for 1 (2 * n + 1) ~f:(fun i -> Printf.printf "%d " i); print_endline "";
  end else begin
    let set = fold_for 1 (2 * n + 1) ~init:SI.empty ~f:(fun acc i -> SI.add i acc)
      |> SI.remove 1 |> SI.remove (k + 1) in
    Printf.printf "%d %d " (k + 1) 1;
    SI.iter (Printf.printf "%d ") set;
    print_endline ""
  end
;;


The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples:  $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points;  $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points;  $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point;  $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Then the test cases follow. Each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 50$$$, $$$0 \le m \le n$$$, $$$2 \le k \le n$$$, $$$k$$$ is a divisors of $$$n$$$).

For each test case, print one integer — the maximum number of points a player can get for winning the game.

NoteTest cases of the example are described in the statement.

open Printf
open Scanf

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,m) = read_pair() in
    let k = read_int() in
    let win_jokers = min m (n/k) in
    let lose_jokers = (m - win_jokers + k-2)/(k-1) in
    printf "%d\n" (win_jokers - lose_jokers)
  done


Burenka is about to watch the most interesting sporting event of the year — a fighting tournament organized by her friend Tonya.$$$n$$$ athletes participate in the tournament, numbered from $$$1$$$ to $$$n$$$. Burenka determined the strength of the $$$i$$$-th athlete as an integer $$$a_i$$$, where $$$1 \leq a_i \leq n$$$. All the strength values are different, that is, the array $$$a$$$ is a permutation of length $$$n$$$. We know that in a fight, if $$$a_i > a_j$$$, then the $$$i$$$-th participant always wins the $$$j$$$-th.The tournament goes like this: initially, all $$$n$$$ athletes line up in ascending order of their ids, and then there are infinitely many fighting rounds. In each round there is exactly one fight: the first two people in line come out and fight. The winner goes back to the front of the line, and the loser goes to the back.Burenka decided to ask Tonya $$$q$$$ questions. In each question, Burenka asks how many victories the $$$i$$$-th participant gets in the first $$$k$$$ rounds of the competition for some given numbers $$$i$$$ and $$$k$$$. Tonya is not very good at analytics, so he asks you to help him answer all the questions.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq q \leq 10^5$$$) — the number of tournament participants and the number of questions. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the array $$$a$$$, which is a permutation. The next $$$q$$$ lines of a test case contain questions. Each line contains two integers $$$i$$$ and $$$k$$$ ($$$1 \leq i \leq n$$$, $$$1 \leq k \leq 10^9$$$) — the number of the participant and the number of rounds. It is guaranteed that the sum of $$$n$$$ and the sum of $$$q$$$ over all test cases do not exceed $$$10^5$$$.

For each Burenka's question, print a single line containing one integer — the answer to the question.

NoteIn the first test case, the first numbered athlete has the strength of $$$3$$$, in the first round he will defeat the athlete with the number $$$2$$$ and the strength of $$$1$$$, and in the second round, the athlete with the number $$$3$$$ and the strength of $$$2$$$.In the second test case, we list the strengths of the athletes fighting in the first $$$5$$$ fights: $$$1$$$ and $$$3$$$, $$$3$$$ and $$$4$$$, $$$4$$$ and $$$2$$$, $$$4$$$ and $$$1$$$, $$$4$$$ and $$$3$$$. The participant with the number $$$4$$$ in the first $$$5$$$ rounds won $$$0$$$ times (his strength is $$$2$$$). The participant with the number $$$3$$$ has a strength of $$$4$$$ and won $$$1$$$ time in the first two fights by fighting $$$1$$$ time.

module A = Array
let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())

let bin_search ~(cmp : 'a -> 'a -> int) (target:int) (a: 'a array) =
  let l = ref (-1) in
  let r = ref (A.length a) in
  while !l < !r - 1 do
    let m = (!l + !r) / 2 in
    if cmp a.(m) target < 0 then
      l := m
    else
      r := m;
  done;
  !r

let snd (_, y) = y

let safe_get a i =
  if (i < 0) then 0
  else a.(i)

let compute_wins (a: int array) =
  let n = A.length a in
  let res = A.make n 0 in
  let imx = ref 0 in
  for i = 1 to n - 1 do
    if a.(i) > a.(!imx) then begin
      res.(i) <- 1;
      imx := i;
    end else
      res.(!imx) <- res.(!imx) + 1;
  done;
  (!imx, res)

let compute_pref_sums (a: int array) =
  let n = A.length a in
  let res = A.make n 0 in
  res.(0) <- a.(0);
  for i = 1 to n - 1 do
    res.(i) <- res.(i - 1) + a.(i);
  done;
  res

let () =
  let t = read_int () in
  for _ = 1 to t do
    let n = read_int () in
    let q = read_int () in
    let a = read_array read_int n in
    let (pos_mx, wins) = compute_wins a in
    let pref_sums = compute_pref_sums wins in
    for _ = 1 to q do
      let pos = read_int () - 1 in
      let k = read_int () in
      let last_win_pos = bin_search ~cmp:compare k pref_sums in
      if pos > last_win_pos || n = 1 then
        pf "0\n"
      else if pos < last_win_pos then
        begin
          if (last_win_pos = n && pos = pos_mx) then
            pf "%d\n" (k - safe_get pref_sums (pos_mx - 1))
          else
            pf "%d\n" wins.(pos)
        end
      else
        pf "%d\n" (k - safe_get pref_sums (pos - 1));
    done;
  done;


Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.

The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.  The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.

In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.  In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.

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 tab = Array.make (n + 1) 100000 in

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

	for i = 1 to n - 1 do
		if tab.(i) + tab.(i - 1) < m then begin
			wyn := !wyn + abs(m - (tab.(i) + tab.(i - 1)));
			tab.(i) <- m - tab.(i - 1);
		end;
	done;

	printf "%d\n" !wyn;

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

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

let input () =
    let n = read () in
    let k = read () in
    let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in
    (n, k, arr)

let solve (n, k, arr) =
    let rec loop sum i =
        if i < n + 1
        then
            let a = arr.(i - 1) in
            let b = arr.(i) in
            if a + b < k
            then
                (arr.(i) <- k - a;
                let new_sum = sum + (k - a - b) in
                loop new_sum (i + 1))
            else
                loop sum (i + 1)
        else
            (sum, Array.sub arr 1 n)
    in loop 0 1

let print (sum, array) =
    Printf.printf "%d\n" sum;
    Array.iter (Printf.printf "%d ") array;
    Printf.printf "\n"

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

open Printf

let (n1,k1) = Scanf.scanf "%d %d " (fun x y -> (x,y) )

let rec readi n a =
  match n with
  | 0 -> (List.rev a)
  | _ -> let x = Scanf.scanf "%d " (fun x -> x) in
      readi (n-1) (x::a)

let l = readi n1 []

(*
let () =
  List.iter (fun x -> printf "%d " x) l;
  print_endline ""
  *)

let rec f a al ll =
  match ll with
  |[] -> (a, List.rev al)
  |x1::[] -> (a,List.rev (x1::al))
  |x1::(x2::tl) ->
      if x1+x2<k1 then
       (f (a+(k1-x1-x2)) (x1::al) ((k1-x1)::tl))
      else
        (f a (x1::al) (x2::tl))

let (t,al) = f 0 [] l

let () =
  printf "%d\n" t;
  List.iter (fun x -> printf "%d " x) al

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 tab = Array.make (n + 1) 100000 in

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

	for i = 1 to n - 1 do
		if tab.(i) + tab.(i - 1) < m then
			wyn := !wyn + abs(tab.(i) - tab.(i - 1));
		tab.(i) <- m - tab.(i - 1);
	done;

	printf "%d\n" !wyn;

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

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 tab = Array.make (n + 1) 100000 in

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

	for i = 1 to n - 1 do
		if tab.(i) + tab.(i - 1) < m then
			wyn := !wyn + abs(m - (tab.(i) + tab.(i - 1)));
		tab.(i) <- m - tab.(i - 1);
	done;

	printf "%d\n" !wyn;

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

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

let input () =
    let n = read () in
    let k = read () in
    let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in
    (n, k, arr)

let solve (n, k, arr) =
    let rec loop sum i =
        if i < n + 1
        then
            let a = arr.(i - 1) in
            let b = arr.(i) in
            if a + b < k
            then
                (arr.(i) <- k - a;
                let new_sum = sum + (k - a) in
                loop new_sum (i + 1))
            else
                loop sum (i + 1)
        else
            (sum, Array.sub arr 1 n)
    in loop 0 1

let print (sum, array) =
    Printf.printf "%d\n" sum;
    Array.iter (Printf.printf "%d ") array;
    Printf.printf "\n"

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

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

let input () =
    let n = read () in
    let k = read () in
    let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in
    (n, k, arr)

let solve (n, k, arr) =
    let rec loop i =
        if i < n + 1
        then
            let a = arr.(i - 1) in
            let b = arr.(i) in
            if a + b < k
            then
                (arr.(i) <- k - a;
                loop (i + 1))
            else
                loop (i + 1)
        else
            Array.sub arr 1 n
    in loop 1

let print array = Array.iter (Printf.printf "%d ") array;
    Printf.printf "\n"

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

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

let input () =
    let n = read () in
    let k = read () in
    let arr = Array.append (Array.make 1 k) (Array.init n (fun n -> read ())) in
    (n, k, arr)

let solve (n, k, arr) =
    let rec loop sum i =
        if i < n + 1
        then
            let a = arr.(i - 1) in
            let b = arr.(i) in
            if a + b < k
            then
                (arr.(i) <- k - a - b;
                let new_sum = sum + (k - a) in
                loop new_sum (i + 1))
            else
                loop sum (i + 1)
        else
            (sum, Array.sub arr 1 n)
    in loop 0 1

let print (sum, array) =
    Printf.printf "%d\n" sum;
    Array.iter (Printf.printf "%d ") array;
    Printf.printf "\n"

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


Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.

The first line of the input contains three numbers n, m, k (1 ≤ n, m, k ≤ 105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1, a2, ..., an — the initial order of icons from left to right in the menu (from the first to the last one), ai —  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1, b2, ..., bm(1 ≤ bi ≤ n) — the ids of the launched applications in the planned order. One application may be launched multiple times.

Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.

NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let ( ++ ) a b = Int64.add a b
let long x = Int64.of_int x

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

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

  let index = Array.make n 0 in

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

  let swap i =
    if i>0 then (
      let (x,y) = (a.(i), a.(i-1)) in
      index.(x) <- i-1;
      index.(y) <- i;
      a.(i) <- y;
      a.(i-1) <- x;
    )
  in

  let count = ref 0L in

  for j=0 to m-1 do
    let i = index.(b.(j)) in
    swap i;
    count := !count ++ (long (i/k)) ++ 1L
  done;

  printf "%Ld\n" !count

open Printf
open Scanf

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

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

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

  let index = Array.make n 0 in

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

  let swap i =
    if i>0 then (
      let (x,y) = (a.(i), a.(i-1)) in
      index.(x) <- i-1;
      index.(y) <- i;
      a.(i) <- y;
      a.(i-1) <- x;
    )
  in

  let count = ref 0 in

  for j=0 to m-1 do
    let i = index.(b.(j)) in
    swap i;
    count := !count + (i/k) + 1
  done;

  printf "%d\n" !count


Stanley and Megan decided to shop in the "Crossmarket" grocery store, which can be represented as a matrix with $$$n$$$ rows and $$$m$$$ columns. Stanley and Megan can move to an adjacent cell using $$$1$$$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $$$1$$$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.They decided to split up: Stanley will go from the upper-left cell (cell with coordinates $$$(1, 1)$$$) to the lower-right cell (cell with coordinates $$$(n, m)$$$), whilst Megan needs to get from the lower-left cell (cell with coordinates $$$(n, 1)$$$) to the upper-right cell (cell with coordinates $$$(1, m)$$$).What is the minimum total energy needed for them both to do that?Note that they can choose the time they move. Time does not affect energy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The only line in the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$).

For each test case print a single integer on a new line – the answer.

Note  In the first test case they can stick to the following plan:   Megan (red circle) moves to the cell $$$(7, 3)$$$. Then she goes to the cell $$$(1, 3)$$$, and Stanley (blue circle) does the same.  Stanley uses the portal in that cell (cells with portals are grey) to get to the cell $$$(7, 3)$$$. Then he moves to his destination — cell $$$(7, 5)$$$.  Megan also finishes her route and goes to the cell $$$(1, 5)$$$. The total energy spent is $$$(2 + 6) + (2 + 1 + 2) + (2)= 15$$$, which is our final answer.

module A = Array
module L = List
module I = Int64
module B = Big_int

module Opt = struct
  let get = function
    | None -> assert false
    | Some v -> v
end

let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)

let read_long () = sf " %Ld" (fun x -> x)

let read_array read n = A.init n (fun _ -> read ())

let i_bit x i = (x lsr i) land 1

let () =
  let t = read_int () in

  for _ = 1 to t do
    let n = read_int () in
    let m = read_int () in
    if (n = 1 && m = 1) then pf "0\n"
    else if (n = 1 || m = 1) then pf "%d\n" (max n m)
    else pf "%d\n" (n + m - 2 + min n m)
  done;


Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\texttt{A}$$$ except for the last character which is $$$\texttt{B}$$$. The good strings are $$$\texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots$$$. Note that $$$\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times:   Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single string $$$s_2$$$ ($$$1 \leq |s_2| \leq 2 \cdot 10^5$$$). It is guaranteed that $$$s_2$$$ consists of only the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$. It is guaranteed that the sum of $$$|s_2|$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if we can turn $$$s_1$$$ into $$$s_2$$$ after some number of operations, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAB}} \to \texttt{A}\color{red}{\texttt{AB}}\texttt{AB}$$$.In the third test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAAAAAAAB}}$$$.In the second and fourth test case, it can be shown that it is impossible to turn $$$s_1$$$ into $$$s_2$$$.

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

let rec create_char_list input input_length = function
    | 0 -> []
    | n -> (String.get input  (input_length-n))::(create_char_list input input_length (n-1))
;;

type acceptable_char = A | B | AB ;;

let rec run_case a_count = function
    | A, [x] -> false
    | _, [x] -> if (x=='B') then true else false
    | A, x::xs ->
        if (x=='A') then run_case (a_count+1) (AB, xs)
        else false
    | B, x::xs ->
        if (x=='B') then run_case (a_count-1) (A, xs)
        else false
    | AB, x::xs ->
        if (x=='B' && a_count==1) then run_case 0 (A, xs)
        else if (x=='B') then run_case (a_count-1) (AB, xs)
        else run_case (a_count+1) (AB, xs)
;;

let rec run_cases = function
    | 0 -> 0
    | n ->
        let str_case = read_word () in
        let lst_case = create_char_list str_case (String.length str_case) (String.length str_case) in
        if (run_case 0 (A, lst_case)) then begin
            print_string "YES";
            print_newline ();
            run_cases (n-1)
        end
        else begin
            print_string "NO";
            print_newline ();
            run_cases (n-1)
        end
;;

let num_cases = read_int () in
run_cases num_cases;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let str = (input_line stdin) in
  let rep = ref true in
  if str.[0] = 'B' || str.[String.length str -1] = 'A' then rep := false
  else begin
    let tot = ref 0 in
    for j = 0 to String.length str -1 do
      if str.[j] = 'B' then incr tot else decr tot ;
      if !tot > 0 then rep := false
    done;
  end;
  if !rep then print_endline "YES" else print_endline "NO";
done;;

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

let rec create_char_list input input_length = function
    | 0 -> []
    | n -> (String.get input  (input_length-n))::(create_char_list input input_length (n-1))
;;

type acceptable_char = A | B | AB ;;

let rec run_case = function
    | A, [x] -> false
    | _, [x] -> if (x=='B') then true else false
    | A, x::xs -> if (x=='A') then run_case (AB, xs) else false
    | B, x::xs -> if (x=='B') then run_case (A, xs) else false
    | AB, x::xs -> run_case (AB, xs)
;;

let rec run_cases = function
    | 0 -> 0
    | n ->
        let str_case = read_word () in
        let lst_case = create_char_list str_case (String.length str_case) (String.length str_case) in
        if (run_case (A, lst_case)) then begin
            print_string "YES";
            print_newline ();
            run_cases (n-1)
        end
        else begin
            print_string "NO";
            print_newline ();
            run_cases (n-1)
        end
;;

let num_cases = read_int () in
run_cases num_cases;;

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

let rec create_char_list input input_length = function
    | 0 -> []
    | n -> (String.get input  (input_length-n))::(create_char_list input input_length (n-1))
;;

type acceptable_char = A | B | AB ;;

let rec run_case = function
    | A, [x] -> false
    | _, [x] -> if (x=='B') then true else false
    | A, x::xs -> if (x=='A') then run_case (AB, xs) else false
    | B, x::xs -> if (x=='B') then run_case (A, xs) else false
    | AB, x::xs -> if (x=='B') then run_case (A, xs) else run_case (AB, xs)
;;

let rec run_cases = function
    | 0 -> 0
    | n ->
        let str_case = read_word () in
        let lst_case = create_char_list str_case (String.length str_case) (String.length str_case) in
        if (run_case (A, lst_case)) then begin
            print_string "YES";
            print_newline ();
            run_cases (n-1)
        end
        else begin
            print_string "NO";
            print_newline ();
            run_cases (n-1)
        end
;;

let num_cases = read_int () in
run_cases num_cases;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let str = (input_line stdin) in
  let rep = ref true in
  if str.[0] = 'B' || str.[String.length str -1] = 'A' then rep := false
  else begin
    for j = 0 to String.length str -2 do
      if str.[j] = 'B' && str.[j+1] = 'B' then rep := false
    done;
  end;
  if !rep then print_endline "YES" else print_endline "NO";
done;;


You came to the exhibition and one exhibit has drawn your attention. It consists of $$$n$$$ stacks of blocks, where the $$$i$$$-th stack consists of $$$a_i$$$ blocks resting on the surface.The height of the exhibit is equal to $$$m$$$. Consequently, the number of blocks in each stack is less than or equal to $$$m$$$.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le m \le 10^9$$$) — the number of stacks and the height of the exhibit. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the number of blocks in each stack from left to right.

Print exactly one integer — the maximum number of blocks that can be removed.

NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are $$$10$$$ blue cells, so the answer is $$$10$$$.

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module I64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  (* input *)
  let input_i64_array n = Array.init (i32 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 i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

let () =
  let n,m = get_2_i64 0 in
  let a = input_i64_array n in
  sort compare a;
  let need = ref n in
  let height = fold_left (fun height v ->
    if height >= v then height
    else height + 1L
  ) 0L a in
  let mx = a.(i32 n-$1) in
  if mx > height then need += (mx - height);
  let sum = fold_left (+) 0L a in
  printf "%Ld\n" @@ sum - !need


A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from  - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist.

The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0.

If the required point exists, output its coordinates, otherwise output -1.

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

open Int64

let blankinship a b =
  let rec go a b u v x y =
    if a = 0L then
      b,x,y
    else
      let q = div b a in
      go (sub b (mul q a)) a (sub x (mul q u)) (sub y (mul q v)) u v
  in go a b 1L 0L 0L 1L

let () =
  let a = read_int64 0 in
  let b = read_int64 0 in
  let c = read_int64 0 in
  let d,x,y = blankinship a b in
  if rem c d = 0L then
    let t = div (neg c) d in
    Printf.printf "%Ld %Ld\n" (mul x t) (mul y t)
  else
    print_endline "-1"

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

open Int64

let blankinship a b =
  let rec go a b u v x y =
    if a = 0L then
      b,x,y
    else
      let q = div b a in
      go (sub b (mul q a)) a (sub x (mul q u)) (sub y (mul q v)) u v
  in go a b 1L 0L 0L 1L

let () =
  let a = read_int64 0 in
  let b = read_int64 0 in
  let c = read_int64 0 in
  let d,x,y = blankinship a b in
  let t = div (neg c) d in
  Printf.printf "%Ld %Ld\n" (mul x t) (mul y t)


Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them — those with biggest ti.Your task is to handle queries of two types:  "1 id" — Friend id becomes online. It's guaranteed that he wasn't online before.  "2 id" — Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type?

The first line contains three integers n, k and q (1 ≤ n, q ≤ 150 000, 1 ≤ k ≤ min(6, n)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 109) where ti describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers typei and idi (1 ≤ typei ≤ 2, 1 ≤ idi ≤ n) — the i-th query. If typei = 1 then a friend idi becomes online. If typei = 2 then you should check whether a friend idi is displayed. It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei = 2) so the output won't be empty.

For each query of the second type print one line with the answer — "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise.

NoteIn the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries:  "1 3" — Friend 3 becomes online.  "2 4" — We should check if friend 4 is displayed. He isn't even online and thus we print "NO".  "2 3" — We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES".  "1 1" — Friend 1 becomes online. The system now displays both friend 1 and friend 3.  "1 2" — Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1 < t2, t3) so friend 1 won't be displayed  "2 1" — Print "NO".  "2 2" — Print "YES".  "2 3" — Print "YES".

open Printf
open Scanf

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

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

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

let () =
  let n = read_int () in
  let k = read_int () in
  let q = read_int () in

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

  let set = fold 0 (k-1) (fun i ac -> Pset.add (-i,0) ac) Pset.empty in

  ignore (
    fold 1 q (fun _ set ->
      match read_int() with
	| 1 ->
	  let id = -1 + read_int() in
	  let set = Pset.add (t.(id), id) set in
	  let y = Pset.min_elt set in
	  Pset.remove y set
	| 2 ->
	  let id = -1 + read_int() in
	  if Pset.mem (t.(id),id) set then printf "YES\n" else printf "NO\n";
	  set
	| _ -> failwith "bad input"
    ) set
  )


Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.

A single input line contains a single integer n (1 ≤ n ≤ 105).

Print a single integer — the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.

(* Codeforces 248B PaperWork done *)

open Big_int;;
open List;;

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

let sp = [2; 3; 5; 7];;

let cvo o p = (o * 10) mod p;;

(* remainders 10^n from dividing by 2 3 5 7 *)
let rec ostat n p o = match n with
| 0 -> o
| _ -> ostat (n-1) p (cvo o p);;

let checkonep o p k = ((o + k) mod p) = 0;;

let rec checklp lo lp k = match lo with
| [] -> true
| h :: t -> (checkonep h (List.hd lp) k) && (checklp t (List.tl lp) k);;

let rec findfirst lo lp k =
	if checklp lo lp k then k
	else findfirst lo lp (k+1);;

let rec pow10 n = match n with
| 0 -> Big_int.unit_big_int
| _ ->
	if n < 10 then Big_int.mult_int_big_int 10 (pow10 (n-1))
	else
		let a = n/2 in
		let b = n - 2*a in
		let pa = pow10 a in
		let pb = pow10 b in
		Big_int.mult_big_int pa (Big_int.mult_big_int pa pb);;

let main () =
	let n = gr() in
	let lo = List.map (fun p -> ostat (n-1) p 1) sp in
	let k = findfirst lo sp 1 in
	if n < 3 then print_string "-1"
	else begin
		(* print_string "lo = ";                               *)
		(* printlisti lo;                                      *)
		(* print_string ("\nk = " ^ (string_of_int k) ^ "\n"); *)
		let pown = pow10 (n-1) in
		let ret = Big_int.add_int_big_int k pown in
		print_string (Big_int.string_of_big_int ret)
	end;;

main();;

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

let rec pow n = if n=0 then 1 else
  let m = n/2 in
  let p = pow m in
    (if m+m=n then 1 else 10)*p*p mod 210

let () =
  let n = read_int() in
    if n<=2 then print_string "-1\n"
    else if n=3 then print_string "210\n"
    else
      let x = pow (n-1) in
      let y = 210-x in
	print_string "1";
	for i=2 to n-3 do
	  print_string "0"
	done;
	Printf.printf "%03d\n" y


Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.

The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".

Output n lines — on the i-th line you should print the i-th stone's number from the left.

NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1.

module Pset = Set.Make (struct type t = int*int let compare = compare end)
let read_string () = Scanf.bscanf Scanf.Scanning.stdib " %s " (fun x -> x)

let () =
  let dir = read_string() in
  let n = String.length dir in

  let rec loop i s lo hi = if i=0 then s else (
    if dir.[i-1] = 'r'
    then loop (i-1) (Pset.add (lo-1, i) s) (lo-1) hi
    else loop (i-1) (Pset.add (hi+1, i) s) lo (hi+1)
  ) in

  let s = loop (n-1) (Pset.singleton (0,n)) 0 0 in

    Pset.iter (fun (i,j) -> Printf.printf "%d\n" j) s;


Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.

Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.

5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503

5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503

NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.

open Scanf
open Printf

let scan_int () = Scanf.scanf " %d " (fun i -> i);;
let scan_string () = Scanf.scanf " %s" (fun i -> i);;

type result =
  {
    name: string;
    score: int;
  };;

let insert_reg_team team res =
  let rec aux team res n =
    if n = 0 then []
    else match team with
      | [] -> []
      | h::t -> if res.score > h.score
                then res::(aux team {name=""; score=(-1)} (n-1))
                else h::(aux t res (n-1))
  in aux team res 3;;

let () =
  let n = scan_int () in
  let m = scan_int () in

  let teams = Array.make m [{name= ""; score=(-1)}; {name= ""; score=(-1)}; {name= ""; score=(-1)}] in

  for i=1 to n do
    let name = scan_string () in
    let reg = scan_int () in
    let score = scan_int() in
    let team = Array.get teams (reg - 1) in
    let new_team = insert_reg_team team { name = name; score = score; } in
    Array.set teams (reg - 1) new_team
  done;
  (* Array.iter (fun team -> List.iter (fun p -> Printf.printf "%s %d\n" p.name p.score) team; Printf.printf "\n" ) t
eams; *)
  Array.iter (fun team ->
    let p1 = List.nth team 0 in
    let p2 = List.nth team 1 in
    if List.length team > 2
    then
      let p3 = List.nth team 2 in
      if p3.score = p2.score
      then Printf.printf "?\n"
      else Printf.printf "%s %s\n" p1.name p2.name
    else Printf.printf "%s %s\n" p1.name p2.name
    ) teams;

open Scanf
open Printf

let scan_int () = Scanf.scanf " %d " (fun i -> i);;
let scan_string () = Scanf.scanf " %s" (fun i -> i);;

type result =
  {
    name: string;
    score: int;
  };;

let insert_reg_team team res =
  let rec aux team res n =
    if n = 0 then []
    else match team with
      | [] -> []
      | h::t -> if res.score > h.score
                then res::(aux team {name=""; score=0} (n-1))
                else h::(aux t res (n-1))
  in aux team res 3;;

let () =
  let n = scan_int () in
  let m = scan_int () in

  let teams = Array.make m [{name= ""; score= 0}; {name= ""; score= 0}; {name= ""; score= 0}] in

  for i=1 to n do
    let name = scan_string () in
    let reg = scan_int () in
    let score = scan_int() in
    let team = Array.get teams (reg - 1) in
    let new_team = insert_reg_team team { name = name; score = score; } in
    Array.set teams (reg - 1) new_team
  done;
  (* Array.iter (fun team -> List.iter (fun p -> Printf.printf "%s %d\n" p.name p.score) team; Printf.printf "\n" ) t
eams; *)
  Array.iter (fun team ->
    let p1 = List.nth team 0 in
    let p2 = List.nth team 1 in
    if List.length team > 2
    then
      let p3 = List.nth team 2 in
      if p3.score = p2.score
      then Printf.printf "?\n"
      else Printf.printf "%s %s\n" p1.name p2.name
    else Printf.printf "%s %s\n" p1.name p2.name
    ) teams;

open Scanf
open Printf

let scan_int () = Scanf.scanf " %d " (fun i -> i);;
let scan_string () = Scanf.scanf " %s" (fun i -> i);;

type result =
  {
    name: string;
    score: int;
  };;

let insert_reg_team team res =
  let rec aux team res n =
      match team with
        | [] -> if n > 2 then [] else [res]
        | h :: t -> if h.score >= res.score
          then h :: (aux t res (n + 1))
          else if n > 2 then team else res :: team
  in (aux team res 0);;

let () =
  let n = scan_int () in
  let m = scan_int () in

  let teams = Array.make m [] in

  for i=1 to n do
    let name = scan_string () in
    let reg = scan_int () in
    let score = scan_int() in
    let team = Array.get teams (reg - 1) in
    let new_team = insert_reg_team team { name = name; score = score; } in
    Array.set teams (reg - 1) new_team
  done;
  Array.iter (fun team ->
    let p1 = List.nth team 0 in
    let p2 = List.nth team 1 in
    if List.length team = 3
    then
      let p3 = List.nth team 2 in
      if p3.score = p2.score
      then Printf.printf "?\n"
      else Printf.printf "%s %s\n" p1.name p2.name
    else Printf.printf "%s %s\n" p1.name p2.name
    ) teams;

open Scanf
open Printf

let scan_int () = Scanf.scanf " %d " (fun i -> i);;
let scan_string () = Scanf.scanf " %s" (fun i -> i);;

type result =
  {
    name: string;
    score: int;
  };;

let insert_reg_team team res =
  let rec aux team res n =
      match team with
        | [] -> if n > 2 then [] else [res]
        | h :: t -> if h.score >= res.score
          then h :: (aux t res (n + 1))
          else if n > 2 then team else res :: team
  in (aux team res 0);;

let () =
  let n = scan_int () in
  let m = scan_int () in

  let teams = Array.make m [] in

  for i=1 to n do
    let name = scan_string () in
    let reg = scan_int () in
    let score = scan_int() in
    let team = Array.get teams (reg - 1) in
    let new_team = insert_reg_team team { name = name; score = score; } in
    Array.set teams (reg - 1) new_team
  done;
  Array.iter (fun team ->
    let p1 = List.nth team 0 in
    let p2 = List.nth team 1 in
    if List.length team = 3
    then
      let p3 = List.nth team 2 in
      if p3.score = p2.score || p1.score = p2.score
      then Printf.printf "?\n"
      else Printf.printf "%s %s\n" p1.name p2.name
    else Printf.printf "%s %s\n" p1.name p2.name
    ) teams;

open Scanf
open Printf

let scan_int () = Scanf.scanf " %d " (fun i -> i);;
let scan_string () = Scanf.scanf " %s" (fun i -> i);;

type result =
  {
    name: string;
    score: int;
  };;

let insert_reg_team team res =
  let rec aux team res n =
    if n = 0 then []
    else match team with
      | [] -> []
      | h::t -> if res.score > h.score
                then res::(aux team {name=""; score=0} (n-1))
                else h::(aux t res (n-1))
  in aux team res 3;;

let () =
  let n = scan_int () in
  let m = scan_int () in

  let teams = Array.make m [{name= ""; score= 0}; {name= ""; score= 0}; {name= ""; score= 0}] in

  for i=1 to n do
    let name = scan_string () in
    let reg = scan_int () in
    let score = scan_int() in
    let team = Array.get teams (reg - 1) in
    let new_team = insert_reg_team team { name = name; score = score; } in
    Array.set teams (reg - 1) new_team
  done;
  Array.iter (fun team -> List.iter (fun p -> Printf.printf "%s %d\n" p.name p.score) team; Printf.printf "\n" ) teams;
  Array.iter (fun team ->
    let p1 = List.nth team 0 in
    let p2 = List.nth team 1 in
    if List.length team > 2
    then
      let p3 = List.nth team 2 in
      if p3.score = p2.score
      then Printf.printf "?\n"
      else Printf.printf "%s %s\n" p1.name p2.name
    else Printf.printf "%s %s\n" p1.name p2.name
    ) teams;


Thanos wants to destroy the avengers base, but he needs to destroy the avengers along with their base.Let we represent their base with an array, where each position can be occupied by many avengers, but one avenger can occupy only one position. Length of their base is a perfect power of $$$2$$$. Thanos wants to destroy the base using minimum power. He starts with the whole base and in one step he can do either of following:   if the current length is at least $$$2$$$, divide the base into $$$2$$$ equal halves and destroy them separately, or  burn the current base. If it contains no avenger in it, it takes $$$A$$$ amount of power, otherwise it takes his $$$B \cdot n_a \cdot l$$$ amount of power, where $$$n_a$$$ is the number of avengers and $$$l$$$ is the length of the current base. Output the minimum power needed by Thanos to destroy the avengers' base.

The first line contains four integers $$$n$$$, $$$k$$$, $$$A$$$ and $$$B$$$ ($$$1 \leq n \leq 30$$$, $$$1 \leq k \leq 10^5$$$, $$$1 \leq A,B \leq 10^4$$$), where $$$2^n$$$ is the length of the base, $$$k$$$ is the number of avengers and $$$A$$$ and $$$B$$$ are the constants explained in the question. The second line contains $$$k$$$ integers $$$a_{1}, a_{2}, a_{3}, \ldots, a_{k}$$$ ($$$1 \leq a_{i} \leq 2^n$$$), where $$$a_{i}$$$ represents the position of avenger in the base.

Output one integer — the minimum power needed to destroy the avengers base.

NoteConsider the first example.One option for Thanos is to burn the whole base $$$1-4$$$ with power $$$2 \cdot 2 \cdot 4 = 16$$$.Otherwise he can divide the base into two parts $$$1-2$$$ and $$$3-4$$$.For base $$$1-2$$$, he can either burn it with power $$$2 \cdot 1 \cdot 2 = 4$$$ or divide it into $$$2$$$ parts $$$1-1$$$ and $$$2-2$$$.For base $$$1-1$$$, he can burn it with power $$$2 \cdot 1 \cdot 1 = 2$$$. For $$$2-2$$$, he can destroy it with power $$$1$$$, as there are no avengers. So, the total power for destroying $$$1-2$$$ is $$$2 + 1 = 3$$$, which is less than $$$4$$$. Similarly, he needs $$$3$$$ power to destroy $$$3-4$$$. The total minimum power needed is $$$6$$$.

(* keywords: binary search *)
(*  There's a bug.
3 2 5 1
7 8

Output
8

Answer
12

Checker Log
wrong answer 1st numbers differ - expected: '12', found: '8'

*)

(* 6 minutes after the end got this *)

open Printf
open Scanf

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

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

let read_long _ = bscanf Scanning.stdib " %Ld " (fun x -> x)
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,k) = read_pair () in
  let (aa,bb) = read_pair () in
  let a = Array.init k (fun _ -> short (read_long() -- 1L)) in

  let h = Hashtbl.create 10 in

  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  for i=0 to k-1 do
    increment a.(i)
  done;

  let np = Hashtbl.length h in
  let p = Array.make np 0 in  (* places where there is something *)
  let s = Array.make np 0 in

  let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in
  Array.sort compare p;
  for i=0 to np-1 do
    s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))
  done;

  (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)

  let prefix_count x =
  (* the number of things at positions <= x *)
    let rec bsearch lo hi =
    (* know that p.(lo) <= x < p.(hi) *)
      if lo + 1 = hi then s.(lo) else
	let m = (hi+lo)/2 in
	if p.(m) <= x then bsearch m hi else bsearch lo m
    in

    if x < p.(0) then 0
    else if x >= p.(np-1) then s.(np-1)
    else bsearch 0 (np-1)
  in

  let count_range x y = (* the number in range [x..y] *)
    (prefix_count y) - (prefix_count (x-1))
  in

  let rec eval i j =
    let len' = j-i in  (* can't represent 2^30 in 31 bit signed arithmetic *)
    let c = count_range i j in
    if c = 0 then long aa else (
      let opt1 = (long bb) ** (long c) ** (1L++(long len')) in
      if len' = 0 then opt1 else
	let opt2 = (eval i (i + len'/2)) ++ (eval (i+1+(len'/2)) j) in
	min opt1 opt2
    )
  in

  let answer = eval 0 ((1 lsl n)-1) in (* have to avoid 1 lsl 30 *)
  printf "%Ld\n" answer

(* keywords: binary search *)
(*  There's a bug.
3 2 5 1
7 8

Output
8

Answer
12

Checker Log
wrong answer 1st numbers differ - expected: '12', found: '8'

*)

(* 6 minutes after the end got this *)

open Printf
open Scanf

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

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

let read_long _ = bscanf Scanning.stdib " %Ld " (fun x -> x)
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,k) = read_pair () in
  let (aa,bb) = read_pair () in
  let a = Array.init k (fun _ -> short (read_long() -- 1L)) in

  let h = Hashtbl.create 10 in

  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  for i=0 to k-1 do
    increment a.(i)
  done;

  let np = Hashtbl.length h in
  let p = Array.make np 0 in  (* places where there is something *)
  let s = Array.make np 0 in

  let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in
  Array.sort compare p;
  for i=0 to np-1 do
    s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))
  done;

  (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)

  let prefix_count x =
  (* the number of things at positions <= x *)
    let rec bsearch lo hi =
    (* know that p.(lo) <= x < p.(hi) *)
      if lo + 1 = hi then s.(lo) else
	let m = (hi+lo)/2 in
	if p.(m) < x then bsearch m hi else bsearch lo m
    in

    if x < p.(0) then 0
    else if x >= p.(np-1) then s.(np-1)
    else bsearch 0 (np-1)
  in

  let count_range x y = (* the number in range [x..y] *)
    (prefix_count y) - (prefix_count (x-1))
  in

  let rec eval i j =
    let len = j-i+1 in
    let c = count_range i j in
    if c = 0 then long aa else (
      let opt1 = (long bb) ** (long c) ** (long len) in
      if len = 1 then opt1 else
	let opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in
	min opt1 opt2
    )
  in

  let answer = eval 0 ((1 lsl n)-1) in (* have to avoid 1 lsl 30 *)
  printf "%Ld\n" answer

(* keywords: binary search *)
(*  There's a bug.
3 2 5 1
7 8

Output
8

Answer
12

Checker Log
wrong answer 1st numbers differ - expected: '12', found: '8'

*)

(* 6 minutes after the end got this *)

open Printf
open Scanf

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

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,k) = read_pair () in
  let (aa,bb) = read_pair () in
  let a = Array.init k (fun _ -> -1+read_int()) in

  let h = Hashtbl.create 10 in

  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  for i=0 to k-1 do
    increment a.(i)
  done;

  let np = Hashtbl.length h in
  let p = Array.make np 0 in  (* places where there is something *)
  let s = Array.make np 0 in

  let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in
  Array.sort compare p;
  for i=0 to np-1 do
    s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))
  done;

  (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)

  let prefix_count x =
  (* the number of things at positions <= x *)
    let rec bsearch lo hi =
    (* know that p.(lo) <= x < p.(hi) *)
      if lo + 1 = hi then s.(lo) else
	let m = lo + (hi-lo)/2 in
	if p.(m) < x then bsearch m hi else bsearch lo m
    in

    if x < p.(0) then 0
    else if x >= p.(np-1) then s.(np-1)
    else bsearch 0 (np-1)
  in

  let count_range x y = (* the number in range [x..y] *)
    (prefix_count y) - (prefix_count (x-1))
  in

  let rec eval i j =
    let len = j-i+1 in
    let c = count_range i j in
    if c = 0 then long aa else (
      let opt1 = (long bb) ** (long c) ** (long len) in
      if len = 1 then opt1 else
	let opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in
	min opt1 opt2
    )
  in

  let answer = eval 0 ((1 lsl n)-1) in (* have to avoid 1 lsl 30 *)
  printf "%Ld\n" answer

(* keywords: binary search *)
(*  There's a bug.
3 2 5 1
7 8

Output
8

Answer
12

Checker Log
wrong answer 1st numbers differ - expected: '12', found: '8'

*)

(* 6 minutes after the end got this *)

open Printf
open Scanf

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

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,k) = read_pair () in
  let (aa,bb) = read_pair () in
  let a = Array.init k (fun _ -> -1+read_int()) in

  let h = Hashtbl.create 10 in

  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  for i=0 to k-1 do
    increment a.(i)
  done;

  let np = Hashtbl.length h in
  let p = Array.make np 0 in  (* places where there is something *)
  let s = Array.make np 0 in

  let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in
  Array.sort compare p;
  for i=0 to np-1 do
    s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))
  done;

   (* s.(i) = p.(0) + a.(1) + ... + a.(i) *)

  let prefix_count x =
  (* the number of things at positions <= x *)
    let rec bsearch lo hi =
    (* know that p.(lo) < x <= p.(hi) *)
      if lo + 1 = hi then if x=p.(hi) then s.(hi) else s.(lo) else (
	let m = lo + (hi-lo)/2 in
	if p.(m) < x then bsearch m hi else bsearch lo m
      )
    in

    if x < p.(0) then 0 else if x=p.(0) then s.(0) else bsearch 0 (np-1)
  in

  let count_range x y =
    (prefix_count y) - (prefix_count (x-1))
  in

  let rec eval i j =
    let len = j-i+1 in
    let c = count_range i j in
    if c = 0 then long aa else (
      let opt1 = (long bb) ** (long c) ** (long len) in
      if len = 1 then opt1 else
	let opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in
	min opt1 opt2
    )
  in

  let answer = eval 0 ((1 lsl n)-1) in
  printf "%Ld\n" answer

(* keywords: binary search *)

(* 6 minutes after the end got this *)

open Printf
open Scanf

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

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,k) = read_pair () in
  let (aa,bb) = read_pair () in
  let a = Array.init k read_int in

  let h = Hashtbl.create 10 in

  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  for i=0 to k-1 do
    increment a.(i)
  done;

  let np = Hashtbl.length h in
  let p = Array.make np 0 in  (* places where there is something *)
  let s = Array.make np 0 in

  let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in
  Array.sort compare p;
  for i=0 to np-1 do
    s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))
  done;

   (* s.(i) = p.(0) + a.(1) + ... + a.(i) *)

  let prefix_count x =
  (* the number of things at positions <= x *)
    let rec bsearch lo hi =
    (* know that p.(lo) < x <= p.(hi) *)
      if lo + 1 = hi then if x=p.(hi) then s.(hi) else s.(lo) else (
	let m = lo + (hi-lo)/2 in
	if p.(m) < x then bsearch m hi else bsearch lo m
      )
    in

    if x < p.(0) then 0 else if x=p.(0) then s.(0) else bsearch 0 (np-1)
  in

  let count_range x y =
    (prefix_count y) - (prefix_count (x-1))
  in

  let rec eval i j =
    let len = j-i+1 in
    let c = count_range i j in
    if c = 0 then long aa else (
      let opt1 = (long bb) ** (long c) ** (long len) in
      if len = 1 then opt1 else
	let opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in
	min opt1 opt2
    )
  in

  let answer = eval 0 ((1 lsl n)-1) in
  printf "%Ld\n" answer

(* keywords: binary search *)
(*  There's a bug.
3 2 5 1
7 8

Output
8

Answer
12

Checker Log
wrong answer 1st numbers differ - expected: '12', found: '8'

*)

(* 6 minutes after the end got this *)

open Printf
open Scanf

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

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,k) = read_pair () in
  let (aa,bb) = read_pair () in
  let a = Array.init k read_int in

  let h = Hashtbl.create 10 in

  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  for i=0 to k-1 do
    increment a.(i)
  done;

  let np = Hashtbl.length h in
  let p = Array.make np 0 in  (* places where there is something *)
  let s = Array.make np 0 in

  let _ = Hashtbl.fold (fun k v i -> p.(i) <- k; i+1) h 0 in
  Array.sort compare p;
  for i=0 to np-1 do
    s.(i) <- (if i=0 then 0 else s.(i-1)) + (Hashtbl.find h p.(i))
  done;

  (* s.(i) = the number of avengers in positions p.(0), p.(1) ... p.(i) *)

  let prefix_count x =
  (* the number of things at positions <= x *)
    let rec bsearch lo hi =
    (* know that p.(lo) < x <= p.(hi) *)
      if lo + 1 = hi then if x = p.(hi) then s.(hi) else s.(lo) else
	let m = lo + (hi-lo)/2 in
	if p.(m) < x then bsearch m hi else bsearch lo m
    in

    if x < p.(0) then 0
    else if x=p.(0) then s.(0)
    else if x > p.(np-1) then s.(np-1) else bsearch 0 (np-1)
  in

  let count_range x y = (* the number in range [x..y] *)
    (prefix_count y) - (prefix_count (x-1))
  in

  let rec eval i j =
    let len = j-i+1 in
    let c = count_range i j in
    if c = 0 then long aa else (
      let opt1 = (long bb) ** (long c) ** (long len) in
      if len = 1 then opt1 else
	let opt2 = (eval i (i + (len/2) - 1)) ++ (eval (i+(len/2)) j) in
	min opt1 opt2
    )
  in

  let answer = eval 1 (1 lsl n) in
  printf "%Ld\n" answer


An array $$$b$$$ is called to be a subarray of $$$a$$$ if it forms a continuous subsequence of $$$a$$$, that is, if it is equal to $$$a_l$$$, $$$a_{l + 1}$$$, $$$\ldots$$$, $$$a_r$$$ for some $$$l, r$$$.Suppose $$$m$$$ is some known constant. For any array, having $$$m$$$ or more elements, let's define it's beauty as the sum of $$$m$$$ largest elements of that array. For example:   For array $$$x = [4, 3, 1, 5, 2]$$$ and $$$m = 3$$$, the $$$3$$$ largest elements of $$$x$$$ are $$$5$$$, $$$4$$$ and $$$3$$$, so the beauty of $$$x$$$ is $$$5 + 4 + 3 = 12$$$. For array $$$x = [10, 10, 10]$$$ and $$$m = 2$$$, the beauty of $$$x$$$ is $$$10 + 10 = 20$$$.You are given an array $$$a_1, a_2, \ldots, a_n$$$, the value of the said constant $$$m$$$ and an integer $$$k$$$. Your need to split the array $$$a$$$ into exactly $$$k$$$ subarrays such that:  Each element from $$$a$$$ belongs to exactly one subarray. Each subarray has at least $$$m$$$ elements. The sum of all beauties of $$$k$$$ subarrays is maximum possible.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m$$$, $$$2 \le k$$$, $$$m \cdot k \le n$$$) — the number of elements in $$$a$$$, the constant $$$m$$$ in the definition of beauty and the number of subarrays to split to. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).

In the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition. In the second line, print $$$k-1$$$ integers $$$p_1, p_2, \ldots, p_{k-1}$$$ ($$$1 \le p_1 < p_2 < \ldots < p_{k-1} < n$$$) representing the partition of the array, in which:  All elements with indices from $$$1$$$ to $$$p_1$$$ belong to the first subarray. All elements with indices from $$$p_1 + 1$$$ to $$$p_2$$$ belong to the second subarray. $$$\ldots$$$. All elements with indices from $$$p_{k-1} + 1$$$ to $$$n$$$ belong to the last, $$$k$$$-th subarray. If there are several optimal partitions, print any of them.

NoteIn the first example, one of the optimal partitions is $$$[5, 2, 5]$$$, $$$[2, 4]$$$, $$$[1, 1, 3, 2]$$$.  The beauty of the subarray $$$[5, 2, 5]$$$ is $$$5 + 5 = 10$$$.  The beauty of the subarray $$$[2, 4]$$$ is $$$2 + 4 = 6$$$.  The beauty of the subarray $$$[1, 1, 3, 2]$$$ is $$$3 + 2 = 5$$$. The sum of their beauties is $$$10 + 6 + 5 = 21$$$.In the second example, one optimal partition is $$$[4]$$$, $$$[1, 3]$$$, $$$[2, 2]$$$, $$$[3]$$$.

open Printf
open Scanf

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

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in
  let k = read_int () in
  let b = Array.init n read_int in
  let a = Array.init n (fun i -> (b.(i), i)) in
  Array.sort (fun x y -> compare y x) a;

  let mark = Array.make n 0 in

  for i=0 to m*k-1 do
    mark.(snd a.(i)) <- 1
  done;

  let p = Array.make (k+1) (-1) in

  for j=1 to k-1 do
    let rec loop i need =
      let need = need - mark.(i) in
      if need = 0 then p.(j) <- i else loop (i+1) need
    in
    loop (p.(j-1)+1) m
  done;

  let total = sum 0 (n-1) (fun i ->
    long (mark.(i) * b.(i))
  ) in

  printf "%Ld\n" total;

  for j=1 to k-1 do
    printf "%d " (p.(j)+1)
  done;

  print_newline()


Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift. Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

open Scanf;;
open Printf;;

module UF = struct
  type t = int array

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

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

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

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

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

module S = Set.Make(struct
  type t = int
  let compare x y = x - y
end)

let input () =
  let n = scanf "%d " (fun x -> x) in
  let arr = Array.make n (0, 0) in
  for i = 0 to (n - 1) do
    arr.(i) <- scanf "%d %d " (fun x y -> (x, y))
  done;
  (n, arr)

let solve (n, arr) =
  let uf = UF.make n in
  for i = 0 to (n - 1) do
    let (x1, y1) = arr.(i) in
    for j = 0 to (i - 1) do
      let (x2, y2) = arr.(j) in
      if x1 = x2 || y1 = y2 then
        ignore(UF.union_set i j uf)
    done
  done;

  let s = ref S.empty in
  for i = 0 to (n - 1) do
    s := S.add (UF.root i uf) !s
  done;
  S.cardinal !s

let () =
  let inp = input () in
  let n = solve inp in
  printf "%d\n" (n - 1)


Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his string — each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2·ai ≤ |s|.You face the following task: determine what Pasha's string will look like after m days.

The first line of the input contains Pasha's string s of length from 2 to 2·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≤ m ≤ 105) —  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≤ ai; 2·ai ≤ |s|) — the position from which Pasha started transforming the string on the i-th day.

In the first line of the output print what Pasha's string s will look like after m days.

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let m = String.length s in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a;
    let b = ref false in
    let pos = ref 0 in
      for i = 0 to m / 2 - 1 do
	while !pos < n && a.(!pos) <= i + 1 do
	  incr pos;
	  b := not !b;
	done;
	if !b then (
	  let tmp = s.[i] in
	    s.[i] <- s.[m - i - 1];
	    s.[m - i - 1] <- tmp;
	)
      done;
      Printf.printf "%s\n" s;


Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars.Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?

First line of input contains an integer n (2 ≤ n ≤ 105), the number of players. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 109) — the bids of players.

Print "Yes" (without the quotes) if players can make their bids become equal, or "No" otherwise.

NoteIn the first sample test first and third players should double their bids twice, second player should double his bid once and fourth player should both double and triple his bid.It can be shown that in the second sample test there is no way to make all bids equal.

open Printf
open Scanf

(* returns true iff f t = true for all i <= t <= j *)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

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

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

  let rec remove d x = if x mod d = 0 then remove d (x/d) else x in

  for i=0 to n-1 do
    a.(i) <- remove 3 (remove 2 a.(i))

  done;

  if forall 1 (n-1) (fun i -> (a.(0) = a.(i)))
  then printf "Yes\n" else printf "No\n"

module IntMap = Map.Make(struct type t = int let compare = compare end)

(* factorise : int -> (int * int) list *)
let reachable n =
    let rec aux d n =
        if n = 1 then true else
        if d > 3 then false else
        if n mod d = 0 then aux d (n / d) else aux (d + 1) n
    in
    aux 2 n

let rec gcd n m =
    if m = 0 then n else gcd m (n mod m)

let () = Scanf.scanf "%d\n" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
    (* calculate lcm *)
    let g = Array.fold_left (fun a b -> gcd a b)
                            a.(0) (Array.sub a 1 (Array.length a - 1))
    in
    let ap = Array.map (fun n -> reachable (n / g)) a in
    print_endline (if List.for_all (fun x -> x) (Array.to_list ap) then "Yes" else "No"))

open Printf
open Scanf

let id x = x

let rec gen_norm k x = if x mod k = 0 then gen_norm k (x / k) else x
let norm x = gen_norm 2 (gen_norm 3 x)

let () =
  let n = scanf " %d" id in
  let a = scanf " %d" norm in
  let rec check = function
    | 0 -> true
    | n -> (scanf " %d" norm = a) && check (n - 1) in
  printf "%s\n" (if check (n - 1) then "Yes" else "No")

open Printf
open Scanf

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

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

  let rec remove d x = if x mod d = 0 then remove d (x/d) else x in

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

  if forall 1 (n-1) (fun i -> a.(0) = a.(i)) then printf "Yes\n" else printf "No\n"


Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.Limak will repeat the following operation till everything is destroyed.Block is called internal if it has all four neighbors, i.e. it has each side (top, left, down and right) adjacent to other block or to the floor. Otherwise, block is boundary. In one operation Limak destroys all boundary blocks. His paws are very fast and he destroys all those blocks at the same time.Limak is ready to start. You task is to count how many operations will it take him to destroy all towers.

The first line contains single integer n (1 ≤ n ≤ 105). The second line contains n space-separated integers h1, h2, ..., hn (1 ≤ hi ≤ 109) — sizes of towers.

Print the number of operations needed to destroy all towers.

NoteThe picture below shows all three operations for the first sample test. Each time boundary blocks are marked with red color.    After first operation there are four blocks left and only one remains after second operation. This last block is destroyed in third operation.

open Printf
open Scanf

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let h = Array.make (n+2) 0 in

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

  for i=1 to n do  (* L-->R pass *)
    h.(i) <- min h.(i) (1 + h.(i-1))
  done;

  for i=n downto 1 do  (* R-->L pass *)
    h.(i) <- min h.(i) (1 + h.(i+1))
  done;

  let answer = maxf 1 n (fun i-> h.(i)) in

  printf "%d\n" answer