Pay attention to the non-standard memory limit in this problem.In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.The array $$$a=[a_1, a_2, \ldots, a_n]$$$ ($$$1 \le a_i \le n$$$) is given. Its element $$$a_i$$$ is called special if there exists a pair of indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) such that $$$a_i = a_l + a_{l+1} + \ldots + a_r$$$. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).Print the number of special elements of the given array $$$a$$$.For example, if $$$n=9$$$ and $$$a=[3,1,4,1,5,9,2,6,5]$$$, then the answer is $$$5$$$:  $$$a_3=4$$$ is a special element, since $$$a_3=4=a_1+a_2=3+1$$$;  $$$a_5=5$$$ is a special element, since $$$a_5=5=a_2+a_3=1+4$$$;  $$$a_6=9$$$ is a special element, since $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$;  $$$a_8=6$$$ is a special element, since $$$a_8=6=a_2+a_3+a_4=1+4+1$$$;  $$$a_9=5$$$ is a special element, since $$$a_9=5=a_2+a_3=1+4$$$. Please note that some of the elements of the array $$$a$$$ may be equal — if several elements are equal and special, then all of them should be counted in the answer.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is given in two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 8000$$$) — the length of the array $$$a$$$. The second line contains integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$8000$$$.

Print $$$t$$$ numbers — the number of special elements for each of the given arrays.

(* Codeforces 1352 E Special Elements 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 tstprintlist head li =
	begin
		print_string head;
		printlisti li;
		print_string "\n"
	end;;

let rec repeat a n = match n with
  | 0 -> []
  | _ -> a :: repeat a (n-1);;

let sums a =
  let rec r_sums sma sm a = match a with
    | [] -> sma
  	| h :: t ->
  		let nsm = h + sm in
  		r_sums (nsm :: sma) nsm t in
	r_sums [0] 0 a;;

let rec setdiffs el spec n sa = match sa with
  | [] -> ()
	| h :: t ->
		let s = el - h in
		let _ = if ((s <= n) && (s > 0)) then spec.(s) <- 1 in
		setdiffs el spec n t;;

let rec set_spec speca n sa = match sa with
  | [] -> ()
	| h :: [] -> ()
	| h0 :: h1 :: t ->
		let _ = setdiffs h0 speca n t in
		set_spec speca n (h1 :: t);;

let rec set_a cnta a = match a with
| [] -> ()
| h :: t ->
	begin
		cnta.(h) <- (cnta.(h) + 1);
		set_a cnta t
	end;;

let rec sum_spec cnta speca sm i n =
	if i > n then sm
	else
		let e = cnta.(i) * speca.(i) in
		sum_spec cnta speca (sm + e) (i+1) n;;

let num_special n a =
	let sma = sums a in
	(* let _ = tstprintlist "sma " sma in *)
	let cnta = Array.make (n+1) 0 in
	let speca = Array.make (n+1) 0 in
	let _ = set_spec speca n sma in
	let _ = set_a cnta a in
   (* let _ = tstprintlist "speca " (Array.to_list speca) in
    let _ = tstprintlist "cnta " (Array.to_list cnta) in*)
	let sumspec = sum_spec cnta speca 0 0 n in
	Printf.printf "%d \n" sumspec;;

let do_one () =
    let n = gr () in
    let a = readlist n [] in
		let a = List.rev a in
		num_special n a;;

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

let main() =
	let t = gr () in
	do_all t;;

main();;


The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.The slogan of the company consists of n characters, so the decorators hung a large banner, n meters wide and 1 meter high, divided into n equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the k-th square of the poster. To draw the i-th character of the slogan on the poster, you need to climb the ladder, standing in front of the i-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the i-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 100) — the number of characters in the slogan and the initial position of the ladder, correspondingly. The next line contains the slogan as n characters written without spaces. Each character of the slogan is either a large English letter, or digit, or one of the characters: '.', '!', ',', '?'.

In t lines, print the actions the programmers need to make. In the i-th line print:   "LEFT" (without the quotes), if the i-th action was "move the ladder to the left";  "RIGHT" (without the quotes), if the i-th action was "move the ladder to the right";  "PRINT x" (without the quotes), if the i-th action was to "go up the ladder, paint character x, go down the ladder".  The painting time (variable t) must be minimum possible. If there are multiple optimal painting plans, you can print any of them.

RIGHT
RIGHT
PRINT !
LEFT
PRINT O
LEFT
PRINT G
LEFT
PRINT ?
LEFT
PRINT O
LEFT
PRINT G

NoteNote that the ladder cannot be shifted by less than one meter. The ladder can only stand in front of some square of the poster. For example, you cannot shift a ladder by half a meter and position it between two squares. Then go up and paint the first character and the second character.

let sr=read_line();;
let rec ind i=if sr.[i]=' ' then i else ind (i+1);;
let id=ind 0;;
let n=int_of_string(String.sub sr 0 id) and k=int_of_string(String.sub sr (id+1) (String.length(sr)-1-id));;

let s=read_line();;
if k<=n/2 then
   begin
   for i=1 to k-1 do
      Printf.printf "LEFT\n"
   done;
   for i=0 to n-1 do
      print_string("PRINT "^(String.sub s i 1)^"\n");
      if i<>n-1 then Printf.printf "RIGHT\n"
   done
   end
else
   begin
   for i=k to n-1 do
      Printf.printf "RIGHT\n"
   done;
   for i=n-1 downto 0 do
      print_string("PRINT "^(String.sub s i 1)^"\n");
      if i<>0 then Printf.printf "LEFT\n"
   done
   end;;

open Printf
open Scanf

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

let reverse str =
    let n = String.length str in
    let res = String.create n in
    for i = 0 to n - 1 do
        res.[i] <- str.[n - 1 - i]
    done;
    res in

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

let res_f sep i c =
    if i > 0 then printf "%s\n" sep;
    printf "PRINT %c\n" c in

if k - 1 <= n - k then begin
    for i = 1 to k - 1 do
        printf "LEFT\n"
    done;
    String.iteri (res_f "RIGHT") s
end else begin
    for i = 1 to n - k do
        printf "RIGHT\n"
    done;
    String.iteri (res_f "LEFT") (reverse s)
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 s = Scanf.bscanf sb "%s " (fun s -> s) in
  let l = k - 1
  and r = n - k in
    if l < r then (
      for i = 1 to l do
	Printf.printf "LEFT\n"
      done;
      for i = 0 to n - 1 do
	Printf.printf "PRINT %c\n" s.[i];
	if i < n - 1
	then Printf.printf "RIGHT\n"
      done;
    ) else (
      for i = 1 to r do
	Printf.printf "RIGHT\n"
      done;
      for i = n - 1 downto 0 do
	Printf.printf "PRINT %c\n" s.[i];
	if i > 0
	then Printf.printf "LEFT\n"
      done;
    )

open Printf
open Scanf

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

let reverse str =
    let n = String.length str in
    let res = String.create n in
    for i = 0 to n - 1 do
        res.[i] <- str.[n - 1 - i]
    done;
    res in

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

let res_f sep i c =
    if i > 0 then printf "%s\n" sep;
    printf "PRINT %c\n" c in

printf "%d %d %s\n" n k s;

if k - 1 <= n - k then begin
    for i = 1 to k - 1 do
        printf "LEFT\n"
    done;
    String.iteri (res_f "RIGHT") s
end else begin
    for i = 1 to n - k do
        printf "RIGHT\n"
    done;
    String.iteri (res_f "LEFT") (reverse s)
end ;;


Businessman Divan loves chocolate! Today he came to a store to buy some chocolate. Like all businessmen, Divan knows the value of money, so he will not buy too expensive chocolate. At the same time, too cheap chocolate tastes bad, so he will not buy it as well.The store he came to has $$$n$$$ different chocolate bars, and the price of the $$$i$$$-th chocolate bar is $$$a_i$$$ dollars. Divan considers a chocolate bar too expensive if it costs strictly more than $$$r$$$ dollars. Similarly, he considers a bar of chocolate to be too cheap if it costs strictly less than $$$l$$$ dollars. Divan will not buy too cheap or too expensive bars.Divan is not going to spend all his money on chocolate bars, so he will spend at most $$$k$$$ dollars on chocolates.Please determine the maximum number of chocolate bars Divan can buy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The description of each test case consists of two lines. The first line contains integers $$$n$$$, $$$l$$$, $$$r$$$, $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le l \le r \le 10^9$$$, $$$1 \le k \le 10^9$$$) — the lowest acceptable price of a chocolate, the highest acceptable price of a chocolate and Divan's total budget, respectively. The second line contains a sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) integers — the prices of chocolate bars in the store.

For each test case print a single integer — the maximum number of chocolate bars Divan can buy.

NoteIn the first example Divan can buy chocolate bars $$$1$$$ and $$$3$$$ and spend $$$100$$$ dollars on them.In the second example Divan can buy chocolate bars $$$3$$$ and $$$4$$$ and spend $$$7$$$ dollars on them.In the third example Divan can buy chocolate bars $$$3$$$, $$$4$$$, and $$$5$$$ for $$$12$$$ dollars.In the fourth example Divan cannot buy any chocolate bar because each of them is either too cheap or too expensive.In the fifth example Divan cannot buy any chocolate bar because he considers the first bar too cheap, and has no budget for the second or third.In the sixth example Divan can buy all the chocolate bars in the shop.

(* Codeforces 1614 A Divan and a Store 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 between l r x =
	(l <= x) && (x <= r);;

let rec max_choc cnt money lc = match lc with
	| [] -> cnt
	| h :: t ->
		if h > money then cnt
		else
			let ncnt = cnt + 1 in
			let nMoney = money - h in
			let nlc = t in
			max_choc ncnt nMoney nlc;;

let do_one () =
    let n = gr() in
    let l = gr() in
    let r = gr() in
    let k = gr() in
		let a = List.rev (readlist n []) in
		let sa = List.sort compare a in
		let fa = List.filter (between l r) sa in
		let cnt = max_choc 0 k fa in
		(print_int cnt; print_string "\n");;

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

let main() =
	do_all ();;

main();;


High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change. The second line contains the string, consisting of letters 'a' and 'b' only.

Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

NoteIn the first sample, Vasya can obtain both strings "aaaa" and "bbbb".In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".

let [n; k] = read_line () |> Str.(split (regexp " ")) |> List.map int_of_string
let s = read_line ()

exception Break of int;;

let max_charm_at_start ch =
  let mana = ref k in
  try
    for i = 0 to n-1 do
      if s.[i] != ch then
        decr mana;
      if !mana < 0 then
        raise (Break i)
    done;
    n
  with
  | Break i -> i

let max_charm ch =
  let left = ref 0
  and right = ref (max_charm_at_start ch) in
  let best = ref !right in
  while !right < n do
    if s.[!right] != ch then
      begin
        while s.[!left] == ch do
          incr left
        done;
        incr left
      end;
    incr right;
    if !right - !left > !best then
      best := !right - !left
  done;
  !best

let () =
  max (max_charm 'a') (max_charm 'b')
  |> Printf.printf "%d\n"

open Printf
open Scanf

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

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

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

  let solve a =
  (* a is an array of n+2 bits (0s or 1s).  We added an extra 0 at start and end
     what's the maximum block of 1s we can make by toggling at most k 0s to 1s. *)
    let nzeros = sum 1 n (fun i -> if a.(i) = 0 then 1 else 0) in
    if nzeros <= k then n else (

      let next = Array.make (n+2) 0 in
      let prev = Array.make (n+2) 0 in

      let rec scan i p = if i<n+2 then
	  if a.(i) = 0 then (
	    prev.(i) <- p;
	    next.(p) <- i;
	    scan (i+1) i
	  ) else (
	    scan (i+1) p
	  )
      in

      scan 1 0;

      if k=0 then (
	 maxf 0 n (fun i -> next.(i) - i - 1)
      ) else (
	let rec step i steps = if steps=0 then i else step next.(i) (steps-1) in
	let rec scan i j ac = if j=n+1 then ac else (
	  (* evaluate this (i,j) option. *)
	  let pi = prev.(i) in
	  let nj = next.(j) in
	  let ac = max ac (nj-pi-1) in
	  scan next.(i) next.(j) ac
	) in

	let i = next.(0) in
	let j = step i (k-1) in
	scan i j 0
      )
    )
  in

  let ma c = Array.init (n+2) (fun i -> if i-1 < 0 || i-1 > n-1 then 0 else if s.[i-1] = c then 1 else 0) in
  let answer = max (solve (ma 'a')) (solve (ma 'b')) in

  printf "%d\n" answer


Dasha logged into the system and began to solve problems. One of them is as follows:Given two sequences a and b of length n each you need to write a sequence c of length n, the i-th element of which is calculated as follows: ci = bi - ai.About sequences a and b we know that their elements are in the range from l to r. More formally, elements satisfy the following conditions: l ≤ ai ≤ r and l ≤ bi ≤ r. About sequence c we know that all its elements are distinct.  Dasha wrote a solution to that problem quickly, but checking her work on the standard test was not so easy. Due to an error in the test system only the sequence a and the compressed sequence of the sequence c were known from that test.Let's give the definition to a compressed sequence. A compressed sequence of sequence c of length n is a sequence p of length n, so that pi equals to the number of integers which are less than or equal to ci in the sequence c. For example, for the sequence c = [250, 200, 300, 100, 50] the compressed sequence will be p = [4, 3, 5, 2, 1]. Pay attention that in c all integers are distinct. Consequently, the compressed sequence contains all integers from 1 to n inclusively.Help Dasha to find any sequence b for which the calculated compressed sequence of sequence c is correct.

The first line contains three integers n, l, r (1 ≤ n ≤ 105, 1 ≤ l ≤ r ≤ 109) — the length of the sequence and boundaries of the segment where the elements of sequences a and b are. The next line contains n integers a1,  a2,  ...,  an (l ≤ ai ≤ r) — the elements of the sequence a. The next line contains n distinct integers p1,  p2,  ...,  pn (1 ≤ pi ≤ n) — the compressed sequence of the sequence c.

If there is no the suitable sequence b, then in the only line print "-1". Otherwise, in the only line print n integers — the elements of any suitable sequence b.

NoteSequence b which was found in the second sample is suitable, because calculated sequence c = [2 - 3, 2 - 4, 2 - 8, 9 - 9] = [ - 1,  - 2,  - 6, 0] (note that ci = bi - ai) has compressed sequence equals to p = [3, 2, 1, 4].

let print_array a =
	for k = 0 to (Array.length a) - 1 do
		print_int a.(k);
		print_char ' ';
	done;

	print_newline ();
;;

let read_array ?(delta=0) n =
	let arr = Array.make n 0 in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %i" (fun v -> arr.(k) <- v + delta;);
		done;
		arr
	end
;;

let permute_array a p =
	let n = Array.length a in
	let a' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			a'.( p.(k) ) <- a.(k);
		done;
		a'
	end
;;

let permute a p =
	let n = Array.length a in
	let a' = Array.make n 0 in
	let p' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			a'.( p.(k) ) <- a.(k);
			p'.( p.(k) ) <- k;
		done;
		(a', p')
	end
;;

(* a_permuted - sequence "a" permuted so that \forall k: A_permuted[ P[k] ] = A[ k ]  *)
let calc_b a_permuted l r =
	let n = Array.length a_permuted in
	let b = Array.make n 0 in
	let b_last = ref l in (* B[ k - 1 ] *)
	begin

		b.(0) <- !b_last;

		let c = ref (!b_last - a_permuted.(0)) in (* minimum possible c - corresponds to the smallest P[k] *)
		let k = ref 1 in
		while (!k < n) && (!b_last <= r) do
			c := (!c + 1);
			b_last := max l (!c + a_permuted.(!k));
			b.(!k) <- !b_last;
			c := !b_last - a_permuted.(!k);
			k := !k + 1;
		done;

		if !b_last <= r then Some b else None

	end
;;

let load_and_process_data n l r =
	let a = read_array n in
	let p = read_array n ~delta:(-1) in
	let (a', p') = permute a p in
	let b = calc_b a' l r in
	match b with
	| Some l -> print_array (permute_array l p')
	| None -> print_endline "-1"
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i %i %i " load_and_process_data
;;

read_input ()

let print_array a =
	for k = 0 to (Array.length a) - 1 do
		print_int a.(k);
		print_char ' ';
	done;

	print_newline ();
;;

let read_array ?(delta=0) n =
	let arr = Array.make n 0 in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %i" (fun v -> arr.(k) <- v + delta;);
		done;
		arr
	end
;;

let permute_array a p =
	let n = Array.length a in
	let a' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			a'.( p.(k) ) <- a.(k);
		done;
		a'
	end
;;

let invert_permutation p =
	let n = Array.length p in
	let p' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			p'.( p.(k) ) <- k;
		done;
		p'
	end
;;

(* a_permuted - sequence "a" permuted so that \forall k: A_permuted[ P[k] ] = A[ k ]  *)
let calc_b a_permuted l r =
	let n = Array.length a_permuted in
	let b = Array.make n 0 in
	let b_last = ref l in (* B[ k - 1 ] *)
	begin

		b.(0) <- !b_last;

		let c = ref (!b_last - a_permuted.(0)) in (* minimum possible c - corresponds to the smallest P[k] *)
		let k = ref 1 in
		while (!k < n) && (!b_last <= r) do
			c := (!c + 1);
			b_last := max l (!c + a_permuted.(!k));
			b.(!k) <- !b_last;
			c := !b_last - a_permuted.(!k);
			k := !k + 1;
		done;

		if !b_last <= r then Some b else None

	end
;;

let load_and_process_data n l r =
	let a = read_array n in
	let p = read_array n ~delta:(-1) in
	let b = calc_b (permute_array a p) l r in
	match b with
	| Some l -> print_array (permute_array l (invert_permutation p))
	| None -> print_endline "-1"
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i %i %i " load_and_process_data
;;

read_input ()

let print_array a =
	for k = 0 to (Array.length a) - 1 do
		print_int a.(k);
		print_char ' ';
	done;

	print_newline ();
;;

let read_array ?(delta=0) n =
	let arr = Array.make n 0 in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %i" (fun v -> arr.(k) <- v + delta;);
		done;
		arr
	end
;;

let invert_permutation p =
	let n = Array.length p in
	let p' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			p'.( p.(k) ) <- k;
		done;
		p'
	end
;;

(* p' - invert function to p, i.e. the function restoring back the permutation created by p *)
let calc_b a p' l r =
	let n = Array.length a in
	let b = Array.make n 0 in
	let b_last = ref l in (* B[ k - 1 ] *)
	let k' = ref p'.( 0 ) in
	begin

		b.( !k' ) <- !b_last;

		let a_cur = ref a.( !k' ) in
		let c = ref (!b_last - !a_cur) in (* minimum possible c - corresponds to the smallest P[k] *)
		let k = ref 1 in
		while (!k < n) && (!b_last <= r) do
			k' := p'.( !k );
			a_cur := a.( !k' );
			c := (!c + 1);
			b_last := max l (!c + !a_cur);
			b.(!k') <- !b_last;
			c := !b_last - !a_cur;
			k := !k + 1;
		done;

		if !b_last <= r then Some b else None

	end
;;

let load_and_process_data n l r =
	let a = read_array n in
	let p = read_array n ~delta:(-1) in
	let b = calc_b a (invert_permutation p) l r in
	match b with
	| Some l -> print_array l
	| None -> print_endline "-1"
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i %i %i " load_and_process_data
;;

read_input ()

let () =
  Scanf.scanf "%d %d %d " @@ fun n l r ->
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let p = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let b = Array.make n 0 in
  let revp = Array.make n 0 in
  Array.iteri (fun i j -> revp.(j - 1) <- i) p;
  let rec loop prevc i =
    if i < n then
      let j = revp.(i) in
      b.(j) <- max l (a.(j) + prevc + 1);
      if b.(j) > r then
        false
      else
        loop (b.(j) - a.(j)) (i + 1)
    else true in
  if loop (l - r - 1) 0 then
    Array.to_list b |> List.map string_of_int |> String.concat " " |> print_endline
  else
    print_endline "-1"


Vova's house is an array consisting of $$$n$$$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $$$i$$$-th element of the array is $$$1$$$ if there is a heater in the position $$$i$$$, otherwise the $$$i$$$-th element of the array is $$$0$$$.Each heater has a value $$$r$$$ ($$$r$$$ is the same for all heaters). This value means that the heater at the position $$$pos$$$ can warm up all the elements in range $$$[pos - r + 1; pos + r - 1]$$$.Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if $$$n = 6$$$, $$$r = 2$$$ and heaters are at positions $$$2$$$ and $$$5$$$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $$$3$$$ elements will be warmed up by the first heater and the last $$$3$$$ elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house.

The first line of the input contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n, r \le 1000$$$) — the number of elements in the array and the value of heaters. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — the Vova's house description.

Print one integer — the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.

NoteIn the first example the heater at the position $$$2$$$ warms up elements $$$[1; 3]$$$, the heater at the position $$$3$$$ warms up elements $$$[2, 4]$$$ and the heater at the position $$$6$$$ warms up elements $$$[5; 6]$$$ so the answer is $$$3$$$.In the second example the heater at the position $$$1$$$ warms up elements $$$[1; 3]$$$ and the heater at the position $$$5$$$ warms up elements $$$[3; 5]$$$ so the answer is $$$2$$$.In the third example there are no heaters so the answer is -1.In the fourth example the heater at the position $$$3$$$ warms up elements $$$[1; 5]$$$, the heater at the position $$$6$$$ warms up elements $$$[4; 8]$$$ and the heater at the position $$$10$$$ warms up elements $$$[8; 10]$$$ so the answer is $$$3$$$.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline 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) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done
end open MyInt64

module Imos = struct
	let make n = Array.make (i32 n +$ 2) 0L
	let add_destructive_closed l r a =
		a.(l+$1) <- a.(l+$1) + 1L;
		a.(r+$2) <- a.(r+$2) - 1L
	let add_destructive_1orig_closed l r a =
		let l = max l 0 in a.(l) <- a.(l) + 1L;
		let r = min (r+$1) (Array.length a-$1) in a.(r) <- a.(r) - 1L
	let cumulate_destructive a = for i=1 to Array.length a -$ 2 do
		a.(i) <- a.(i) + a.(i-$1)
	done
end

let () =
	let n,r = get_2_i64	0 in
	let imos = Imos.make n in
	let ls = ref [] in
	rep 1L n (fun i ->
		let p = get_i64 0 in
		if p = 1L then (
			ls := i :: !ls;
			Imos.add_destructive_1orig_closed (i32 @@ i-r+1L) (i32 @@ i+r-1L) imos;
			(* printf "%Ld: %Ld %Ld\n" i (i-r+1L) (i+r-1L); *)
			(* dump_array imos; *)
		);
		`Ok
	);
	Imos.cumulate_destructive imos;
	(* dump_array imos; *)
	(* let f = Array.fold_left (fun u v ->
		if u then u else if v=0L then true else false) false imos
	in
	if f then (
		printf "-1\n"; exit 0
	); *)
	if repm 1L n false (fun u i ->
		`Ok (if u then u else if imos.(i32 i)=0L then true else false)
	) then (
		printf "-1\n"; exit 0
	);
	List.fold_left (fun u p ->
		let f = ref true in
		for i=(max (i32 @@ p-r+1L) 1) to min (i32 @@ p+r-1L) (i32 n) do
			if imos.(i) = 1L then f := false
		done;
		(* printf "%Ld: %b\n" p !f; *)
		if not !f then u+1L else (
			for i=max (i32 @@ p-r+1L) 1 to min (i32 @@ p+r-1L) (i32 n) do
				imos.(i) <- imos.(i) - 1L;
			done;
			(* dump_array imos; *)
			u
		)
	) 0L !ls
	|> printf "%Ld\n"

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline 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) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done
end open MyInt64

module Imos = struct
	let make n = Array.make (i32 n +$ 2) 0L
	let add_destructive_closed l r a =
		a.(l+$1) <- a.(l+$1) + 1L;
		a.(r+$2) <- a.(r+$2) - 1L
	let add_destructive_1orig_closed l r a =
		let l = max l 0 in a.(l) <- a.(l) + 1L;
		let r = min (r+$1) (Array.length a-$1) in a.(r) <- a.(r) - 1L
	let cumulate_destructive a = for i=1 to Array.length a -$ 2 do
		a.(i) <- a.(i) + a.(i-$1)
	done
end

let () =
	let n,r = get_2_i64	0 in
	let imos = Imos.make n in
	let ls = ref [] in
	rep 1L n (fun i ->
		let p = get_i64 0 in
		if p = 1L then (
			ls := i :: !ls;
			Imos.add_destructive_1orig_closed (i32 @@ i-r+1L) (i32 @@ i+r-1L) imos;
			(* printf "%Ld: %Ld %Ld\n" i (i-r+1L) (i+r-1L); *)
			(* dump_array imos; *)
		);
		`Ok
	);
	Imos.cumulate_destructive imos;
	(* dump_array imos; *)
	(* let f = Array.fold_left (fun u v ->
		if u then u else if v=0L then true else false) false imos
	in
	if f then (
		printf "-1\n"; exit 0
	); *)
	if repm 1L n false (fun u i ->
		`Ok (if u then u else if imos.(i32 i)=0L then true else false)
	) then (
		printf "-1\n"; exit 0
	);
	List.fold_left (fun u p ->
		let f = ref true in
		for i=(max (i32 @@ p-r+1L) 1) to min (i32 @@ p+r-1L) (i32 n) do
			if imos.(i) = 1L then f := false
		done;
		(* printf "%Ld: %b\n" p !f; *)
		if !f then u else u+1L
	) 0L !ls
	|> printf "%Ld\n"


A tree is a connected graph that doesn't contain any cycles.The distance between two vertices of a tree is the length (in edges) of the shortest path between these vertices.You are given a tree with n vertices and a positive number k. Find the number of distinct pairs of the vertices which have a distance of exactly k between them. Note that pairs (v, u) and (u, v) are considered to be the same pair.

The first line contains two integers n and k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 500) — the number of vertices and the required distance between the vertices. Next n - 1 lines describe the edges as "ai bi" (without the quotes) (1 ≤ ai, bi ≤ n, ai ≠ bi), where ai and bi are the vertices connected by the i-th edge. All given edges are different.

Print a single integer — the number of distinct pairs of the tree's vertices which have a distance of exactly k between them. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the pairs of vertexes at distance 2 from each other are (1, 3), (1, 5), (3, 5) and (2, 4).

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 es = Array.make n [] in
    for i = 1 to n - 1 do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(u) <- v :: es.(u);
	es.(v) <- u :: es.(v);
    done;
    let es = Array.map Array.of_list es in
    let res = ref 0L in
    let used = Array.make n false in
    let rec bfs u ds =
      let ds2 = Array.make k 0 in
      let ds4 = Array.make k 0 in
	ds2.(0) <- 1;
	ds4.(0) <- 1;
	for i = 1 to k - 1 do
	  ds2.(i) <- ds.(i - 1);
	done;
	(*for i = 0 to k - 1 do
	  Printf.printf "asd %d %d +%d\n" u i ds.(i);
	done;*)
	res := Int64.add !res (Int64.of_int ds.(k - 1));
	used.(u) <- true;
	for i = 0 to Array.length es.(u) - 1 do
	  let v = es.(u).(i) in
	    if not used.(v) then (
	      let ds3 = bfs v ds2 in
		for i = 1 to k - 1 do
		  ds2.(i) <- ds2.(i) + ds3.(i - 1);
		  ds4.(i) <- ds4.(i) + ds3.(i - 1);
		done
	    )
	done;
	ds4
    in
      ignore (bfs 0 (Array.make k 0));
      Printf.printf "%Ld\n" !res;


You are given a book with $$$n$$$ chapters.Each chapter has a specified list of other chapters that need to be understood in order to understand this chapter. To understand a chapter, you must read it after you understand every chapter on its required list.Currently you don't understand any of the chapters. You are going to read the book from the beginning till the end repeatedly until you understand the whole book. Note that if you read a chapter at a moment when you don't understand some of the required chapters, you don't understand this chapter.Determine how many times you will read the book to understand every chapter, or determine that you will never understand every chapter no matter how many times you read the book.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — number of chapters. Then $$$n$$$ lines follow. The $$$i$$$-th line begins with an integer $$$k_i$$$ ($$$0 \le k_i \le n-1$$$) — number of chapters required to understand the $$$i$$$-th chapter. Then $$$k_i$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le n, a_{i, j} \ne i, a_{i, j} \ne a_{i, l}$$$ for $$$j \ne l$$$) follow — the chapters required to understand the $$$i$$$-th chapter. It is guaranteed that the sum of $$$n$$$ and sum of $$$k_i$$$ over all testcases do not exceed $$$2\cdot10^5$$$.

For each test case, if the entire book can be understood, print how many times you will read it, otherwise print $$$-1$$$.

NoteIn the first example, we will understand chapters $$$\{2, 4\}$$$ in the first reading and chapters $$$\{1, 3\}$$$ in the second reading of the book.In the second example, every chapter requires the understanding of some other chapter, so it is impossible to understand the book.In the third example, every chapter requires only chapters that appear earlier in the book, so we can understand everything in one go.In the fourth example, we will understand chapters $$$\{2, 3, 4\}$$$ in the first reading and chapter $$$1$$$ in the second reading of the book.In the fifth example, we will understand one chapter in every reading from $$$5$$$ to $$$1$$$.

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in

    let graph = Array.make n [] in

    for i=0 to n-1 do
      let k = read_int () in
      for z=0 to k-1 do
	let j = -1+read_int () in
	(* chapter j depends on i *)
	graph.(i) <- j::graph.(i)
      done
    done;
    (* graph is the reverse of the dependency graph *)

    (* first see if the graph is acyclic *)
    let visited = Array.make n false in
    let sorted = Array.make n 0 in
    let k = ref 0 in
    let rec topsort v =
      if not visited.(v) then (
	visited.(v) <- true;
	List.iter topsort graph.(v);
	sorted.(v) <- !k;
	k := !k+1
      )
    in
    for v=0 to n-1 do topsort v done;

    let acyclic = forall 0 (n-1) (fun v ->
      List.fold_left (fun ac w ->
	ac && sorted.(v) > sorted.(w)
      ) true graph.(v))
    in
    if not acyclic then printf "-1\n" else (

      let lirp = Array.make n (-1) in  (* longest increasing reverse path *)

      let rec dfs v =
	if lirp.(v) >= 0 then lirp.(v) else (
	  let my_val = List.fold_left (fun ac w ->
	    let x = (if w>v then 1 else 0) + (dfs w) in
	    max ac x
	  ) 0 graph.(v)
	  in
	  lirp.(v) <- my_val;
	  my_val
	)
      in

      printf "%d\n" (1 + maxf 0 (n-1) dfs)
    )
  done


You are given an array $$$a$$$ of $$$n$$$ integers and an integer $$$s$$$. It is guaranteed that $$$n$$$ is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $$$s$$$.The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $$$6, 5, 8$$$ is equal to $$$6$$$, since if we sort this array we will get $$$5, 6, 8$$$, and $$$6$$$ is located on the middle position.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1\le n\le 2\cdot 10^5-1$$$, $$$1\le s\le 10^9$$$) — the length of the array and the required value of median. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1\le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that $$$n$$$ is odd.

In a single line output the minimum number of operations to make the median being equal to $$$s$$$.

NoteIn the first sample, $$$6$$$ can be increased twice. The array will transform to $$$8, 5, 8$$$, which becomes $$$5, 8, 8$$$ after sorting, hence the median is equal to $$$8$$$.In the second sample, $$$19$$$ can be increased once and $$$15$$$ can be increased five times. The array will become equal to $$$21, 20, 12, 11, 20, 20, 12$$$. If we sort this array we get $$$11, 12, 12, 20, 20, 20, 21$$$, this way the median is $$$20$$$.

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

	let repm from_ to_ m_init fbod =
		let i,f,m = ref ~|from_,ref true,ref m_init in
		while !i <= ~|to_ && !f do
			match fbod (~~| !i) !m with
			| `Break -> f := false
			| `Break_m m' -> (f := false; m := m')
			| `Ok m' -> (i := !i +$ 1; m := m')
		done; !m
end open MyInt64
module Array = struct
	include Array
	let destruct f a =
		for i=0 to (Array.length a -$ 1) do
			let c = ref a.(i) in f c; a.(i) <- !c;
		done
	let destructi f a =
		for i=0 to (Array.length a -$ 1) do
			let c = ref a.(i) in f i c; a.(i) <- !c;
		done
	let foldi_left f v a =
		let m = ref v in for i=0 to (Array.length a -$ 1) do
			m := f !m (~~|i) a.(i)
		done; !m
	let foldii_left f v a =
		let m = ref v in for i=0 to (Array.length a -$ 1) do
			m := f !m (~~|i)
		done; !m
	let foldmap f v a =
		let m = ref v in Array.map (fun w -> let mm,vv = f !m w in m := mm; vv) a
	let foldmapi f v a =
		let m = ref v in Array.mapi (fun i w -> let mm,vv = f i !m v in m := mm; vv) a
	(* let exists f a = BatArray.exists *)
	let exists f a = let flg,i = ref true,ref 0 in while !flg && !i<Array.length a -$ 1 do if f a.(!i) then flg := false; i := !i +$ 1 done; not !flg
end
let () =
	let n,s = get_2_i64 0
	in let a = input_i64_array n
	in Array.sort compare a;
	let i_mid = n/2L
	in
	Array.foldi_left (fun u i v ->
		let d = labs (s - v) in
		if i < i_mid && v > s
		|| i > i_mid && v < s
		|| i = i_mid && v <> s then u + d
		else u
	) 0L a
	|> printf "%Ld\n"

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v
	let labs p = if p < 0L then -1L*p else p
	let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p

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

	let (mod) m n = m - (m/n) * n let (%) = (mod)
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n
	let repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
	let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
end

open MyInt64
let () =
	let n,s = get_2_i64 0
	in
	if n=1L then (
		let v = get_i64 0 in printf "%Ld" (labs (v-s))
	) else (
	let a = Array.make (~|n) 0L in
	rep 0L (n) (fun i ->
		a.(~|i) <- get_i64 0;
		(* printf ";;%Ld %Ld\n" i a.(~|i); *)
		`Ok
	);
	Array.sort compare a;
	let i_med = n / 2L
	in let i_nearest = (
		let fv = ref 0L in
		let res = ref (n) in
		repint 0L (n) (fun i ->
			(* printf "::%d, %Ld\n" i a.(i); *)
			if a.(i) = s then (
				res := ~~| i; `Ng
			)
			else if a.(i) < s then (
				fv := a.(i); `Ok
			) else (
				if s - !fv < a.(i) - s then (
					res := ~~| i
				) else (
					res := ~~| i - 1L
				);
				`Ng
			)
		); !res
	) in
	let res = ref 0L in
	rep i_med i_nearest (fun i ->
		res += (s - a.(~|i)); `Ok
	);
	!res |> printf "%Ld\n";
	(* printf "%Ld %Ld" i_med i_nearest; *)
	)

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v
	let labs p = if p < 0L then -1L*p else p
	let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p

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

	let (mod) m n = m - (m/n) * n let (%) = (mod)
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n
	let repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
	let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
end

open MyInt64
let () =
	let n,s = get_2_i64 0
	in
	if n=1L then (
		let v = get_i64 0 in printf "%Ld" (labs (v-s))
	) else (
	let a = Array.make (~|n) 0L in
	rep 0L (n) (fun i ->
		a.(~|i) <- get_i64 0;
		(* printf ";;%Ld %Ld\n" i a.(~|i); *)
		`Ok
	);
	Array.sort compare a;
	let i_med = n / 2L
	in let i_nearest = (
		let fv = ref 0L in
		let res = ref (n) in
		repint 0L (n) (fun i ->
			(* printf "::%d, %Ld\n" i a.(i); *)
			if a.(i) = s then (
				res := ~~| i; `Ng
			)
			else if a.(i) < s then (
				fv := a.(i); `Ok
			) else (
				if !fv = 0L then (
					res := ~~| i
				) else if s - !fv < a.(i) - s then (
					res := ~~| i
				) else (
					res := ~~| i - 1L
				);
				`Ng
			)
		); !res
	) in
	let res = ref 0L in
	if i_nearest > i_med
	then rep i_med i_nearest (fun i ->
		res += labs (s - a.(~|i)); `Ok
	) else rep i_nearest (i_med + 1L) (fun i ->
		res += labs (s - a.(~|i)); `Ok
	);
	!res |> printf "%Ld\n";
	(* printf "%Ld %Ld" i_med i_nearest; *)
	)

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

	let repm from_ to_ m_init fbod =
		let i,f,m = ref ~|from_,ref true,ref m_init in
		while !i <= ~|to_ && !f do
			match fbod (~~| !i) !m with
			| `Break -> f := false
			| `Break_m m' -> (f := false; m := m')
			| `Ok m' -> (i := !i +$ 1; m := m')
		done; !m
end

open MyInt64
let rec binary_search_value_nearest v l r a =
	if a.(~|l) > v then `Nearest l
	else if a.(~|r) < v then `Nearest r
	else if l=r then (
		if a.(~|l)=v then `At l else `Nearest l
	) else (
		let mid = l+(r-l)/2L in
		if a.(~|mid)>v then binary_search_value_nearest v l (mid-1L) a else
		if a.(~|mid)<v then binary_search_value_nearest v (mid+1L) r a
		else `At mid
	)
let () =
	let n,s = get_2_i64 0
	in let a = input_i64_array n
	in Array.sort compare a;
	let i_mid = n/2L in
	let i_nearest = (
		match binary_search_value_nearest s 0L (n-1L) a with
		| `At i | `Nearest i -> i
	) in
	let ans =
		if i_mid = i_nearest then (
			labs (s - a.(~|i_nearest))
		) else if i_mid < i_nearest then (
			repm i_mid i_nearest 0L (fun i m -> `Ok (m + labs (s - a.(~|i))))
		) else (
			repm i_nearest i_mid 0L (fun i m -> `Ok (m + labs (s - a.(~|i))))
		)
	in
	printf "%Ld\n" ans

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v
	let labs p = if p < 0L then -1L*p else p
	let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p

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

	let (mod) m n = m - (m/n) * n let (%) = (mod)
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n
	let repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
	let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
end

open MyInt64
let () =
	let n,s = get_2_i64 0
	in
	if n=1L then (
		let v = get_i64 0 in printf "%Ld" (labs (v-s))
	) else (
	let a = Array.make (~|n) 0L in
	rep 0L (n) (fun i ->
		a.(~|i) <- get_i64 0;
		(* printf ";;%Ld %Ld\n" i a.(~|i); *)
		`Ok
	);
	Array.sort compare a;
	let i_med = n / 2L
	in let i_nearest = (
		let fv = ref 0L in
		let res = ref (n) in
		repint 0L (n) (fun i ->
			(* printf "::%d, %Ld\n" i a.(i); *)
			if a.(i) = s then (
				res := ~~| i; `Ng
			)
			else if a.(i) < s then (
				fv := a.(i); `Ok
			) else (
				if !fv = 0L then (
					res := ~~| i
				) else if labs (s - !fv) < labs  (a.(i) - s) then (
					res := ~~| i - 1L
				) else if labs (s - !fv) > labs  (a.(i) - s) then (
					res := ~~| i
				) else (
					res := (
						if labs (~~|i - i_med) < labs (~~|i - 1L - i_med) then (
							~~| i
						) else (
							~~| i - 1L
						)
					)
				);
				`Ng
			)
		); !res
	) in
	let res = ref 0L in
	if i_nearest > i_med
	then rep i_med (min (i_nearest + 1L) n) (fun i ->
		res += labs (s - a.(~|i)); `Ok
	) else rep i_nearest (i_med + 1L) (fun i ->
		res += labs (s - a.(~|i)); `Ok
	);
	!res |> printf "%Ld\n";
	(* printf "%Ld %Ld" i_med i_nearest; *)
	)

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v
	let labs p = if p < 0L then -1L*p else p
	let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p

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

	let (mod) m n = m - (m/n) * n let (%) = (mod)
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n
	let repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
	let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
end

open MyInt64
let () =
	let n,s = get_2_i64 0
	in
	if n=1L then (
		let v = get_i64 0 in printf "%Ld" (labs (v-s))
	) else (
	let a = Array.make (~|n) 0L in
	rep 0L (n) (fun i ->
		a.(~|i) <- get_i64 0;
		(* printf ";;%Ld %Ld\n" i a.(~|i); *)
		`Ok
	);
	Array.sort compare a;
	let i_med = n / 2L
	in let i_nearest = (
		let fv = ref 0L in
		let res = ref (n) in
		repint 0L (n) (fun i ->
			(* printf "::%d, %Ld\n" i a.(i); *)
			if a.(i) = s then (
				res := ~~| i; `Ng
			)
			else if a.(i) < s then (
				fv := a.(i); `Ok
			) else (
				if !fv = 0L then (
					res := ~~| i
				) else if s - !fv < a.(i) - s then (
					res := ~~| i
				) else if s - !fv > a.(i) - s then (
					res := ~~| i - 1L
				) else (
					res := (
						if labs (~~|i - i_med) < labs (~~|i - 1L - i_med) then (
							~~| i
						) else (
							~~| i - 1L
						)
					)
				);
				`Ng
			)
		); !res
	) in
	let res = ref 0L in
	if i_nearest > i_med
	then rep i_med i_nearest (fun i ->
		res += labs (s - a.(~|i)); `Ok
	) else rep i_nearest (i_med + 1L) (fun i ->
		res += labs (s - a.(~|i)); `Ok
	);
	!res |> printf "%Ld\n";
	(* printf "%Ld %Ld" i_med i_nearest; *)
	)

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v
	let labs p = if p < 0L then -1L*p else p
	let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p

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

	let (mod) m n = m - (m/n) * n let (%) = (mod)
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n
	let repint from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
	let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do match fbod ~~| !i with | `Ng -> f := false | _ -> i := !i +$ 1; done
end

open MyInt64
let () =
	let n,s = get_2_i64 0
	in
	if n=1L then (
		let v = get_i64 0 in printf "%Ld" (labs (v-s))
	) else (
	let a = Array.make (~|n) 0L in
	rep 0L (n) (fun i ->
		a.(~|i) <- get_i64 0;
		(* printf ";;%Ld %Ld\n" i a.(~|i); *)
		`Ok
	);
	Array.sort compare a;
	let i_med = n / 2L
	in let i_nearest = (
		let fv = ref 0L in
		let res = ref (n) in
		repint 0L (n) (fun i ->
			(* printf "::%d, %Ld\n" i a.(i); *)
			if a.(i) = s then (
				res := ~~| i; `Ng
			)
			else if a.(i) < s then (
				fv := a.(i); `Ok
			) else (
				if !fv = 0L then (
					res := ~~| i
				) else if s - !fv < a.(i) - s then (
					res := ~~| i
				) else if s - !fv > a.(i) - s then (
					res := ~~| i - 1L
				) else (
					res := (
						if labs (~~|i - i_med) < labs (~~|i - 1L - i_med) then (
							~~| i
						) else (
							~~| i - 1L
						)
					)
				);
				`Ng
			)
		); !res
	) in
	let res = ref 0L in
	if i_nearest > i_med
	then rep i_med (min (i_nearest + 1L) n) (fun i ->
		res += labs (s - a.(~|i)); `Ok
	) else rep i_nearest (i_med + 1L) (fun i ->
		res += labs (s - a.(~|i)); `Ok
	);
	!res |> printf "%Ld\n";
	(* printf "%Ld %Ld" i_med i_nearest; *)
	)


You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?

The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$), where $$$2n$$$ is the number of elements in the array $$$a$$$. The second line contains $$$2n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{2n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.

If there's no solution, print "-1" (without quotes). Otherwise, print a single line containing $$$2n$$$ space-separated integers. They must form a reordering of $$$a$$$. You are allowed to not change the order.

NoteIn the first example, the first $$$n$$$ elements have sum $$$2+1+3=6$$$ while the last $$$n$$$ elements have sum $$$1+1+2=4$$$. The sums aren't equal.In the second example, there's no solution.

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x*2) in
  let a = Array.init n
      (fun _ ->
         Scanf.scanf "%d " (fun x -> x)
      )
  in
  let xx = a.(0) in
  let a = Array.to_list a in
  let all_eq =
    List.fold_left
      (fun acc x -> x = xx && acc) true a
  in
  if all_eq then Printf.printf "-1" else
    let a = List.sort compare a in
    List.iter (fun x -> Printf.printf "%d " x) a
;;


Marmot found a row with n pillars. The i-th pillar has the height of hi meters. Starting from one pillar i1, Marmot wants to jump on the pillars i2, ..., ik. (1 ≤ i1 < i2 < ... < ik ≤ n). From a pillar i Marmot can jump on a pillar j only if i < j and |hi - hj| ≥ d, where |x| is the absolute value of the number x.Now Marmot is asking you find out a jump sequence with maximal length and print it.

The first line contains two integers n and d (1 ≤ n ≤ 105, 0 ≤ d ≤ 109). The second line contains n numbers h1, h2, ..., hn (1 ≤ hi ≤ 1015).

The first line should contain one integer k, the maximal length of a jump sequence. The second line should contain k integers i1, i2, ..., ik (1 ≤ i1 < i2 < ... < ik ≤ n), representing the pillars' indices from the maximal length jump sequence. If there is more than one maximal length jump sequence, print any.

NoteIn the first example Marmot chooses the pillars 1, 2, 3, 5 with the heights 1, 3, 6, 4. Another jump sequence of length 4 is 1, 2, 4, 5.

module Lib_option = struct
  module Option = struct
    let value ~default = function
      | None       -> default
      | Some value -> value
  end
end

module Lib_algorithm = struct
  open Lib_option

  let lower_bound ?(compare=compare) ?len arr ~x =
    let len = Option.value ~default:(Array.length arr) len in
    let bound = ref (-1) in
    let step = ref 1 in
    while !step lsl 1 < len do
      step := !step lsl 1
    done;
    while !step > 0 do
      let pos = !bound + !step in
      if pos < len && compare x arr.(pos) > 0 then
        bound := pos;
      step := !step lsr 1
    done;
    !bound + 1
  ;;
end

module Lib_iterators = struct
  module Make_iterators(C : sig
      type 'a t;;
      val iter : ('a -> unit) -> 'a t -> unit
      val map : ('a -> 'b) -> 'a t -> 'b t
      val iteri : (int -> 'a -> unit) -> 'a t -> unit
      val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t
    end) = struct
    let map ~f arr = C.map f arr;;
    let mapi ~f arr = C.mapi f arr;;
    let iter ~f arr = C.iter f arr;;
    let iteri ~f arr = C.iteri f arr;;
  end
end

module Lib_array = struct
  open Lib_iterators

  module T = struct
    include Array
    type 'a t = 'a array;;
  end

  module Array = struct
    include T
    include Make_iterators(T)

    let sort ?(cmp=compare) arr = sort cmp arr;;
  end
end

module Lib_int64 = struct
  module Int64 = struct
    include Int64

    let (+),(-),( * ),(/),(%),(~-) = add,sub,mul,div,rem,neg;;
  end
end

module Lib_core = struct
  let id x = x;;
  let const x _ = x;;

  let fail () = failwith "";;
end

module Lib_io = struct
  open Lib_core

  let printf = Printf.printf;;
  let scanf = Scanf.scanf;;

  let read_int () = scanf " %d " id;;
  let read_long () = scanf " %Ld " id;;
  let read_char () = scanf " %c " id;;
  let read_array n ~f = Array.init n (fun _ -> f ());;
end

module Lib_list = struct
  open Lib_iterators

  module T = struct
    include List
    type 'a t = 'a list;;
  end

  module List = struct
    include T
    include Make_iterators(T)

    let rev_map ~f l = rev_map f l;;
  end
end

module Lib_fenwick = struct
  module Make_fenwick(V : sig
      type t;;
      val neutral : t;;
      val reduce : t -> t -> t;;
    end) : sig
    type t;;
    type value;;
    val create : int -> t;;
    val update : t -> int -> value -> unit;;
    val query : t -> int -> value;;
  end with type value := V.t
  = struct
    type t = V.t array;;

    let create n = Array.make n V.neutral;;

    let lowbit x = x land -x;;

    let update t i x =
      let len = Array.length t in
      let i = ref (i + 1) in
      while !i <= len do
        t.(!i - 1) <- V.reduce t.(!i - 1) x;
        i := !i + lowbit !i
      done
    ;;

    let query t i =
      let i = ref (i + 1) in
      let acc = ref V.neutral in
      while !i > 0 do
        acc := V.reduce !acc t.(!i - 1);
        i := !i - lowbit !i
      done;
      !acc
    ;;
  end
end

module Lib_maxpos_fenwick = struct
  open Lib_fenwick

  module Make_fenwick(T : sig
      type t;;
      val zero : t;;
    end) = Make_fenwick (struct
      type t = T.t;;
      let neutral = T.zero;;
      let reduce = max;;
    end)

  module Int_fenwick = Make_fenwick(struct
      type t = int;;
      let zero = 0;;
    end)
end

open Lib_io
open Lib_array
open Lib_list
open Lib_algorithm
open Lib_int64

module Fenwick = Lib_maxpos_fenwick.Int_fenwick

let () =
  let n = read_int () in
  let d = read_long () in
  let hgs = read_array n ~f:read_long in
  let shgs = Array.copy hgs in
  Array.sort shgs;
  let lfen = Fenwick.create n in
  let rfen = Fenwick.create n in
  let vals = ref [] in
  let best = ref 0 in
  Array.iter hgs ~f:(fun h ->
      let lpos = lower_bound shgs ~x:Int64.(h - d + 1L) - 1 in
      let rpos = lower_bound shgs ~x:Int64.(h + d) in
      let curr =
        max (Fenwick.query lfen lpos) (Fenwick.query rfen (n - rpos - 1)) + 1
      in
      vals := curr :: !vals;
      best := max !best curr;
      let pos = lower_bound shgs ~x:h in
      Fenwick.update lfen pos curr;
      Fenwick.update rfen (n - pos - 1) curr
    );
  let curr = ref !best in
  let lasth = ref 0L in
  let path = ref [] in
  List.iteri !vals ~f:(fun i v ->
      let i = n - i - 1 in
      let h = hgs.(i) in
      if v = !curr && (!lasth = 0L || Int64.(abs (!lasth - h)) >= d) then begin
        path := (i + 1) :: !path;
        decr curr;
        lasth := h
      end
    );
  printf "%d\n" !best;
  List.iter !path ~f:(printf "%d ");
  print_newline ()
;;


One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

let pf = Printf.printf ;;
let epf = Printf.eprintf ;;
let sf = Scanf.scanf ;;

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

module Array = ArrayLabels ;;
module List  = ListLabels ;;

let solve n arr =
  let prev = ref arr.(0) in
  let rec iter i =
    if i = n then n
    else if !prev > arr.(i) then i
    else begin prev := arr.(i); iter (i + 1) end in
  let last = iter 1 in
  if last = n then pf "0"
  else
    let prev = ref arr.(last) in
    let rec iter i =
      if i = n then n
      else if !prev > arr.(i) then i
      else begin prev := arr.(i);  iter (i + 1) end in
    let l = iter (last + 1) in
    if l = n && arr.(n - 1) <= arr.(0) then pf "%d\n" (n - last)
    else pf "-1\n"
;;

let () =
  sf "%d " (fun n ->
    let arr = Array.init n ~f:(fun _ -> sf "%d " (fun i -> i)) in
    solve n arr)
;;

let input () =
  let n = Scanf.scanf " %d " (fun x -> x) in
  let a = ref 0 in
  let l = ref [] in
  for i = 1 to n do
    if i = n then
      a := Scanf.scanf "%d\n" (fun x -> x)
    else
      a := Scanf.scanf " %d " (fun x -> x);

    l := !a :: !l;
  done;
  List.rev !l

let () =
  let rec scan l n head turn_down index =
    match l with
    | [] -> Printf.printf "-1\n"
    | t :: [] ->
       begin
	 match n with
	 | 2 ->
	    if (t <= head) then
	      Printf.printf "%d\n" (index - turn_down)
	    else
	      Printf.printf "-1\n"
	 | 1 ->
	    Printf.printf "0\n"
	 | _ ->
	    Printf.printf "-1\n"
       end
    | last :: ((h :: t) as tl) ->
       if n <= 2 then
	 if h >= last then
	   scan tl n head turn_down (index+1)
	 else
	   scan tl (n+1) head index (index+1)
       else
	 Printf.printf "%d\n" (-1)
  in
  let l = input () in
  scan l 1 (List.hd l) (-1) 1

let pf = Printf.printf ;;
let epf = Printf.eprintf ;;
let sf = Scanf.scanf ;;

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

module Array = ArrayLabels ;;
module List  = ListLabels ;;

let solve n arr =
  let prev = ref arr.(0) in
  let rec iter i =
    if i = n then n
    else if !prev > arr.(i) then i
    else begin prev := arr.(i); iter (i + 1) end in
  let last = iter 1 in
  if last = n then pf "0"
  else
    let prev = ref arr.(last) in
    let rec iter i =
      if i = n then n
      else if !prev > arr.(i) then i
      else begin prev := arr.(i);  iter (i + 1) end in
    let l = iter (last + 1) in
    if l = n && arr.(n - 1) < arr.(0) then pf "%d\n" (n - last)
    else pf "-1\n"
;;

let () =
  sf "%d " (fun n ->
    let arr = Array.init n ~f:(fun _ -> sf "%d " (fun i -> i)) in
    solve n arr)
;;

let input () =
  let n = Scanf.scanf " %d " (fun x -> x) in
  let a = ref 0 in
  let l = ref [] in
  for i = 1 to n do
    if i = n then
      a := Scanf.scanf "%d\n" (fun x -> x)
    else
      a := Scanf.scanf " %d " (fun x -> x);

    l := !a :: !l;
  done;
  List.rev !l

let () =
  let rec scan l n head turn_down index =
    match l with
    | [] -> Printf.printf "-1\n"
    | t :: [] ->
       if n = 2 then
	 if t <= head then
	   Printf.printf "%d\n" (index - turn_down)
	 else
	   Printf.printf "-1\n"
       else
	 Printf.printf "0\n"
    | last :: ((h :: t) as tl) ->
       if n <= 2 then
	 if h >= last then
	   scan tl n head turn_down (index+1)
	 else
	   scan tl (n+1) head index (index+1)
       else
	 Printf.printf "%d\n" (-1)
  in
  let l = input () in
  scan l 1 (List.hd l) (-1) 1

let input () =
  let n = Scanf.scanf " %d " (fun x -> x) in
  let a = ref 0 in
  let l = ref [] in
  for i = 1 to n do
    if i = n then
      a := Scanf.scanf "%d\n" (fun x -> x)
    else
      a := Scanf.scanf " %d " (fun x -> x);

    l := !a :: !l;
  done;
  List.rev !l

let () =
  let rec scan l n head turn_down index =
    match l with
    | [] -> Printf.printf "-1\n"
    | t :: [] ->
       begin
	 match n with
	 | 2 ->
	    if (t <= head) then
	      Printf.printf "%d\n" (index - turn_down)
	    else
	      Printf.printf "-1\n"
	 | 1 ->
	    Printf.printf "0\n"
	 | _ ->
	    Printf.printf "-1\n"
       end
    | last :: ((h :: t) as tl) ->
       if n <= 2 then
	 if h >= last then
	   scan tl n head (index+1) (index+1)
	 else
	   scan tl (n+1) head index (index+1)
       else
	 Printf.printf "%d\n" (-1)
  in
  let l = input () in
  scan l 1 (List.hd l) (-1) 1


There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".

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

let find_segs xs =
  let rec find_segs_aux i xs seen acc =
    match xs with
    | [] -> acc
    | [x] -> begin
      match acc with
      | [] ->
          if IntSet.mem x seen
          then [ 1, i ]
          else []
      | (lo, hi)::rest ->
          if IntSet.mem x seen
          then (hi + 1, i) :: (lo, hi) :: rest
          else (lo, i) :: rest
    end
    | x :: xs -> begin
      match acc with
      | [] ->
          if IntSet.mem x seen
          then find_segs_aux (i + 1) xs (IntSet.empty) [ 1, i ]
          else find_segs_aux (i + 1) xs (IntSet.add x seen) []
      | (lo, hi)::rest ->
          if IntSet.mem x seen
          then find_segs_aux (i + 1) xs (IntSet.empty) ((hi + 1, i)::acc)
          else find_segs_aux (i + 1) xs (IntSet.add x seen) acc
    end
  in
  find_segs_aux 1 xs IntSet.empty []

let print_output = function
  | [] -> print_int (-1); print_newline ()
  | xs ->
      print_int (List.length xs);
      print_newline ();
      List.iter (fun (lo, hi) ->
        print_int lo;
        print_string " ";
        print_int hi;
        print_newline ()) xs

let () =
  ignore (read_line ()); read_line ()
  |> Str.split (Str.regexp " ")
  |> List.map int_of_string
  |> find_segs
  |> print_output

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

let () =
  let rec find a l r x =
    let m = (l + r) / 2 in
    if a.(m) = x then m
    else (
      if a.(m) < x then (find a (m + 1) r x)
      else (find a l (m - 1) x)
    )
  in

  let min x y =
    if x < y then x
    else y
  in

  let n = xint() in
  let a = Array.make n 0 in
  let xs = Array.make n 0 and m = ref 0 in

  for i = 0 to n - 1 do
    a.(i) <- xint();
    xs.(i) <- a.(i);
  done;
  Array.sort (fun x y -> x - y) xs;
  m := 1;
  for i = 1 to n - 1 do
    if xs.(i) != xs.(i - 1) then (
      xs.(!m) <- xs.(i);
      m := !m + 1;
    )
  done;

  let nx = Array.make n n and pos = Array.make !m n in

  for i = n - 1 downto 0 do
    a.(i) <- find xs 0 (!m - 1) a.(i);
    nx.(i) <- pos.(a.(i));
    pos.(a.(i)) <- i;
  done;

  let l = Array.make n 0 and r = Array.make n 0 in
  let ret = ref 0 and i = ref 0 in
  while !i < n do
    let x = !i and y = ref nx.(!i) in
    while !i < !y do
      y := min !y nx.(!i);
      i := !i + 1;
    done;
    if !y != n then (
      l.(!ret) <- x + 1;
      r.(!ret) <- !y + 1;
      ret := !ret + 1;
    );
    if !y = n && x != 0 then (
      r.(!ret - 1) <- n;
    );
    i := !i + 1;
  done;

  if !ret = 0 then (
    Printf.printf "-1\n";
  ) else (
    Printf.printf "%d\n" !ret;
    for i = 0 to !ret - 1 do
      Printf.printf "%d %d\n" l.(i) r.(i);
    done;
  )

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let ks = ref [] in
  let ht = Hashtbl.create 10 in
  let prev = ref (-1) in
    for i = 0 to n - 1 do
      if Hashtbl.mem ht a.(i) then (
	ks := (!prev + 1, i) :: !ks;
	prev := i;
	Hashtbl.clear ht;
      ) else (
	Hashtbl.replace ht a.(i) ()
      )
    done;
    let ks =
      if !prev = n - 1
      then !ks
      else (
	match !ks with
	  | [] ->
	      Printf.printf "-1\n";
	      exit 0
	  | (l, r) :: ks ->
	      (l, n - 1) :: ks
      )
    in
    let ks = List.rev ks in
      Printf.printf "%d\n" (List.length ks);
      List.iter
	(fun (l, r) ->
	   Printf.printf "%d %d\n" (l + 1) (r + 1)
	) ks

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 read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> read_int()) in

  let find_segment i =
  (* find segment starting from i.  either Some (i,j) or None *)
    let h = Hashtbl.create 5 in
    let rec loop j = if j>=n then None else
	if Hashtbl.mem h a.(j) then Some (i,j) else (
	  Hashtbl.add h a.(j) true;
	  loop (j+1)
	)
    in
    if i >= n then None else (
      Hashtbl.add h a.(i) true;
      loop (i+1)
    )
  in

  let rec outer_loop i ac =
    match find_segment i with
      | Some (_,j) -> outer_loop (j+1) ((i,j)::ac)
      | None ->
	match ac with
	  | [] -> []
	  | (i,j)::tail -> (i,n-1)::tail
  in

  match outer_loop 0 [] with
    | [] -> printf "-1\n"
    | li ->
      printf "%d\n" (List.length li);
      List.iter (fun (i,j) -> printf "%d %d\n" (i+1) (j+1)) li

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

let () =
  let rec find a l r x =
    let m = (l + r) / 2 in
    if a.(m) = x then m
    else (
      if a.(m) < x then (find a (m + 1) r x)
      else (find a l (m - 1) x)
    )
  in

  let min x y =
    if x < y then x
    else y
  in

  let n = xint() in
  let a = Array.make n 0 in
  let xs = Array.make n 0 and m = ref 0 in

  for i = 0 to n - 1 do
    a.(i) <- xint();
    xs.(i) <- a.(i);
  done;
  Array.sort (fun x y -> x - y) xs;
  m := 1;
  for i = 1 to n - 1 do
    if xs.(i) != xs.(i - 1) then (
      xs.(!m) <- xs.(i);
      m := !m + 1;
    )
  done;

  let nx = Array.make n n and pos = Array.make !m n in

  for i = n - 1 downto 0 do
    a.(i) <- find xs 0 (!m - 1) a.(i);
    nx.(i) <- pos.(a.(i));
    pos.(a.(i)) <- i;
  done;

  let l = Array.make n 0 and r = Array.make n 0 in
  let ret = ref 0 and i = ref 0 in
  while !i < n do
    let x = !i and y = ref nx.(!i) in
    while !i < !y do
      y := min !y nx.(!i);
      i := !i + 1;
    done;
    if !y != n then (
      l.(!ret) <- x + 1;
      r.(!ret) <- !y + 1;
      ret := !ret + 1;
    );
    i := !i + 1;
  done;

  if !ret = 0 then (
    Printf.printf "-1\n";
  ) else (
    Printf.printf "%d\n" !ret;
    for i = 0 to !ret - 1 do
      Printf.printf "%d %d\n" l.(i) r.(i);
    done;
  )


Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any real number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-0.5$$$ on the path from $$$4$$$ to $$$5$$$.   Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree.

If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".  Otherwise, output "YES".  You can print each letter in any case (upper or lower).

NoteIn the first example, we can add any real $$$x$$$ to the value written on the only edge $$$(1, 2)$$$.  In the second example, one of configurations that we can't reach is $$$0$$$ written on $$$(1, 2)$$$ and $$$1$$$ written on $$$(2, 3)$$$.  Below you can see graphs from examples $$$3$$$, $$$4$$$:

let () =
    let main () =
        let n = int_of_string (read_line ()) in
        let nodes = Array.make n 0 in
        for i = 1 to n - 1 do
            Scanf.sscanf (read_line ()) "%d %d" (fun a b ->
                nodes.(a - 1) <- nodes.(a - 1) + 1;
                nodes.(b - 1) <- nodes.(b - 1) + 1)
        done;
        let rec loop i =
            if i < 0 then "YES" else
                if nodes.(i) = 2 then "NO" else loop (i - 1)
        in
        print_endline (loop (n - 1))
    in
    main ()


Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

The first line contains integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.

NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.

let scanf = Scanf.scanf

let printf = Printf.printf

let flip = function 0 -> 1
                  | 1 -> 0

let find_last_index (e: 'a) (src: 'a array): int option =
  let rec f (i: int): int option =
    if i < 0
    then None
    else if src.(i) = e then Some i
    else f (i - 1)
  in f (Array.length src - 1)

let extract_option (Some x) = x

let _ =
  let n = Scanf.scanf "%d " (fun i -> i) in
  let arr = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i)) in
  let ele_to_find = flip (arr.(Array.length arr - 1)) in
  printf "%d\n" ((find_last_index ele_to_find arr |> extract_option) + 1)


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each query print one integer in a single line — the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.

NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3]$$$.

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let [t] = read_ints ();;
for _ = 1 to t do
  let [n] = read_ints () and a = read_ints () in
  let [c0; c1; c2] = List.(
      map
        (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)
        [0; 1; 2]) in
  let r =
    if c1 > c2 then
      c0 + c2 + (c1 - c2) / 3
    else
      c0 + c1 + (c2 - c1) / 3
  in
  print_ints [r]
done;;

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let [t] = read_ints ();;
for _ = 1 to t do
  let [n] = read_ints () and a = read_ints () in
  let [c0; c1; c2] = List.(
      map
        (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)
        [0; 1; 2]) in
  let r = c0 + (c1 + 2*c2) / 3 - (if c2 mod 3 == 2 && c1 < 2 then 1 else 0) in
  print_ints [r]
done;;

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let rec solve n =
  1 +
    let open Int64 in
    if rem n 2L = 0L then
      solve (div n 2L)
    else if rem n 3L = 0L then
      solve (mul 2L (div n 3L))
    else if rem n 5L = 0L then
      solve (mul 4L (div n 5L))
    else if n = 1L then
      -1
    else
      raise Not_found;;

let [t] = read_ints ();;
for _ = 1 to t do
  let [n] = read_ints () and a = read_int64s () in
  let open Int64 in
  let [c0; c1; c2] = List.(
      map
        (fun r -> fold_left (fun acc x -> if rem x 3L = r then acc + 1 else acc) 0 a)
        [0L; 1L; 2L]) in
  let r = c0 + (c1 + 2*c2) / 3 - (if c2 > c1 && (c1 + 2*c2) mod 3 == 1 then 1 else 0) in
  print_ints [r]
done;;

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let [t] = read_ints ();;
for _ = 1 to t do
  let [n] = read_ints () and a = read_ints () in
  let [c0; c1; c2] = List.(
      map
        (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)
        [0; 1; 2]) in
  let r = c0 + (c1 + 2*c2) / 3 - (if c2 mod 3 == 2 && c1 == 0 then 1 else 0) in
  print_ints [r]
done;;

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let rec solve n =
  1 +
    let open Int64 in
    if rem n 2L = 0L then
      solve (div n 2L)
    else if rem n 3L = 0L then
      solve (mul 2L (div n 3L))
    else if rem n 5L = 0L then
      solve (mul 4L (div n 5L))
    else if n = 1L then
      -1
    else
      raise Not_found;;

let [t] = read_ints ();;
for _ = 1 to t do
  let [n] = read_ints () and a = read_int64s () in
  let open Int64 in
  let [c0; c1; c2] = List.(
      map
        (fun r -> fold_left (fun acc x -> if rem x 3L = r then acc + 1 else acc) 0 a)
        [0L; 1L; 2L]) in
  let r = c0 + (c1 + 2*c2) / 3 - (if c1 >= c2 then 0 else 1)
  in
  print_ints [r]
done;;

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let rec solve n =
  1 +
    let open Int64 in
    if rem n 2L = 0L then
      solve (div n 2L)
    else if rem n 3L = 0L then
      solve (mul 2L (div n 3L))
    else if rem n 5L = 0L then
      solve (mul 4L (div n 5L))
    else if n = 1L then
      -1
    else
      raise Not_found;;

let [t] = read_ints ();;
for _ = 1 to t do
  let [n] = read_ints () in
  let open Int64 in
  print_int64s [
      div
        (read_int64s ()
         |> List.map (fun x -> succ (rem (pred x) 3L))
         |> List.fold_left add 0L)
        3L
    ]
done;;

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let [t] = read_ints ();;
for _ = 1 to t do
  let [n] = read_ints () and a = read_ints () in
  let [c0; c1; c2] = List.(
      map
        (fun r -> fold_left (fun acc x -> if x mod 3 = r then acc + 1 else acc) 0 a)
        [0; 1; 2]) in
  let r =
    if c1 > c2 then
      c0 + c2 + c1 / 3
    else
      c0 + c1 + c2 / 3
  in
  print_ints [r]
done;;