A median in an array with the length of n is an element which occupies position number  after we sort the elements in the non-decreasing order (the array elements are numbered starting with 1). A median of an array (2, 6, 1, 2, 3) is the number 2, and a median of array (0, 96, 17, 23) — the number 17.We define an expression  as the integer part of dividing number a by number b.One day Vasya showed Petya an array consisting of n integers and suggested finding the array's median. Petya didn't even look at the array and said that it equals x. Petya is a very honest boy, so he decided to add several numbers to the given array so that the median of the resulting array would be equal to x.Petya can add any integers from 1 to 105 to the array, including the same numbers. Of course, he can add nothing to the array. If a number is added multiple times, then we should consider it the number of times it occurs. It is not allowed to delete of change initial numbers of the array. While Petya is busy distracting Vasya, your task is to find the minimum number of elements he will need.

The first input line contains two space-separated integers n and x (1 ≤ n ≤ 500, 1 ≤ x ≤ 105) — the initial array's length and the required median's value. The second line contains n space-separated numbers — the initial array. The elements of the array are integers from 1 to 105. The array elements are not necessarily different.

Print the only integer — the minimum number of elements Petya needs to add to the array so that its median equals x.

NoteIn the first sample we can add number 9 to array (10, 20, 30). The resulting array (9, 10, 20, 30) will have a median in position , that is, 10.In the second sample you should add numbers 4, 5, 5, 5. The resulting array has median equal to 4.

type t =   J of int
         | P of int
let _ =
    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
    in

    let main () =
        let n = rdint () in
        let x = rdint () in
        let arr = Array.init n (fun _ -> rdint ()) in
        let l = Array.to_list arr in
        let q = if List.exists (fun t -> t = x) l then 0 else 1 in
        let l = if q = 1 then x :: l else l in
        let arr = Array.of_list l in
        let n = n + q in
        Array.sort compare arr;

        let r =
            let med = arr.((n - 1) / 2) in
            let rec search p v =
                if arr.(p) = x then p else
                search (p + v) v
            in
            if med = x then 0 else
            if med > x then (
                let p = search ((n - 1) / 2) (- 1) in
                n - 2 * (p + 1)
            ) else (
                let p = search ((n - 1) / 2) 1 in
                p * 2 + 1 - n
            )
        in
        Printf.printf "%d\n" (r + q)
    in
    main ()

let _ =
    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
    in

    let main () =
        let n = rdint () in
        let x = rdint () in
        let arr = Array.init n (fun _ -> rdint ()) in
        Array.sort compare arr;

        let r =
            let med = arr.((n - 1) / 2) in
            let rec search p v =
                if p < 0 || p >= n then p else
                if arr.(p) = x then p else search (p + v) v
            in
            if med = x then 0 else
            if med > x then (
                let p = search ((n - 1) / 2) (-1) in
                n - 2 * (p + 1)
            ) else (
                let p = search ((n - 1) / 2) 1 in
                p * 2 + 1 - n
            )
        in
        Printf.printf "%d\n" r
    in
    main ()


Shinju loves permutations very much! Today, she has borrowed a permutation $$$p$$$ from Juju to play with.The $$$i$$$-th cyclic shift of a permutation $$$p$$$ is a transformation on the permutation such that $$$p = [p_1, p_2, \ldots, p_n] $$$ will now become $$$ p = [p_{n-i+1}, \ldots, p_n, p_1,p_2, \ldots, p_{n-i}]$$$.Let's define the power of permutation $$$p$$$ as the number of distinct elements in the prefix maximums array $$$b$$$ of the permutation. The prefix maximums array $$$b$$$ is the array of length $$$n$$$ such that $$$b_i = \max(p_1, p_2, \ldots, p_i)$$$. For example, the power of $$$[1, 2, 5, 4, 6, 3]$$$ is $$$4$$$ since $$$b=[1,2,5,5,6,6]$$$ and there are $$$4$$$ distinct elements in $$$b$$$.Unfortunately, Shinju has lost the permutation $$$p$$$! The only information she remembers is an array $$$c$$$, where $$$c_i$$$ is the power of the $$$(i-1)$$$-th cyclic shift of the permutation $$$p$$$. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.Given the array $$$c$$$, determine if there exists a permutation $$$p$$$ that is consistent with $$$c$$$. You do not have to construct the permutation $$$p$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^3$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$c_1,c_2,\ldots,c_n$$$ ($$$1 \leq c_i \leq n$$$).  It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" if there is a permutation $$$p$$$ exists that satisfies the array $$$c$$$, and "NO" otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive response).

NoteIn the first test case, the permutation $$$[1]$$$ satisfies the array $$$c$$$.In the second test case, the permutation $$$[2,1]$$$ satisfies the array $$$c$$$.In the fifth test case, the permutation $$$[5, 1, 2, 4, 6, 3]$$$ satisfies the array $$$c$$$. Let's see why this is true.  The zeroth cyclic shift of $$$p$$$ is $$$[5, 1, 2, 4, 6, 3]$$$. Its power is $$$2$$$ since $$$b = [5, 5, 5, 5, 6, 6]$$$ and there are $$$2$$$ distinct elements — $$$5$$$ and $$$6$$$.  The first cyclic shift of $$$p$$$ is $$$[3, 5, 1, 2, 4, 6]$$$. Its power is $$$3$$$ since $$$b=[3,5,5,5,5,6]$$$.  The second cyclic shift of $$$p$$$ is $$$[6, 3, 5, 1, 2, 4]$$$. Its power is $$$1$$$ since $$$b=[6,6,6,6,6,6]$$$.  The third cyclic shift of $$$p$$$ is $$$[4, 6, 3, 5, 1, 2]$$$. Its power is $$$2$$$ since $$$b=[4,6,6,6,6,6]$$$.  The fourth cyclic shift of $$$p$$$ is $$$[2, 4, 6, 3, 5, 1]$$$. Its power is $$$3$$$ since $$$b = [2, 4, 6, 6, 6, 6]$$$.  The fifth cyclic shift of $$$p$$$ is $$$[1, 2, 4, 6, 3, 5]$$$. Its power is $$$4$$$ since $$$b = [1, 2, 4, 6, 6, 6]$$$. Therefore, $$$c = [2, 3, 1, 2, 3, 4]$$$.In the third, fourth, and sixth testcases, we can show that there is no permutation that satisfies array $$$c$$$.

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

let finish tab = let icount = ref 0 in
  let oky = ref true in
  if tab.(0) = 1 then incr icount ;
  if tab.(0) > tab.(Array.length tab -1) +1 then oky := false ;
  for i = 1 to Array.length tab -1 do
    if tab.(i) = 1 then incr icount ;
    if tab.(i) > tab.(i-1)+1 then oky := false ;
  done;
  (!icount = 1 && (!oky));;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let len = int_of_string(input_line stdin) in
  let str = (input_line stdin) in
  let toto = parse str len in
  let tototo = finish toto in
  if tototo then print_endline "YES" else print_endline "NO"
done;
;;


You have a rectangular chocolate bar consisting of n × m single squares. You want to eat exactly k squares, so you may need to break the chocolate bar. In one move you can break any single rectangular piece of chocolate in two rectangular pieces. You can break only by lines between squares: horizontally or vertically. The cost of breaking is equal to square of the break length.For example, if you have a chocolate bar consisting of 2 × 3 unit squares then you can break it horizontally and get two 1 × 3 pieces (the cost of such breaking is 32 = 9), or you can break it vertically in two ways and get two pieces: 2 × 1 and 2 × 2 (the cost of such breaking is 22 = 4).For several given values n, m and k find the minimum total cost of breaking. You can eat exactly k squares of chocolate if after all operations of breaking there is a set of rectangular pieces of chocolate with the total size equal to k squares. The remaining n·m - k squares are not necessarily form a single rectangular piece.

The first line of the input contains a single integer t (1 ≤ t ≤ 40910) — the number of values n, m and k to process. Each of the next t lines contains three integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ min(n·m, 50)) — the dimensions of the chocolate bar and the number of squares you want to eat respectively.

For each n, m and k print the minimum total cost needed to break the chocolate bar, in order to make it possible to eat exactly k squares.

NoteIn the first query of the sample one needs to perform two breaks:  to split 2 × 2 bar into two pieces of 2 × 1 (cost is 22 = 4),  to split the resulting 2 × 1 into two 1 × 1 pieces (cost is 12 = 1). In the second query of the sample one wants to eat 3 unit squares. One can use exactly the same strategy as in the first query of the sample.

let _ =
  let min (x : int) y = if x < y then x else y in
  let sb = Scanf.Scanning.stdib in
  let n = 30
  and m = 30
  and kk = 50 in
  let a =
    Array.init (n + 1)
      (fun _ -> Array.make_matrix (m + 1) (kk + 1) 100000000)
  in
    for i = 1 to n do
      for j = 1 to m do
	a.(i).(j).(0) <- 0;
	if i * j <= kk
	then a.(i).(j).(i * j) <- 0;
	for k = 1 to kk do
	  for i' = 1 to i - 1 do
	    for k' = 0 to k do
	      a.(i).(j).(k) <-
		min a.(i).(j).(k)
		(a.(i').(j).(k') + a.(i - i').(j).(k - k') + j * j);
	    done;
	  done;
	  for j' = 1 to j - 1 do
	    for k' = 0 to k do
	      a.(i).(j).(k) <-
		min a.(i).(j).(k)
		(a.(i).(j').(k') + a.(i).(j - j').(k - k') + i * i);
	    done;
	  done;
	  (*Printf.printf "asd %d %d %d  %d\n" i j k a.(i).(j).(k);*)
	done
      done
    done;
    let t = Scanf.bscanf sb "%d " (fun s -> s) in
      for ca = 1 to t do
	let n = Scanf.bscanf sb "%d " (fun s -> s) in
	let m = Scanf.bscanf sb "%d " (fun s -> s) in
	let kk = Scanf.bscanf sb "%d " (fun s -> s) in
	  Printf.printf "%d\n" a.(n).(m).(kk)
      done

let _ =
  let min (x : int) y = if x < y then x else y in
  let sb = Scanf.Scanning.stdib in
  let n = 30
  and m = 30
  and kk = 50 in
  let a =
    Array.init (n + 1)
      (fun _ -> Array.make_matrix (m + 1) (kk + 1) 1000000000)
  in
    for i = 1 to n do
      for j = 1 to m do
	a.(i).(j).(0) <- 0;
	if i * j <= kk
	then a.(i).(j).(i * j) <- 0;
	for k = 1 to kk do
	  for i' = 1 to i - 1 do
	    for k' = 0 to k do
	      a.(i).(j).(k) <-
		min a.(i).(j).(k)
		(a.(i').(j).(k') + a.(i - i').(j).(k - k') + j * j);
	    done;
	  done;
	  for j' = 1 to j - 1 do
	    for k' = 0 to k do
	      a.(i).(j).(k) <-
		min a.(i).(j).(k)
		(a.(i).(j').(k') + a.(i).(j - j').(k - k') + i * i);
	    done;
	  done;
	  (*Printf.printf "asd %d %d %d  %d\n" i j k a.(i).(j).(k);*)
	done
      done
    done;
    let t = Scanf.bscanf sb "%d " (fun s -> s) in
      for ca = 1 to t do
	let n = Scanf.bscanf sb "%d " (fun s -> s) in
	let m = Scanf.bscanf sb "%d " (fun s -> s) in
	let kk = Scanf.bscanf sb "%d " (fun s -> s) in
	  Printf.printf "%d\n" a.(n).(m).(kk)
      done

let _ =
  let min (x : int) y = if x < y then x else y in
  let sb = Scanf.Scanning.stdib in
  let t = Scanf.bscanf sb "%d " (fun s -> s) in
    for ca = 1 to t do
      let n = Scanf.bscanf sb "%d " (fun s -> s) in
      let m = Scanf.bscanf sb "%d " (fun s -> s) in
      let kk = Scanf.bscanf sb "%d " (fun s -> s) in
      let a =
	Array.init (n + 1)
	  (fun _ -> Array.make_matrix (m + 1) (kk + 1) 1000000000)
      in
	for i = 1 to n do
	  for j = 1 to m do
	    a.(i).(j).(1) <- 0;
	    for k = 2 to kk do
	      for i' = 1 to i - 1 do
		for k' = 1 to k - 1 do
		  a.(i).(j).(k) <-
		    min a.(i).(j).(k)
		    (a.(i').(j).(k') + a.(i - i').(j).(k - k') + j * j)
		done;
	      done;
	      for j' = 1 to j - 1 do
		for k' = 1 to k - 1 do
		  a.(i).(j).(k) <-
		    min a.(i).(j).(k)
		    (a.(i).(j').(k') + a.(i).(j - j').(k - k') + i * i)
		done;
	      done;
	    done
	  done
	done;
	Printf.printf "%d\n" a.(n).(m).(kk)
    done


Friday is Polycarpus' favourite day of the week. Not because it is followed by the weekend, but because the lessons on Friday are 2 IT lessons, 2 math lessons and 2 literature lessons. Of course, Polycarpus has prepared to all of them, unlike his buddy Innocentius. Innocentius spent all evening playing his favourite game Fur2 and didn't have enough time to do the literature task. As Innocentius didn't want to get an F, he decided to do the task and read the book called "Storm and Calm" during the IT and Math lessons (he never used to have problems with these subjects). When the IT teacher Mr. Watkins saw this, he decided to give Innocentius another task so that the boy concentrated more on the lesson and less — on the staff that has nothing to do with IT. Mr. Watkins said that a palindrome is a string that can be read the same way in either direction, from the left to the right and from the right to the left. A concatenation of strings a, b is a string ab that results from consecutive adding of string b to string a. Of course, Innocentius knew it all but the task was much harder than he could have imagined. Mr. Watkins asked change in the "Storm and Calm" the minimum number of characters so that the text of the book would also be a concatenation of no more than k palindromes. Innocentius can't complete the task and therefore asks you to help him.

The first input line contains a non-empty string s which is the text of "Storm and Calm" (without spaces). The length of the string s does not exceed 500 characters. String s consists of uppercase and lowercase Latin letters. The second line contains a single number k (1 ≤ k ≤ |s|, where |s| represents the length of the string s).

Print on the first line the minimum number of changes that Innocentius will have to make. Print on the second line the string consisting of no more than k palindromes. Each palindrome should be non-empty and consist of uppercase and lowercase Latin letters. Use the character "+" (ASCII-code 43) to separate consecutive palindromes. If there exist several solutions, print any of them. The letters' case does matter, that is an uppercase letter is not considered equivalent to the corresponding lowercase letter.

let getint () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun i->i)
let getstr () = Scanf.bscanf Scanf.Scanning.stdin " %s" (fun s-> s)
let getchar () = Scanf.bscanf Scanf.Scanning.stdin " %c" (fun i->i)
let inf = 1000000007

let s = getstr ()
let n = String.length s
let k = getint ()
let cost = Array.make_matrix n n 0
let dp = Array.make_matrix (n+1) (k+1) inf
let tb = Array.make_matrix (n+1) (k+1) 0

let calc_cost () =
  for i = 0 to n-1 do
    for j = i to n-1 do
      let i' = ref i and j' = ref j in
        while !i' <= !j' do
          if s.[!i'] <> s.[!j'] then cost.(i).(j) <- cost.(i).(j) + 1;
          incr i'; decr j'
        done
    done
  done

let minimize () =
  for j = 0 to k do
    dp.(0).(j) <- 0
  done;
  for i = 1 to n do
    for j = 1 to k do
      for m = 0 to i-1 do
        if dp.(i).(j) > dp.(m).(j-1) + cost.(m).(i-1)
        then
          begin
            dp.(i).(j) <- dp.(m).(j-1) + cost.(m).(i-1);
            tb.(i).(j) <- m
          end
      done
    done
  done

let trace_back () =
  let len = ref n and k' = ref k and l = ref [] in
  while !len <> 0 do
    l := (!len - tb.(!len).(!k')) :: !l;
    len := tb.(!len).(!k');
    decr k'
  done;
  let last = ref 0 in
  List.iter
  (
      fun len ->
        let i = ref !last and j = ref (!last + len - 1) in
        while !i <= !j do
          if s.[!i] <> s.[!j] then s.[!i] <- s.[!j];
          incr i; decr j
        done;
        for i = !last to !last+ len - 1 do
          print_char s.[i];
        done;
        last := !last + len;
        if !last <> n then print_char '+'
        else print_char '\n';
    )
    !l

let _ =
  calc_cost ();
  minimize ();
  print_int dp.(n).(k); print_newline ();
  trace_back ()

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

let read_string () = Scanf.scanf " %s " (fun x -> x);;

let str = read_string ();;
let k = read_int ();;
let n = String.length str;;

let dp = Array.create_matrix 505 505 10000000;;
let cnt = Array.create_matrix 505 505 0;;
let mark = Array.create_matrix 505 505 0;;

let _ = for i = 0 to (n-1) do
           for j = (i+1) to (n-1) do
              for t1 = i to ((j+i)/2) do
                 if str.[t1]!=str.[j-t1+i] then cnt.(i).(j) <- cnt.(i).(j) + 1
              done
            done
         done;;

let _ = for i = 0 to (n-1) do
              dp.(i).(1) <- cnt.(0).(i);
              mark.(i).(1) <- -1
        done;;

let _ = for i = 0 to (n-1) do
            for j = 2 to (min (i+1) k) do
                for t = 0 to (i-1) do
                    if dp.(t).(j-1) + cnt.(t+1).(i) < dp.(i).(j) then
                     begin
                        dp.(i).(j) <- dp.(t).(j-1) + cnt.(t+1).(i);
                        mark.(i).(j) <- t
                     end
                done
            done
         done;;

let ans = ref 10000000;;
let len = ref (-1);;
let p = ref 0;;

let _ = for i = 1 to k do
            if dp.(n-1).(i) < !ans then
             begin
               ans := dp.(n-1).(i);
               len := i;
               p := mark.(n-1).(i)
             end
        done;;

let rec solve2 str i j =
   if i>=j then str
   else if str.[i]!=str.[j] then begin str.[i] <- str.[j]; solve2 str (i+1) (j-1) end
   else solve2 str (i+1) (j-1);;

let rec solve str len s t =
     if len = 1 then solve2 (String.sub str s (t-s+1)) 0 (t-s)
     else solve (String.sub str 0 s) (len-1) (mark.(s-1).(len-1)+1) (s-1) ^ "+" ^ solve2 (String.sub str s (t-s+1)) 0 (t-s);;

if n = 1 then Printf.printf "0\n%s\n" str
else Printf.printf "%d\n%s\n" (!ans) (solve str (!len) (!p+1) (n-1));;

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

let read_string () = Scanf.scanf " %s " (fun x -> x);;

let str = read_string ();;
let k = read_int ();;
let n = String.length str;;

let dp = Array.create_matrix 505 505 10000000;;
let cnt = Array.create_matrix 505 505 0;;
let mark = Array.create_matrix 505 505 0;;

let _ = for i = 0 to (n-1) do
           for j = (i+1) to (n-1) do
              for t1 = i to ((j+i)/2) do
                 if str.[t1]!=str.[j-t1+i] then cnt.(i).(j) <- cnt.(i).(j) + 1
              done
            done
         done;;

let _ = for i = 0 to (n-1) do
              dp.(i).(1) <- cnt.(0).(i);
              mark.(i).(1) <- -1
        done;;

let _ = for i = 0 to (n-1) do
            for j = 2 to (min (i+1) k) do
                for t = 0 to (i-1) do
                    if dp.(t).(j-1) + cnt.(t+1).(i) < dp.(i).(j) then
                     begin
                        dp.(i).(j) <- dp.(t).(j-1) + cnt.(t+1).(i);
                        mark.(i).(j) <- t
                     end
                done
            done
         done;;

let ans = ref 10000000;;
let len = ref (-1);;
let p = ref 0;;

let _ = for i = 1 to k do
            if dp.(n-1).(i) < !ans then
             begin
               ans := dp.(n-1).(i);
               len := i;
               p := mark.(n-1).(i)
             end
        done;;

let rec solve2 str i j =
   if i>=j then str
   else if str.[i]!=str.[j] then begin str.[i] <- str.[j]; solve2 str (i+1) (j-1) end
   else solve2 str (i+1) (j-1);;

let rec solve str len s t str_ans =
     if len = 0 then str_ans
     else if len = 1 then solve "" 0 0 0 (solve2 (String.sub str s (t-s+1)) 0 (t-s) ^ str_ans )
     else solve (String.sub str 0 s) (len-1) (mark.(s-1).(len-1)+1) (s-1)  ("+" ^ solve2 (String.sub str s (t-s+1)) 0 (t-s) ^  str_ans) ;;

if n = 1 then Printf.printf "0\n%s\n" str
else let str_ans = (solve str (!len) (!p+1) (n-1) "") in Printf.printf "%d\n%s\n" (!ans) str_ans;;

let s = input_line stdin;;
let n = String.length s;;
let k = read_int ();;
let f = Array.make_matrix n n 0;;
for i = n - 1 downto 0 do
 for j = i to n - 1 do
  if i == j then begin
   f.(i).(j) <- 0
  end else if i + 1 == j then begin
   f.(i).(j) <- if s.[i] != s.[j] then 1 else 0;
  end else begin
   f.(i).(j) <- f.(i + 1).(j - 1) + if s.[i] != s.[j] then 1 else 0;
  end;
 done
done;;
let g = Array.make_matrix (n + 1) (n + 1) 12345;;
let p = Array.make_matrix (n + 1) (n + 1) 12345;;
g.(0).(0) <- 0;;
for i = 0 to n - 1 do
 for j = 0 to i do
  for l = i + 1 to n do
   let cur = g.(i).(j) + f.(i).(l - 1) in
   if g.(l).(j + 1) > cur then begin
    g.(l).(j + 1) <- cur;
    p.(l).(j + 1) <- i;
   end
  done;
 done
done;;
let h = Array.make n "";;
let u = ref 0;;
let v = ref n;;
for j = 0 to k do
 if g.(n).(!u) > g.(n).(j) then begin u := j end
done;;
Printf.printf "%d\n" g.(n).(!u);;
let w = ref 0;;
for j = 0 to !u - 1 do
 let c = String.sub s p.(!v).(!u - j) (!v - p.(!v).(!u - j)) in
 let t = String.length c in
 let x = ref 0 in
 let y = ref (t - 1) in begin
  while !x < !y do
   c.[!y] <- c.[!x];
   x := !x + 1;
   y := !y - 1;
  done;
  h.(j) <- c;
  v := p.(!v).(!u - j);
 end;
done;;
for j = !u - 1 downto 0 do
 Printf.printf "%s%s" h.(j) (if j == 0 then "\n" else "+");
done;;

let main() =
  let s = Scanf.scanf " %s" (fun i -> i) in
  let n = String.length s in
  let k = Scanf.scanf " %d" (fun i -> i) in
  let a = Array.make_matrix n n 0 in
  let rec d1 l =
    let rec d2 i =
      let j = i + l - 1 in
      if j < n then (a.(i).(j) <- (if l == 2 then 0 else a.(i+1).(j-1)) + (if s.[i] == s.[j] then 0 else 1); d2 (i+1)) else ()
    in
    d2 0;
    if l < n then d1 (l+1) else ()
  in
  d1 2;
  let b = Array.make_matrix (k+1) (n+1) (2*n) in
  let p = Array.make_matrix (k+1) (n+1) (-1) in
  b.(0).(0) <- 0;
  let rec f1 l =
    let br = b.(l-1) in let bn = b.(l) in
    let rec f2 i =
      let x = br.(i) in let y = a.(i) in
      let rec f3 j =
        let v = x + y.(j-1) in
        if bn.(j) > v then (bn.(j) <- v; p.(l).(j) <- i) else ();
        if j < n then f3 (j+1) else ()
      in
      f3 (i+1);
      if i < (n-1) then f2 (i+1) else ()
    in
    f2 0;
    if l < k then f1 (l+1) else ();
  in
  f1 1;
  let d = Array.init k (fun i -> b.(i+1).(n), i+1) in
  let best_v, best_k = Array.fold_left (fun b x -> if (fst b) < (fst x) then b else x) (2*n, -1) d in
  let rec h i j =
    if i < j then (s.[j] <- s.[i]; h (i+1) (j-1)) else ()
  in
  let g i j =
    h i j;
    String.sub s i (j - i + 1)
  in
  let rec ans k j l =
    if k = 0 then l else (let i = p.(k).(j) in ans (k-1) i ((g i (j-1))::l))
  in
  Printf.printf "%d\n%s\n" best_v (String.concat "+" (ans best_k n []))
  ;;
main()

let main() =
  let s = Scanf.scanf " %s" (fun i -> i) in
  let n = String.length s in
  let k = Scanf.scanf " %d" (fun i -> i) in
  let a = Array.make_matrix n n 0 in
  for l = 2 to n do
    for i = 0 to n-l do
      let j = i + l - 1 in
      a.(i).(j) <- (if l == 2 then 0 else a.(i+1).(j-1)) + (if s.[i] == s.[j] then 0 else 1);
    done;
  done;
  let b = Array.make_matrix (k+1) (n+1) (2*n) in let p = Array.make_matrix (k+1) (n+1) (-1) in
  b.(0).(0) <- 0;
  for l = 1 to k do
    let br = b.(l-1) in let bn = b.(l) in
    for i = 0 to (n-1) do
      let x = br.(i) in let y = a.(i) in
      for j = (i+1) to n do
        let v = x + y.(j-1) in
        if bn.(j) > v then (bn.(j) <- v; p.(l).(j) <- i) else ();
      done;
    done;
  done;
  let d = Array.init k (fun i -> b.(i+1).(n), i+1) in
  let best_v, best_k = Array.fold_left (fun b x -> if (fst b) < (fst x) then b else x) (2*n, -1) d in
  let rec h i j =
    if i < j then (s.[j] <- s.[i]; h (i+1) (j-1)) else ()
  in
  let g i j =
    h i j;
    String.sub s i (j - i + 1)
  in
  let rec ans k j l =
    if k = 0 then l else (let i = p.(k).(j) in ans (k-1) i ((g i (j-1))::l))
  in
  Printf.printf "%d\n%s\n" best_v (String.concat "+" (ans best_k n []))
  ;;
main()

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = String.length s in
  let c = Array.make_matrix n n 0 in
  let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	let d = ref 0 in
	  for k = 0 to (j - i + 1) / 2 - 1 do
	    if s.[i + k] <> s.[j - k]
	    then incr d;
	  done;
	  c.(i).(j) <- !d
      done
    done
  in
  (*let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	Printf.printf "%d " c.(i).(j)
      done;
      Printf.printf "\n"
    done
  in*)
  (*let min (x : int) y = if x < y then x else y in*)
  let a = Array.make_matrix (k + 1) (n + 1) 10000 in
  let d = Array.make_matrix (k + 1) (n + 1) 10000 in
    a.(0).(0) <- 0;
    for i = 1 to k do
      a.(i).(0) <- 0;
      for j = 1 to n do
	for r = 0 to j - 1 do
	  if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (
	    a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);
	    d.(i).(j) <- r;
	  )
	done
      done
    done;
    (*let _ =
      for i = 0 to k do
	for j = 0 to n do
	  Printf.printf "%d(%d) " a.(i).(j) d.(i).(j)
	done;
	Printf.printf "\n"
      done
    in*)
    let palindromize s =
      let n = String.length s in
	for i = 0 to n / 2 - 1 do
	  if s.[i] <> s.[n - i - 1]
	  then s.[i] <- s.[n - i - 1]
	done
    in
    let res = a.(k).(n) in
    let ss = ref [] in
    let _ =
      let i = ref n in
	for j = k downto 1 do
	  if !i > 0 then (
	    let r = d.(j).(!i) in
	      ss := String.sub s r (!i - r) :: !ss;
	      i := r;
	  )
	done
    in
      assert (!ss <> []);
      Printf.printf "%d\n" res;
      let f = ref true in
	List.iter
	  (fun s ->
	     if not !f
	     then Printf.printf "+";
	     f := false;
	     assert (s <> "");
	     palindromize s;
	     Printf.printf "%s" s
	  ) !ss;
	Printf.printf "\n"

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

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

let argmin i j f =
  fold i j (
    fun k (index,v) -> let m = (f k) in if m<v then (k,m) else (index,v)
  ) (i-1, inf)

let s = read_string()
let k = read_int()
let n = String.length s

let dist = Array.make_matrix n n 0

let delta i j = if s.[i] = s.[j] then 0 else 1

let () =
  for l = 1 to n do
    for i=0 to n-l do
      let j = i+l-1 in
	dist.(i).(j) <-
	  if i+1 <= j-1 then dist.(i+1).(j-1) + (delta i j)
	  else delta i j
    done
  done

let c = Array.make_matrix n (k+1) (-1)
let bj = Array.make_matrix n (k+1) 0

let rec cost i p =
  if i<0 then 0 else
    if c.(i).(p) >= 0 then c.(i).(p) else
      let cc =
	if p=1 then dist.(0).(i) else
	  let (j,opt) = argmin 0 i (fun j -> (cost (j-1) (p-1)) + dist.(j).(i)) in
	    bj.(i).(p) <- j;
	    opt
      in
	c.(i).(p) <- cc;
	cc

let make_palindrome i j = (* return a palindrome of s.[i...j] *)
  let l = j-i+1 in
  let r = String.sub s i l in
    for k=0 to l/2-1 do
      r.[k] <- r.[l-1-k]
    done;
    r

let rec build_soln i p ac =
  if i<0 || p<1 then ac else
    let j = bj.(i).(p) in
      build_soln (j-1) (p-1) ((make_palindrome j i)::ac)

let () =
  Printf.printf "%d\n" (cost (n-1) k);
  Printf.printf "%s\n" (String.concat "+" (build_soln (n-1) k []));

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

let read_string () = Scanf.scanf " %s " (fun x -> x);;

let str = read_string ();;
let k = read_int ();;
let n = String.length str;;

let dp = Array.create_matrix 505 505 10000000;;
let cnt = Array.create_matrix 505 505 0;;
let mark = Array.create_matrix 505 505 0;;

let _ = for i = 0 to (n-1) do
           for j = (i+1) to (n-1) do
              for t1 = i to ((j+i)/2) do
                 if str.[t1]!=str.[j-t1+i] then cnt.(i).(j) <- cnt.(i).(j) + 1
                 else ()
              done
            done
         done;;

let _ = for i = 0 to (n-1) do
            begin
              dp.(i).(1) <- cnt.(0).(i);
              mark.(i).(1) <- -1
            end
        done;;

let _ = for i = 0 to (n-1) do
            for j = 2 to (min (i+1) k) do
                for t = 0 to (i-1) do
                    if dp.(t).(j-1) + cnt.(t+1).(i) < dp.(i).(j) then
                        dp.(i).(j) <- dp.(t).(j-1) + cnt.(t+1).(i);
                        mark.(i).(j) <- t
                done
            done
         done;;

let ans = ref 10000000;;
let len = ref (-1);;
let p = ref 0;;

let _ = for i = 1 to k do
            if dp.(n-1).(i) < !ans then
               ans := dp.(n-1).(i);
               len := i;
               p := mark.(n-1).(i)
        done;;

let rec solve2 str i j =
   if i>=j then str
   else if str.[i]!=str.[j] then begin str.[i] <- str.[j]; solve2 str (i+1) (j-1) end
   else solve2 str (i+1) (j-1);;

let rec solve str len s t =
     if len = 1 then solve2 (String.sub str s (t-s+1)) s t
     else solve (String.sub str 0 s) (len-1) (mark.(s-1).(len-1)+1) (s-1) ^ "+" ^ solve2 (String.sub str s (t-s+1)) s t;;

if n = 1 then Printf.printf "0\n%s\n" str
else Printf.printf "%d\n%s\n" (!ans) (solve str (!len) (!p+1) (n-1));;

(*************** Ocaml stdio functions **********************)
let stdin_stream = Stream.of_channel stdin;;
let stdout_buffer = Buffer.create 65536;;
let rec gi() =
  match Stream.next stdin_stream with
    '-' ->  - (ri 0)
  | '+' ->  ri 0
  | '0'..'9' as c -> ri ((int_of_char c) - 48)
  | _ -> gi ()
and ri x =
  match Stream.next stdin_stream with
    '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))
  | _ -> x
;;
let flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;
let putchar c =
  if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();
  Buffer.add_char stdout_buffer c;;
let rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;
let pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;
let pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\n' else ' ')) a;;
(*************** Ocaml solution ******************************)
open Array
let main() =
  let s = Scanf.scanf "%s" (fun i -> i) in
  let mk = Scanf.scanf " %d" (fun i -> i) in
  let l = String.length s in
  let a = make_matrix l l (-1, 0) in
  let b = make_matrix (mk+1) (l+1) 10000 in
  let c = make_matrix (mk+1) (l+1) (-1) in
  let rec f i j =
    if (j-i) <= 1 then (0,0)
    else (if (fst a.(i).(j)) >= 0 then a.(i).(j)
          else
            (
            let (u,_) = f (i+1) (j-1) in
            let r = if s.[i] == s.[j] then (u, 0) else (u + 1, 1) in
            a.(i).(j) <- r;
            r
            )
         )
    in
  let rec g i j =
    if (j-i) <= 1 then ()
    else ((match snd (f i j) with
            1 -> s.[i] <- s.[j]
          | _ -> ()
           ); g (i+1) (j-1))
    in
  b.(mk).(0) <- 0;
  for k = (mk - 1) downto 0 do
    for i = 0 to (l - 1) do
      let w = b.(k+1).(i) in
      for j = (i+1) to l do
        let v = w + (fst (f i (j-1))) in
        if v < b.(k).(j) then ( b.(k).(j) <- v; c.(k).(j) <- i )
        else ()
        done
      done
    done;
  let rec h j k a =
    if k == mk then a
    else (
      let i = c.(k).(j) in
      g i (j-1);
      let ss = String.sub s i (j - i) in
      h i (k+1) (ss::a)
      )
    in
  let y = h l 0 [] in
  Printf.printf "%d\n%s\n" (b.(0).(l)) (String.concat "+" y)
  ;;
main();;
flushout ()

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = String.length s in
  let c = Array.make_matrix n n 0 in
  let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	let d = ref 0 in
	  for k = 0 to (j - i + 1) / 2 - 1 do
	    if s.[i + k] <> s.[j - k]
	    then incr d;
	  done;
	  c.(i).(j) <- !d
      done
    done
  in
  (*let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	Printf.printf "%d " c.(i).(j)
      done;
      Printf.printf "\n"
    done
  in*)
  (*let min (x : int) y = if x < y then x else y in*)
  let a = Array.make_matrix (k + 1) (n + 1) 10000 in
  let d = Array.make_matrix (k + 1) (n + 1) 10000 in
    a.(0).(0) <- 0;
    for i = 1 to k do
      a.(i).(0) <- 0;
      for j = 0 to n do
	for r = 0 to j - 1 do
	  if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (
	    a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);
	    d.(i).(j) <- r;
	  )
	done
      done
    done;
    (*let _ =
      for i = 0 to k do
	for j = 0 to n do
	  Printf.printf "%d " a.(i).(j)
	done;
	Printf.printf "\n"
      done
    in*)
    let palindromize s =
      let n = String.length s in
	for i = 0 to n / 2 do
	  if s.[i] <> s.[n - i - 1]
	  then s.[i] <- s.[n - i - 1]
	done
    in
    let res = a.(k).(n) in
    let ss = ref [] in
    let _ =
      let i = ref n in
	for j = k downto 1 do
	  if !i > 0 then (
	    let r = d.(k).(!i) in
	      ss := String.sub s r (!i - r) :: !ss;
	      i := r;
	  )
	done
    in
      Printf.printf "%d\n" res;
      let f = ref true in
	List.iter
	  (fun s ->
	     if not !f
	     then Printf.printf "+";
	     f := false;
	     palindromize s;
	     Printf.printf "%s" s
	  ) !ss;
	Printf.printf "\n"

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = String.length s in
  let c = Array.make_matrix n n 0 in
  let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	let d = ref 0 in
	  for k = 0 to (j - i + 1) / 2 - 1 do
	    if s.[i + k] <> s.[j - k]
	    then incr d;
	  done;
	  c.(i).(j) <- !d
      done
    done
  in
  (*let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	Printf.printf "%d " c.(i).(j)
      done;
      Printf.printf "\n"
    done
  in*)
  (*let min (x : int) y = if x < y then x else y in*)
  let a = Array.make_matrix (k + 1) (n + 1) 10000 in
  let d = Array.make_matrix (k + 1) (n + 1) 10000 in
    a.(0).(0) <- 0;
    for i = 1 to k do
      a.(i).(0) <- 0;
      for j = 1 to n do
	for r = 0 to j - 1 do
	  if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (
	    a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);
	    d.(i).(j) <- r;
	  )
	done
      done
    done;
    (*let _ =
      for i = 0 to k do
	for j = 0 to n do
	  Printf.printf "%d " a.(i).(j)
	done;
	Printf.printf "\n"
      done
    in*)
    let palindromize s =
      let n = String.length s in
	for i = 0 to n / 2 - 1 do
	  if s.[i] <> s.[n - i - 1]
	  then s.[i] <- s.[n - i - 1]
	done
    in
    let res = a.(k).(n) in
    let ss = ref [] in
    let _ =
      let i = ref n in
	for j = k downto 1 do
	  if !i > 0 then (
	    let r = d.(k).(!i) in
	      ss := String.sub s r (!i - r) :: !ss;
	      i := r;
	  )
	done
    in
      assert (!ss <> []);
      Printf.printf "%d\n" res;
      let f = ref true in
	List.iter
	  (fun s ->
	     if not !f
	     then Printf.printf "+";
	     f := false;
	     assert (s <> "");
	     palindromize s;
	     Printf.printf "%s" s
	  ) !ss;
	Printf.printf "\n"

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = String.length s in
  let c = Array.make_matrix n n 0 in
  let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	let d = ref 0 in
	  for k = 0 to (j - i + 1) / 2 - 1 do
	    if s.[i + k] <> s.[j - k]
	    then incr d;
	  done;
	  c.(i).(j) <- !d
      done
    done
  in
  (*let _ =
    for i = 0 to n - 1 do
      for j = i to n - 1 do
	Printf.printf "%d " c.(i).(j)
      done;
      Printf.printf "\n"
    done
  in*)
  (*let min (x : int) y = if x < y then x else y in*)
  let a = Array.make_matrix (k + 1) (n + 1) 10000 in
  let d = Array.make_matrix (k + 1) (n + 1) 10000 in
    a.(0).(0) <- 0;
    for i = 1 to k do
      a.(i).(0) <- 0;
      for j = 1 to n do
	for r = 0 to j - 1 do
	  if a.(i).(j) > a.(i - 1).(r) + c.(r).(j - 1) then (
	    a.(i).(j) <- a.(i - 1).(r) + c.(r).(j - 1);
	    d.(i).(j) <- r;
	  )
	done
      done
    done;
    (*let _ =
      for i = 0 to k do
	for j = 0 to n do
	  Printf.printf "%d " a.(i).(j)
	done;
	Printf.printf "\n"
      done
    in*)
    let palindromize s =
      let n = String.length s in
	for i = 0 to n / 2 do
	  if s.[i] <> s.[n - i - 1]
	  then s.[i] <- s.[n - i - 1]
	done
    in
    let res = a.(k).(n) in
    let ss = ref [] in
    let _ =
      let i = ref n in
	for j = k downto 1 do
	  if !i > 0 then (
	    let r = d.(k).(!i) in
	      ss := String.sub s r (!i - r) :: !ss;
	      i := r;
	  )
	done
    in
      assert (!ss <> []);
      Printf.printf "%d\n" res;
      let f = ref true in
	List.iter
	  (fun s ->
	     if not !f
	     then Printf.printf "+";
	     f := false;
	     assert (s <> "");
	     palindromize s;
	     Printf.printf "%s" s
	  ) !ss;
	Printf.printf "\n"


You have an array a[1], a[2], ..., a[n], containing distinct integers from 1 to n. Your task is to sort this array in increasing order with the following operation (you may need to apply it multiple times):  choose two indexes, i and j (1 ≤ i < j ≤ n; (j - i + 1) is a prime number);  swap the elements on positions i and j; in other words, you are allowed to apply the following sequence of assignments: tmp = a[i], a[i] = a[j], a[j] = tmp (tmp is a temporary variable). You do not need to minimize the number of used operations. However, you need to make sure that there are at most 5n operations.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n distinct integers a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ n).

In the first line, print integer k (0 ≤ k ≤ 5n) — the number of used operations. Next, print the operations. Each operation must be printed as "i j" (1 ≤ i < j ≤ n; (j - i + 1) is a prime). If there are multiple answers, you can print any of them.

let n=Scanf.scanf "%d " (fun x->x);;
let prime=Array.make 100001 false;;
let sprime=Array.make 100001 0;;
let tri=Array.make n (0,0);;
let vec=Array.make n 0;;
let permu=Array.make n 0;;
for i=0 to n-1 do
   permu.(i)<-i
done;;
let permu_inv=Array.make n 0;;
for i=0 to n-1 do
   permu_inv.(i)<-i
done;;
let l=ref [(0,0)];;
l:=[];;

for i=0 to n-2 do
   let x=Scanf.scanf "%d " (fun x->x) in
   vec.(i)<-x;
   tri.(i)<-(x,i)
done;;
let x=Scanf.scanf "%d" (fun x->x) in (vec.(n-1)<-x;tri.(n-1)<-(x,n-1));;
Array.sort (fun (x,i) (y,j) -> if x=y then 0 else if x<y then -1 else 1) tri;;

let is_prime a=
   let c=int_of_float(sqrt(float_of_int(a))) in
   let b=ref true in
   let i=ref 2 in
   while !b&&(!i<=c) do
      if (a mod !i)=0 then b:=false;
      incr i
   done;
   !b;;

for i=2 to 100000 do
   if is_prime i then prime.(i)<-true
done;;

let h=ref 2;;
for i=2 to 100000 do
   if prime.(i) then h:=i;
   sprime.(i)<- !h
done;;

for i=0 to n-2 do
   let (x,indi)=tri.(i) in
   let ind=ref permu.(indi) in
   while !ind<>i do
      let d=sprime.(!ind-i+1) and temp=vec.(!ind) in
      let j= !ind-d+1 in
         vec.(!ind)<-vec.(j);
         vec.(j)<-temp;
         l:=(j, !ind)::(!l);
         permu.(permu_inv.(j))<- !ind;
         permu_inv.(!ind)<-permu_inv.(j);
         ind:=j;
   done
done;;

let rec taille=function
|[]->0
|(_,_)::t->1+taille t;;

print_int(taille !l);;
print_newline();;

let rec print_list=function
|[]->()
|(i,j)::t->print_list t;Printf.printf "%d %d\n" (i+1) (j+1);;

print_list !l;;


Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once:   Polycarp chooses $$$k$$$ ($$$0 \le k \le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \ldots, i_k$$$);  Polycarp distributes their $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies:   Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^4$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case output:    the minimum value of $$$k$$$, such that Polycarp can choose exactly $$$k$$$ friends so that he can redistribute the candies in the desired way;  "-1" if no such value $$$k$$$ exists.

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int () in
    let a = Array.init n read_int in
    let total = sum 0 (n-1) (fun i -> a.(i)) in
    if total mod n <> 0 then printf "-1\n" else (
      let nbig = sum 0 (n-1) (fun i -> if a.(i) > total/n then 1 else 0) in
      printf "%d\n" nbig
    )
  done


You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Each of the next $$$T$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 998244353$$$) — inclusive borders of the range. It is guaranteed that testset only includes queries, which have at least one suitable pair.

Print $$$T$$$ lines, each line should contain the answer — two integers $$$x$$$ and $$$y$$$ such that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$. The answer in the $$$i$$$-th line should correspond to the $$$i$$$-th query from the input. If there are multiple answers, print any of them.

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 Int64_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
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  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 slen s = String.length s
  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 t = gi 0 in
  rep 1L t (fun _ ->
    let l,r = g2 0 in
    (* let f,u,v = ref true,ref l,ref r in
    while !f do
      while !f do
        if !v mod !u = 0L then (
          f := false;
          printf "%Ld %Ld\n" !u !v
        );
        v -= 1L
      done;
      u += 1L;
    done; *)
    (* let f,u = ref true,ref l in
    while !f do
    done *)
    (* if l*2L > r then (

    ) *)
    printf "%Ld %Ld\n" l (l*2L);
  )

Scanf.(Array.(
  let t = scanf " %d" @@ fun v -> v in
  init t (fun _ ->
    let l = scanf " %d %d" @@ fun p _ -> p in
    Printf.printf "%d %d\n" l (l*2))))


One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.

The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).

In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and k=read_int();;
let m=n*(n-1)/2;;
let nb=k*n;;
let mat=Array.make_matrix (n+1) (n+1) 0;;
let b=ref true

let rec win r i j=
if r=0 then ()
else if i=j then win r i (j+1)
else if j>n then b:=false
else
   begin
   if mat.(i).(j)=0 then (mat.(i).(j)<-1;mat.(j).(i)<-(-1);win (r-1) i (j+1))
   else win r i (j+1)
   end;;

if nb>m then b:=false;;

for i=1 to n do
   win k i 1
done;;

if !b=false then print_int(-1) else
begin
print_int nb;
print_newline();
for i=1 to n do
   for j=1 to n do
      if mat.(i).(j)=1 then Printf.printf "%d %d\n" i j
   done
done
end;;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make_matrix n n 0 in
  let c = Array.make n 0 in
  let tot = ref true in
  let m = ref 0 in
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if i <> j && c.(i) < k && a.(i).(j) = 0 then (
	  c.(i) <- c.(i) + 1;
	  incr m;
	  a.(i).(j) <- 1;
	  a.(j).(i) <- -1;
	)
      done
    done;
    for i = 0 to n - 1 do
      if c.(i) < k
      then tot := false;
    done;
    if not !tot
    then Printf.printf "-1\n"
    else (
      Printf.printf "%d\n" (n * k);
      for i = 0 to n - 1 do
	for j = 0 to n - 1 do
	  if a.(i).(j) = 1
	  then Printf.printf "%d %d\n" (i + 1) (j + 1);
	done
      done;
    )


Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ au.Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u.

The first line contains single integer n (1 ≤ n ≤ 2·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the integers written in the vertices. The next (n - 1) lines contain two integers each. The i-th of these lines contains integers pi and wi (1 ≤ pi ≤ n, 1 ≤ wi ≤ 109) — the parent of the (i + 1)-th vertex in the tree and the number written on the edge between pi and (i + 1). It is guaranteed that the given graph is a tree.

Print n integers — the i-th of these numbers should be equal to the number of vertices that the i-th vertex controls.

NoteIn the example test case the vertex 1 controls the vertex 3, the vertex 3 controls the vertex 5 (note that is doesn't mean the vertex 1 controls the vertex 5).

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

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

  (*
     The representation is (offset, size, set)
     where the set is a set of pairs {(dist,vertex_no), ... }
  *)

let make_ms (dist,vertex_no) = (0L, 1, Pset.singleton (dist, vertex_no))

let getsize ms = let (_,size,_) = ms in size

let adjust_offset (offset,size,set) delta_offset =
  (* Remove the all elements of the ms where dist+offset+delta_offset < 0 *)
  let offset = offset ++ delta_offset in
  let rec loop count s =
    if Pset.is_empty s then (count,s) else
      let (dist,vertex_no) = Pset.min_elt s in
      if dist++offset < 0L then loop (count+1) (Pset.remove (dist,vertex_no) s)
      else (count,s)
  in
  let (count,s) = loop 0 set in
  (offset, size-count, s)

let merge ms1 ms2 =
  let (ms1,ms2) = if getsize ms1 < getsize ms2 then (ms1,ms2) else (ms2,ms1) in
  let ((offset1, size1, set1), (offset2, size2, set2)) = (ms1,ms2) in

  let rec loop count s1 s2 =
    if Pset.is_empty s1 then (count, s2) else
      let (d1,vn1) = Pset.min_elt s1 in
      loop (count+1) (Pset.remove (d1,vn1) s1) (Pset.add (d1++offset1--offset2,vn1) s2)
  in

  let (count,s2) = loop 0 set1 set2 in
  (offset2,size2+count,s2)

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

let () =
  let n = read_int () in
  let a = Array.init n (fun i -> long (read_int())) in
  let tree = Array.make n [] in
  let answer = Array.make n 0 in

  for i=1 to n-1 do
    let p = -1 + read_int() in
    let len = long (read_int()) in
    tree.(p) <- (i,len)::tree.(p)
  done;

  let rec dfs v =
    let ms = List.fold_left (fun ac (w,len) ->
      merge ac (adjust_offset (dfs w) (0L--len))
    ) (make_ms (a.(v), v)) tree.(v)
    in
    answer.(v) <- getsize ms;
    ms
  in

  ignore(dfs 0);

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

  print_newline()


General Payne has a battalion of n soldiers. The soldiers' beauty contest is coming up, it will last for k days. Payne decided that his battalion will participate in the pageant. Now he has choose the participants.All soldiers in the battalion have different beauty that is represented by a positive integer. The value ai represents the beauty of the i-th soldier.On each of k days Generals has to send a detachment of soldiers to the pageant. The beauty of the detachment is the sum of the beauties of the soldiers, who are part of this detachment. Payne wants to surprise the jury of the beauty pageant, so each of k days the beauty of the sent detachment should be unique. In other words, all k beauties of the sent detachments must be distinct numbers.Help Payne choose k detachments of different beauties for the pageant. Please note that Payne cannot just forget to send soldiers on one day, that is, the detachment of soldiers he sends to the pageant should never be empty.

The first line contains two integers n, k (1 ≤ n ≤ 50; 1 ≤ k ≤  ) — the number of soldiers and the number of days in the pageant, correspondingly. The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the beauties of the battalion soldiers. It is guaranteed that Payne's battalion doesn't have two soldiers with the same beauty.

Print k lines: in the i-th line print the description of the detachment that will participate in the pageant on the i-th day. The description consists of integer ci (1 ≤ ci ≤ n) — the number of soldiers in the detachment on the i-th day of the pageant and ci distinct integers p1, i, p2, i, ..., pci, i — the beauties of the soldiers in the detachment on the i-th day of the pageant. The beauties of the soldiers are allowed to print in any order. Separate numbers on the lines by spaces. It is guaranteed that there is the solution that meets the problem conditions. If there are multiple solutions, print any of them.

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

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

let () =
  let n = read_int() in
  let k = read_int() in
  let a = Array.init n (fun i -> read_int()) in
  let () = Array.sort compare a in

  let rec loop count bl nbl i = if count = k then () else
    (* if i has been pushed into the bl then make the bl bigger and reset i *)
    if i+nbl=n then loop count (a.(i-1)::bl) (nbl+1) 0
    else (
      Printf.printf "%d %d " (nbl+1) a.(i);
      List.iter (fun e -> Printf.printf "%d " e) bl;
      print_newline();
      loop (count+1) bl nbl (i+1)
    )
  in
    loop 0 [] 0 0


After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.Alyona has her favourite positive integer k and because she is too small, k does not exceed 10. The girl wants now to choose k disjoint non-empty substrings of string s such that these strings appear as disjoint substrings of string t and in the same order as they do in string s. She is also interested in that their length is maximum possible among all variants.Formally, Alyona wants to find a sequence of k non-empty strings p1, p2, p3, ..., pk satisfying following conditions:  s can be represented as concatenation a1p1a2p2... akpkak + 1, where a1, a2, ..., ak + 1 is a sequence of arbitrary strings (some of them may be possibly empty);  t can be represented as concatenation b1p1b2p2... bkpkbk + 1, where b1, b2, ..., bk + 1 is a sequence of arbitrary strings (some of them may be possibly empty);  sum of the lengths of strings in sequence is maximum possible. Please help Alyona solve this complicated problem and find at least the sum of the lengths of the strings in a desired sequence.A substring of a string is a subsequence of consecutive characters of the string.

In the first line of the input three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 10) are given — the length of the string s, the length of the string t and Alyona's favourite number respectively. The second line of the input contains string s, consisting of lowercase English letters. The third line of the input contains string t, consisting of lowercase English letters.

In the only line print the only non-negative integer — the sum of the lengths of the strings in a desired sequence. It is guaranteed, that at least one desired sequence exists.

NoteThe following image describes the answer for the second sample case:

let _ =
  let max (x : int) y = if x > y then x else y in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let t = Scanf.bscanf sb "%s " (fun s -> s) in
  (*let n = 5
  and m = 5
  and k = 1
  and s = "abcde"
  and t = "abxde" in*)
  let a = Array.init (k + 1) (fun _ -> Array.make_matrix (n + 1) (m + 1) 0) in
  let b = Array.init (k + 1) (fun _ -> Array.make_matrix (n + 1) (m + 1) 0) in
    for i = 1 to n do
      for j = 1 to m do
	for p = 0 to k do
	  a.(p).(i).(j) <-
	    max (max a.(p).(i - 1).(j) a.(p).(i).(j - 1))
	    (max b.(p).(i - 1).(j) b.(p).(i).(j - 1))
	done;
	if s.[i - 1] = t.[j - 1] then (
	  for p = 1 to k do
	    b.(p).(i).(j) <-
	      max a.(p - 1).(i - 1).(j - 1) b.(p).(i - 1).(j - 1) + 1
	  done;
	) else (
	)
      done
    done;
    let res = ref 0 in
      for p = 0 to k do
	res := max !res a.(p).(n).(m)
      done;
      for p = 0 to k do
	res := max !res b.(p).(n).(m)
      done;
      Printf.printf "%d\n" !res;
      a, b

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let t = Scanf.bscanf sb "%s " (fun s -> s) in
  let a = Array.init (k + 1) (fun _ -> Array.make_matrix (n + 1) (m + 1) 0) in
    for i = 1 to n do
      for j = 1 to m do
	if s.[i - 1] = t.[j - 1] then (
	  if i > 1 && j > 1 && s.[i - 2] = t.[j - 2] then (
	    for p = 0 to k do
	      a.(p).(i).(j) <- a.(p).(i - 1).(j - 1) + 1
	    done;
	  ) else (
	    for p = 1 to k do
	      a.(p).(i).(j) <- a.(p - 1).(i - 1).(j - 1) + 1
	    done;
	  )
	) else (
	  for p = 0 to k do
	    a.(p).(i).(j) <- max a.(p).(i - 1).(j) a.(p).(i).(j - 1)
	  done;
	)
      done
    done;
    let res = ref 0 in
      for p = 0 to k do
	res := max !res a.(p).(n).(m)
      done;
      Printf.printf "%d\n" !res


In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x1, x2, ..., xn, two characters cannot end up at the same position.Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally.

The first line on the input contains a single integer n (2 ≤ n ≤ 200 000, n is even) — the number of positions available initially. The second line contains n distinct integers x1, x2, ..., xn (0 ≤ xi ≤ 109), giving the coordinates of the corresponding positions.

Print the distance between the warrior and the archer at the beginning of the fight, provided that both Vova and Lesha play optimally.

NoteIn the first sample one of the optimum behavior of the players looks like that:  Vova bans the position at coordinate 15;  Lesha bans the position at coordinate 3;  Vova bans the position at coordinate 31;  Lesha bans the position at coordinate 1. After these actions only positions 0 and 7 will remain, and the distance between them is equal to 7.In the second sample there are only two possible positions, so there will be no bans.

open Str

let n = int_of_string @@ read_line () ;;
let xs = List.sort compare
    ( List.map int_of_string ( (split @@ regexp " ") (read_line()) ) );;

let maxInIntv len =
    let rec miii l r c = match r with
        | [] -> 0
        | rx::rt -> if rx - List.hd l <= len
                        then max c ( miii l rt (c+1) )
                        else miii (List.tl l) r (c-1)
    in miii xs xs 1
in
let rec optlen lmin lmax =
    if lmin = lmax then lmin
    else
    let mid = lmin/2 + lmax/2 in
    if (maxInIntv mid) > n/2
        then optlen lmin mid
        else optlen (mid+1) lmax
in
print_int @@ optlen 1 1_000_000_000

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 minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int() in
  let x = Array.init n (fun _ -> read_int()) in
  Array.sort compare x;
  let l = (n-2)/2 in
  let v = n-2-l in

  printf "%d\n" (minf 0 v (fun i -> x.(i+n-v-1) - x.(i)))

open Str

let n = int_of_string @@ read_line () ;;
let xs = List.map int_of_string ( (split @@ regexp " ") (read_line()) ) ;;

print_int (List.nth xs (n-1) );;

(* let maxInIntv len =
    let rec miii (l as lx::lt) r c = match r with
        | [] -> 0
        | rx::rt -> if rx - lx <= len
                        then max c ( miii l rt (c+1) )
                        else miii lt r (c-1)
    in miii xs xs 1
in
let rec minlen lmin lmax =
    if lmin = lmax then lmin
    else
    let mid = lmin/2 + lmax/2 *)


A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.

The first line contains three integers n, m and s (2 ≤ n ≤ 105, , 1 ≤ s ≤ n) — the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s.  Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≤ l ≤ 109) — the distance from the capital to the missile silos. It is guaranteed that:    between any two cities no more than one road exists;  each road connects two different cities;  from each city there is at least one way to any other city by the roads.

Print the single number — the number of Super Duper Secret Missile Silos that are located in Berland.

NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.

(* codeforces 103.  Danny Sleator *)
let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
let read_string () = Scanf.bscanf Scanf.Scanning.stdib " %s " (fun x -> x)

(* 4:10 *)

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

let n = read_int ()
let m = read_int ()
let start = read_int () -1

let ss = Array.make (2*m) 0
let ff = Array.make (2*m) 0
let ww = Array.make (2*m) 0
let first = Array.make n (-1)
let next = Array.make (2*m) 0

let () =
  for i=0 to m-1 do
    let vi = read_int() -1 in
    let ui = read_int() -1 in
    let wi = read_int() in
      ss.(i) <- vi;
      ff.(i+m) <- vi;
      ff.(i) <- ui;
      ss.(i+m) <- ui;
      ww.(i) <- wi;
      ww.(i+m) <- wi;
  done;

  for i=0 to 2*m-1 do
    next.(i) <- first.(ss.(i));
    first.(ss.(i)) <- i;
  done

let l = read_int()

let inf = 1_000_000_000
let dist = Array.make n inf

let () = dist.(start) <- 0

let rec printset s = if Pset.is_empty s then () else (
  let (d, v) = Pset.min_elt s in
  let s = Pset.remove (d, v) s in
    Printf.printf "(dist(%d) = %d)" v d;
    printset s
)

let rec dijkstra s = if Pset.is_empty s then () else
(*  Printf.printf "set: ";
  printset s;
  Printf.printf "\n"; *)
  let (d, v) = Pset.min_elt s in
  let s = Pset.remove (d, v) s in
  let rec loop e s = if e = -1 then s else
    let w = ff.(e) in
      (* processing edge v,w *)
      if dist.(w) = inf then (
	dist.(w) <- dist.(v) + ww.(e);
	loop (next.(e)) (Pset.add (dist.(w), w) s)
      ) else if dist.(v) + ww.(e) < dist.(w) then (
	let s = Pset.remove (dist.(w), w) s in
	  dist.(w) <- dist.(v) + ww.(e);
	  loop (next.(e)) (Pset.add (dist.(w), w) s)
      ) else (
	  loop (next.(e)) s
      )
  in
    dijkstra (loop first.(v) s)

let () = dijkstra (Pset.singleton (0,start))

(*
let () =
  for i=0 to n-1 do
    Printf.printf "dist.(%d) = %d\n" i dist.(i)
  done
*)

let ecount = ref 0

let () =
  for i=0 to n-1 do
    if dist.(i) = l then ecount := !ecount + 1
  done;

for i=0 to m-1 do
    let a = dist.(ss.(i)) in
    let b = dist.(ff.(i)) in
    let (a,b) = (min a b, max a b) in
    if a < l && b >= l then (
      if a+ww.(i) > l then ecount := !ecount + 1
    ) else if b<l then (
      if l-b + l-a = ww.(i) then ecount := !ecount + 1
      else if l-b < ww.(i) && l-a < ww.(i) && l-b + l-a < ww.(i) then ecount := !ecount + 2
    )
  done;

  Printf.printf "%d\n" !ecount

(* codeforces 103.  Danny Sleator *)
let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
let read_string () = Scanf.bscanf Scanf.Scanning.stdib " %s " (fun x -> x)

(* 4:10 *)

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

let n = read_int ()
let m = read_int ()
let start = read_int () -1

let ss = Array.make (2*m) 0
let ff = Array.make (2*m) 0
let ww = Array.make (2*m) 0
let first = Array.make n (-1)
let next = Array.make (2*m) 0

let () =
  for i=0 to m-1 do
    let vi = read_int() -1 in
    let ui = read_int() -1 in
    let wi = read_int() in
      ss.(i) <- vi;
      ff.(i+m) <- vi;
      ff.(i) <- ui;
      ss.(i+m) <- ui;
      ww.(i) <- wi;
      ww.(i+m) <- wi;
  done;

  for i=0 to 2*m-1 do
    next.(i) <- first.(ss.(i));
    first.(ss.(i)) <- i;
  done

let l = read_int()

let inf = 1_000_000_000
let dist = Array.make n inf

let () = dist.(start) <- 0

let rec printset s = if Pset.is_empty s then () else (
  let (d, v) = Pset.min_elt s in
  let s = Pset.remove (d, v) s in
    Printf.printf "(dist(%d) = %d)" v d;
    printset s
)

let rec dijkstra s = if Pset.is_empty s then () else
(*  Printf.printf "set: ";
  printset s;
  Printf.printf "\n"; *)
  let (d, v) = Pset.min_elt s in
  let s = Pset.remove (d, v) s in
  let rec loop e s = if e = -1 then s else
    let w = ff.(e) in
      (* processing edge v,w *)
      if dist.(w) = inf then (
	dist.(w) <- dist.(v) + ww.(e);
	loop (next.(e)) (Pset.add (dist.(w), w) s)
      ) else if dist.(v) + ww.(e) < dist.(w) then (
	let s = Pset.remove (dist.(w), w) s in
	  dist.(w) <- dist.(v) + ww.(e);
	  loop (next.(e)) (Pset.add (dist.(w), w) s)
      ) else (
	  loop (next.(e)) s
      )
  in
    dijkstra (loop first.(v) s)

let () = dijkstra (Pset.singleton (0,start))

(*
let () =
  for i=0 to n-1 do
    Printf.printf "dist.(%d) = %d\n" i dist.(i)
  done
*)

let ecount = ref 0

let () =
  for i=0 to n-1 do
    if dist.(i) = l then ecount := !ecount + 1
  done;

  for i=0 to m-1 do
    let a = dist.(ss.(i)) in
    let b = dist.(ff.(i)) in
    let (a,b) = (min a b, max a b) in
    if a < l && b >= l then (
      if a+ww.(i) > l then ecount := !ecount + 1
    ) else if b<l then (
      if l-b + l-a = ww.(i) then ecount := !ecount + 1
      else if l-b + l-a < ww.(i) then ecount := !ecount + 2
    )
  done;

  Printf.printf "%d\n" !ecount


Vika has n jars with paints of distinct colors. All the jars are numbered from 1 to n and the i-th jar contains ai liters of paint of color i.Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1 × 1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color x, then the next square will be painted in color x + 1. In case of x = n, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of jars with colors Vika has. The second line of the input contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is equal to the number of liters of paint in the i-th jar, i.e. the number of liters of color i that Vika has.

The only line of the output should contain a single integer — the maximum number of squares that Vika can paint if she follows the rules described above.

NoteIn the first sample the best strategy is to start painting using color 4. Then the squares will be painted in the following colors (from left to right): 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5.In the second sample Vika can start to paint using any color.In the third sample Vika should start painting using color number 5.

open Printf
open Scanf

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

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

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

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

  let m = minf 0 (n-1) (fun i -> c.(i)) in

  let rec loop i ac = if i=n then List.rev ac else
      let ac = if c.(i) = m then i::ac else ac in
      loop (i+1) ac
  in

  let place = Array.of_list (loop 0 []) in
  let pn = Array.length place in

  let rec mgap i ac = if i=pn then ac else
      mgap (i+1) (max ac (place.(i) - place.(i-1) - 1))
  in

  let maxgap = mgap 1 0 in
  let maxgap = max maxgap ((n-place.(pn-1)) + (place.(0) - 1)) in

  printf "%Ld\n" ((long n)**(long m) ++ (long maxgap))


Polycarp likes numbers that are divisible by 3.He has a huge number $$$s$$$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $$$3$$$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $$$m$$$ such cuts, there will be $$$m+1$$$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $$$3$$$.For example, if the original number is $$$s=3121$$$, then Polycarp can cut it into three parts with two cuts: $$$3|1|21$$$. As a result, he will get two numbers that are divisible by $$$3$$$.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by $$$3$$$ that Polycarp can obtain?

The first line of the input contains a positive integer $$$s$$$. The number of digits of the number $$$s$$$ is between $$$1$$$ and $$$2\cdot10^5$$$, inclusive. The first (leftmost) digit is not equal to 0.

Print the maximum number of numbers divisible by $$$3$$$ that Polycarp can get by making vertical cuts in the given number $$$s$$$.

NoteIn the first example, an example set of optimal cuts on the number is 3|1|21.In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $$$3$$$.In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $$$33$$$ digits 0. Each of the $$$33$$$ digits 0 forms a number that is divisible by $$$3$$$.In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $$$0$$$, $$$9$$$, $$$201$$$ and $$$81$$$ are divisible by $$$3$$$.

open Printf
let print_int_endline n = n |> string_of_int |> print_endline

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 () =
  let s = Scanf.scanf " %s" (fun v -> v)
  in let ls = char_list_of_string s
  |> List.map (fun c -> int_of_char c - int_of_char '0')
  in
  List.fold_left (fun (c,k,n) v ->
    let m = (c+v) mod 3 in
    if m=0 || v mod 3 = 0 || k=2 then (0,0,n+1)
    else (m,k+1,n)
  ) (0,0,0) ls
  |> (fun (_,_,n) -> n)
  |> print_int_endline

open Printf
let print_int_endline n = n |> string_of_int |> print_endline

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 ( *< ) f g x = f (g x)
let ( *> ) f g x = g (f x)

let cumulsum a =
  let ls = ref [0] in
  Array.iter (fun v -> ls := v+(List.hd !ls)::!ls) a;
  !ls |> List.rev |> Array.of_list

let () =
  let s = Scanf.scanf " %s" (fun v -> v)
  in let ls = char_list_of_string s
  |> List.map (fun c -> int_of_char c - int_of_char '0')
  in
  List.fold_left (fun (c,n) v ->
    let m = (c+v) mod 3 in
    if m=0 then (0,n+1)
    else if v mod 3 = 0 then (0,n+1)
    else (m,n)
  ) (0,0) ls
  |> snd
  |> print_int_endline


Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candy — and after that, she has $$$55$$$ candies too.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^{16}$$$) — the number of candies in the first, second and third piles correspondingly.

Print $$$q$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th query — the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).

open Scanf
open Printf

module L = struct
  open Int64
  let ( + ), ( - ), ( * ), ( / ), ( % ) = add, sub, mul, div, rem
end
let ( ~~ ) = Int64.of_int
let ( !! ) = Int64.to_int

let readint () = scanf " %d" (fun x -> x)
let readint64 () = scanf " %Ld" (fun x -> x)

let solve () =
  let a = readint64 () and b = readint64 () and c = readint64 () in
  let rec f x y z = if x <= y then let u = L.(min (y - x) z) in L.(x + u + (z - u) / 2L) else f y x z in
  let ans = L.(List.fold_left max Int64.min_int [f a b c; f a c b; f b a c; f b c a; f c a b; f c b a]) in
  printf "%Ld\n" ans

let () =
  let q = readint () in
  for _ = 0 to q-1 do
    solve ()
  done;


Shubham has a binary string $$$s$$$. A binary string is a string containing only characters "0" and "1".He can perform the following operation on the string any amount of times:   Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$ — the number of test cases. Each of the next $$$t$$$ lines contains a binary string $$$s$$$ $$$(1 \le |s| \le 1000)$$$.

For every string, output the minimum number of operations required to make it good.

NoteIn test cases $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ no operations are required since they are already good strings.For the $$$3$$$rd test case: "001" can be achieved by flipping the first character  — and is one of the possible ways to get a good string.For the $$$4$$$th test case: "000" can be achieved by flipping the second character  — and is one of the possible ways to get a good string.For the $$$7$$$th test case: "000000" can be achieved by flipping the third and fourth characters  — and is one of the possible ways to get a good string.

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (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 s = read_string() in
    let n = String.length s in
    let nones = sum 0 (n-1) (fun i -> if s.[i] = '1' then 1 else 0) in
    let nzeros = n - nones in

    let rec scan i zeros ones best = if i=n+1 then best else (
    (* zeros = number of zeros before i, etc *)
      let zeros_after = nzeros - zeros in
      let ones_after = nones - ones in
      let opt1 = ones + zeros_after in
      let opt2 = zeros + ones_after in
      let best = min best (min opt1 opt2) in
      let ones = ones + (if i=n || s.[i] = '0' then 0 else 1) in
      let zeros = zeros + (if i=n || s.[i] = '1' then 0 else 1) in
      scan (i+1) zeros ones best
    ) in

    printf "%d\n" (scan 0 0 0 n)
  done


You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by one or several messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. It is guaranteed that the dialog begins with the question of the client.You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 500$$$). Description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the total number of messages in the dialog. The second line of each test case consists of $$$n$$$ characters "Q" and "A", describing types of messages in the dialog in chronological order. Character "Q" denotes the message with client question, and character "A" — the message with technical support manager answer. It is guaranteed that the first character in the line equals to "Q".

For each test case print "Yes" (without quotes) if dialog may correspond to the rules of work, or "No" (without quotes) otherwise.

5

4

QQAA

4

QQAQ

3

QAA

1

Q

14

QAQQAQAAQQQAAA

NoteIn the first test case the two questions from the client are followed with two specialist's answers. So this dialog may correspond to the rules of work.In the second test case one of the first two questions was not answered.In the third test case the technical support manager sent two messaged as the answer to the only message of the client.

let t = read_int() in

for i = 1 to t do
    let n=read_int() in
    let s=read_line() in
    let co = ref 0 in
    for j = 0 to (n-1) do
        if s.[j] = 'Q' then
            co := !co + 1
        else
            co := max (!co - 1) 0
    done;
    if !co > 0 then
        print_string("No\n")
    else
        print_string("Yes\n");
done

let t = read_int() in

for i = 1 to t do
    let n=read_int() in
    let s=read_line() in
    let co = ref 0 in
    for j = 0 to (n-1) do
        if s.[j] = 'Q' then
            co := !co + 1
        else
            co := !co - 1
    done;
    if !co > 0 then
        print_string("No\n")
    else
        print_string("Yes\n");
done


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them on a circle so that each number is strictly greater than both its neighbors or strictly smaller than both its neighbors?In other words, check if there exists a rearrangement $$$b_1, b_2, \ldots, b_n$$$ of the integers $$$a_1, a_2, \ldots, a_n$$$ such that for each $$$i$$$ from $$$1$$$ to $$$n$$$ at least one of the following conditions holds: $$$b_{i-1} < b_i > b_{i+1}$$$ $$$b_{i-1} > b_i < b_{i+1}$$$To make sense of the previous formulas for $$$i=1$$$ and $$$i=n$$$, one shall define $$$b_0=b_n$$$ and $$$b_{n+1}=b_1$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 3\cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 10^5$$$)  — the number of integers. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). The sum of $$$n$$$ over all test cases doesn't exceed $$$2\cdot 10^5$$$.

For each test case, if it is not possible to arrange the numbers on the circle satisfying the conditions from the statement, output $$$\texttt{NO}$$$. You can output each letter in any case. Otherwise, output $$$\texttt{YES}$$$. In the second line, output $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$, which are a rearrangement of $$$a_1, a_2, \ldots, a_n$$$ and satisfy the conditions from the statement. If there are multiple valid ways to arrange the numbers, you can output any of them.

NoteIt can be shown that there are no valid arrangements for the first and the third test cases.In the second test case, the arrangement $$$[1, 8, 4, 9]$$$ works. In this arrangement, $$$1$$$ and $$$4$$$ are both smaller than their neighbors, and $$$8, 9$$$ are larger.In the fourth test case, the arrangement $$$[1, 11, 1, 111, 1, 1111]$$$ works. In this arrangement, the three elements equal to $$$1$$$ are smaller than their neighbors, while all other elements are larger than their neighbors.

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in
    let a = Array.init n read_int in
    if n mod 2 = 1 then printf "NO\n" else (
      Array.sort compare a;
      let block1 = sum 0 (n/2 - 1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in
      let block2 = sum (n/2) (n-1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in
      if block1 + block2 > n/2 ||
	(block1 + block2 >= n/2 && block1>0 && block2>0) then printf "NO\n" else (
	printf "YES\n";
	if block1 > block2 then (
	  Array.sort (fun i j -> compare j i) a
	);
	for i=0 to n/2-1 do
	  printf "%d " a.(i);
	  printf "%d " a.(i+n/2)
	done;
	print_newline()
      )
    )
  done

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in
    let a = Array.init n read_int in
    if n mod 2 = 1 then printf "NO\n" else (
      Array.sort compare a;
      let block1 = sum 0 (n/2 - 1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in
      let block2 = sum (n/2) (n-1) (fun i -> if a.(i) = a.(n/2) then 1 else 0) in
      if block1 + block2 >= n/2 then printf "NO\n" else (
	printf "YES\n";
	if block1 > block2 then (
	  Array.sort (fun i j -> compare j i) a
	);
	for i=0 to n/2-1 do
	  printf "%d " a.(i);
	  printf "%d " a.(i+n/2)
	done;
	print_newline()
      )
    )
  done


Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible:   delete $$$s_1$$$ and $$$s_2$$$: $$$\textbf{10}11001 \rightarrow 11001$$$;  delete $$$s_2$$$ and $$$s_3$$$: $$$1\textbf{01}1001 \rightarrow 11001$$$;  delete $$$s_4$$$ and $$$s_5$$$: $$$101\textbf{10}01 \rightarrow 10101$$$;  delete $$$s_6$$$ and $$$s_7$$$: $$$10110\textbf{01} \rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.

First line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Only line of each test case contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$), consisting of only characters 0 and 1.

For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.

NoteIn the first test case after Alice's move string $$$s$$$ become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string $$$s$$$ turn into $$$01$$$. Then, after Bob's move string $$$s$$$ become empty and Alice can not make any move.

let rec str_to_list (str : string) (index : int) =
  if index = String.length str then
    []
  else
    (String.get str index) :: str_to_list str (index + 1)
;;

let rec main (t : int) =
  if t = 0 then
    ()
  else
    (let str = read_line () in
     let str_list = str_to_list str 0 in
     let num_ones = List.fold_left (fun acc x -> if x = '1' then acc + 1 else acc) 0 str_list in
     let num_zeros = (String.length str) - num_ones in
     if (min num_ones num_zeros) mod 2 = 0 then
       print_endline "NET"
     else
       print_endline "DA"
     ;
     main (t-1)
    );;

let t = read_int () in
main t

(* Codeforces 1373 B. 01 Game train *)

(* you can use either gr or rdln but not both *)
let gr () = Scanf.scanf " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let 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;;

(* reading reversed list *)
let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;

let rec countz cnt idx s =
	if idx == (String.length s) then cnt
	else
		let ncnt = if s.[idx]=='0' then (cnt + 1) else cnt in
		countz ncnt (idx + 1) s;;

let game s  =
    let nz = countz 0 0 s in
		let no = (String.length s) - nz in
		let minzo = if nz < no then nz else no in
		(* let _ = Printf.printf "minzo = %d\n" minzo in *)
		let alice_win = (minzo mod 2) == 1 in
		alice_win;;

let do_one () =
    let s = rdln() in
    let ans = game s in
		let sans = if ans then "DA" else "NET" in
    Printf.printf "%s\n" sans;;

let do_all t =
    for i = 1 to t do
        do_one ()
    done;;

let main() =
	let st = rdln () in
	let t = int_of_string st in
	do_all t;;

main();;