You are given a program that consists of $$$n$$$ instructions. Initially a single variable $$$x$$$ is assigned to $$$0$$$. Afterwards, the instructions are of two types:   increase $$$x$$$ by $$$1$$$;  decrease $$$x$$$ by $$$1$$$. You are given $$$m$$$ queries of the following format:   query $$$l$$$ $$$r$$$ — how many distinct values is $$$x$$$ assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the description of $$$t$$$ testcases follows. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of $$$n$$$ characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next $$$m$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the description of the query. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print $$$m$$$ integers — for each query $$$l$$$, $$$r$$$ print the number of distinct values variable $$$x$$$ is assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order.

NoteThe instructions that remain for each query of the first testcase are:   empty program — $$$x$$$ was only equal to $$$0$$$;  "-" — $$$x$$$ had values $$$0$$$ and $$$-1$$$;  "---+" — $$$x$$$ had values $$$0$$$, $$$-1$$$, $$$-2$$$, $$$-3$$$, $$$-2$$$ — there are $$$4$$$ distinct values among them;  "+--+--+" — the distinct values are $$$1$$$, $$$0$$$, $$$-1$$$, $$$-2$$$.

open Str
open Big_int
open Num

let multitest = true

module Int = struct
   type t = int
   let compare = compare
 end

module Ints = Set.Make(Int)

module Shortcuts = struct
  let loop ?(from = 0) n f = for i = from to n - 1 do f i; done
  let rep ?(too = 0) n f = for i = n-1 downto too do f i; done

end

module Helper = struct
  open Shortcuts

  let read_int ~endl () =
    if endl then Scanf.scanf "%d\n" (fun x -> x)
    else Scanf.scanf "%d " (fun x -> x)

  let read_s () = Scanf.scanf "%s\n" (fun x -> x)

  type _ t =
    | I : int t
    | S : string t
    | II : (int * int) t
    | A : int -> int array t

  let read x =
    let rec aux : type a. bool -> a t -> a  = fun endl -> function
      | I -> read_int ~endl ()
      | S -> read_s ()
      | II ->
        let l = aux false I in
        let r = aux true I in
        l, r
      | A n ->
        let a = Array.make n 0 in
        loop (n-1) (fun i -> a.(i) <- aux false I);
        a.(n-1) <- aux true I;
        a
    in
    aux true x

end

module Ext = struct
  module List = struct
    let rec make n x =
      if (n <= 0) then []
      else x :: make (n-1) x

  end

end

module Alg = struct
  let rec gcd x y =
    if y <> 0 then (gcd y (x mod y))
    else (abs x)

  let lcm x y =
    if x = 0 || y = 0 then 0
    else abs (x * y) / (gcd x y)

end

let solve _ =
  let open Shortcuts in
  let open Helper in
  let open Printf in
  let open Ext in
  let open Alg in
  (* ***** Solution code here ***** *)
  let n, d = read II in
  let s = read S in
  let pref = Array.make (n + 1) (0,0,0) in
  let x = ref 0 in
  let pmin = ref 0 in
  let pmax = ref 0 in
  loop n (fun i ->
      if String.get s i = '-' then begin
        decr x;
        if !x < !pmin then pmin := !x
      end else begin
        incr x;
        if !pmax < !x then pmax := !x
      end;
      pref.(i+1) <- (!pmin, !x, !pmax)
    );
  let suf = Array.make (n+1) (0,0,0) in
  let x = ref 0 in
  let smin = ref 0 in
  let smax = ref 0 in
  loop (n - 1) (fun i ->
      if String.get s (n-i-1) = '+' then begin
        decr x;
        if !x < !smin then smin := !x
      end else begin
        incr x;
        if !smax < !x then smax := !x
      end;
      suf.(n-1-i) <- (!smin, !x, !smax)
    );
  loop d (fun i ->
      let l,r = read II in
      let p_min, p_last, p_max = pref.(l-1) in
      let s_min, s_first, s_max = suf.(r) in
      printf "%d\n" (max p_max (p_last + s_max - s_first) - min p_min (p_last + s_min - s_first) + 1);
    );
  (* ***** ******************* ***** *)
;;

let () =
  let open Helper in
  let open Shortcuts in
  let t = if multitest then read I else 1 in
  loop t solve;;


Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 > 19.

The first line contains an integer n (1 ≤ n ≤ 30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.

Print the single number — the number of the winning squares.

NoteIn the first example two upper squares are winning.In the third example three left squares in the both middle rows are winning:5 7 8 49 5 3 21 6 6 49 5 7 3

open Scanf
open Printf

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

let main () =
  let n : int = read_int () in
  let cols = Array.make n 0 in
  let rows = Array.make n 0 in
  let rec compute i j =
    let num = read_int () in
    Array.set cols j ((Array.get cols j)+num);
    Array.set rows i ((Array.get rows i)+num);
    match i, j with
      | 0, 0 -> ()
      | _, 0 -> compute (i-1) (n-1)
      | _, _ -> compute i (j-1)
  in

  compute (n-1) (n-1);

  let total =
    Array.fold_left (fun total i ->
      Array.fold_left (fun total j -> if (i > j) then total+1 else total)
        total
        rows)
      0
      cols
  in
  print_int total

let () = main ()

(*
  let rec compute i =
    let line = read_line () in
    let nums = Str.split (Str.regexp "\b") line in
    ignore (List.fold_left (fun j s ->
      let num = int_of_string s in
      Array.set cols j ((Array.get cols j)+num);
      Array.set rows i ((Array.get rows i)+num);
      j-1
    ) (n-1) nums);
    if i == 0
    then ()
    else compute (i-1)
  in
*)


There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then:  move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$.  move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$.  move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$.  move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$.  move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$.  move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers:  $$$a$$$ — the total size of all sweets eaten by Alice during the game;  $$$b$$$ — the total size of all sweets eaten by Bob during the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\cdot10^5$$$.

For each set of input data print three integers — the number of moves in the game and the required values $$$a$$$ and $$$b$$$.

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

open Printf

let init (x : int) (f : int -> 'a) : 'a list =
  let rec build k =
    if k = x then []
    else (f k) :: build (k + 1) in
  build 0
;;

let run () =
  let n = scan_int () in
  let a = Array.init n (fun _x -> scan_int ()) in
  let posA = ref 0 and posB = ref (n-1) in
  let totA = ref 0 and totB = ref 0 in
  let prv = ref 0 and now = ref 0 in
  let turn = ref 0 and totturn = ref 0 in
  while !posA <= !posB do
    if !turn = 0 then begin
      now  := !now  + a.(!posA);
      totA := !totA + a.(!posA);
      posA := !posA + 1
    end
    else begin
      now  := !now  + a.(!posB);
      totB := !totB + a.(!posB);
      posB := !posB - 1
    end;
    if !now > !prv then begin
      prv := !now;
      now := 0;
      turn := 1 - !turn;
      totturn := !totturn + 1
    end
  done;
  if !now > 0 then incr totturn;
  let lst = [!totturn; !totA; !totB] in
  List.iter (printf "%d ") lst;
  print_endline ""
;;

let () =
  let t = scan_int () in
  for i = 1 to t do
    run ()
  done
;;

(* Codeforces 1352 D Alice, Bob and Candies comp   *)

(* 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;;

(* ============= above library below custom ========== *)

let rec alice ia sma ib smb lastbob nmov v =
	let rec eat i eaten =
		(* let _ = Printf.printf "al eat i eaten = %d %d\n" i eaten in *)
		if eaten > lastbob then (i, eaten)
		else if i > ib then (i, eaten)
		else
			let eaten = eaten + v.(i) in
			let i = i + 1 in
			eat i eaten in
	let idx,aeat = eat ia 0 in
	let sma = sma + aeat in
  let nmov = nmov + 1 in
	if idx > ib then (nmov, sma, smb)
	else
	bob idx sma ib smb aeat nmov v

and

bob ia sma ib smb lastalice nmov v =
    let rec eat i eaten =
        (* let _ = Printf.printf "bo eat i eaten = %d %d\n" i eaten in *)
        if eaten > lastalice then (i, eaten)
        else if i < ia then (i, eaten)
        else
            let eaten = eaten + v.(i) in
            let i = i - 1 in
            eat i eaten in
    let idx,beat = eat ib 0 in
    let smb = smb + beat in
    let nmov = nmov + 1 in
    if idx < ia then (nmov, sma, smb)
    else
    alice ia sma idx smb beat nmov v;;

let do_one () =
    let n = gr () in
    let a = readlist n [] in
		let a = (List.rev a) in
		let va = Array.of_list a in
		let nm,ca,cb = alice 0 0 (n-1) 0 0 0 va in
  	Printf.printf "%d %d %d\n" nm ca cb;;

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

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

main();;


Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.

The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times.

Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.

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

let rec ind i t=if t.[i]=' ' then i else ind (i+1) t;;
let i=ind 0 s;;

let s1=String.sub s 0 i;;
let s2=String.sub s (i+1) (String.length(s)-i-1);;

let a=float_of_string(s1);;
let d=float_of_string(s2);;

let n=read_int();;

let frac b=b-.float_of_int(int_of_float(b));;

let bop b c=
print_float b;
print_string " ";
print_float c;
print_newline();;

let m=ref 0.;;

for i=1 to n do
   m:= !m+.d;
   let p=frac( !m/.(4.0*.a)) in
      if p<0.25 then bop (p*.4.0*.a) 0.0
      else if p<0.5 then bop a ((p-.0.25)*.4.0*.a)
      else if p<0.75 then bop (a-.(p-.0.5)*.4.0*.a) a
      else bop 0.0 (a-.(p-.0.75)*.4.0*.a);
      m:=(p*.4.0*.a)
done;;

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

let a = Scanf.scanf "%f " (fun x -> x);;
let d = Scanf.scanf "%f\n" (fun x -> x);;
let n = Scanf.scanf "%d" (fun x -> x);;

let distance = ref 0.;;

let modulo a b = a -. b *. floor (a /. b);;

for i=1 to n do
  distance := modulo (!distance +. d) (4.*.a);
  match int_of_float (!distance /. a) with
  | 0 -> print_float !distance;
         print_string " ";
         print_float 0.;
         print_string "\n"
  | 1 -> print_float a;
         print_string " ";
         print_float (!distance -. a);
         print_string "\n"
  | 2 -> print_float (3.*.a -. !distance);
         print_string " ";
         print_float a;
         print_string "\n"
  | 3 -> print_float 0.;
         print_string " ";
         print_float (4.*.a -. !distance);
         print_string "\n"
  | _ -> failwith "Erreur !!"
done;

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

let rec ind i t=if t.[i]=' ' then i else ind (i+1) t;;
let i=ind 0 s;;

let s1=String.sub s 0 i;;
let s2=String.sub s (i+1) (String.length(s)-i-1);;

let a=float_of_string(s1);;
let d=float_of_string(s2);;

let n=read_int();;

let frac b=b-.float_of_int(int_of_float(b));;

let bop b c=
print_float b;
print_string " ";
print_float c;
print_newline();;

for i=1 to n do
   let m=float_of_int(i)*.d in
      let p=frac(m/.(4.0*.a)) in
         if p<0.25 then bop (p*.4.0*.a) 0.0
         else if p<0.5 then bop a ((p-.0.25)*.4.0*.a)
         else if p<0.75 then bop (a-.(p-.0.5)*.4.0*.a) a
         else bop 0.0 (a-.(p-.0.75)*.4.0*.a)
done;;


In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely.Lesha knows that today he can study for at most $$$a$$$ hours, and he will have $$$b$$$ hours to study tomorrow. Note that it is possible that on his planet there are more hours in a day than on Earth. Lesha knows that the quality of his knowledge will only depend on the number of lecture notes he will read. He has access to an infinite number of notes that are enumerated with positive integers, but he knows that he can read the first note in one hour, the second note in two hours and so on. In other words, Lesha can read the note with number $$$k$$$ in $$$k$$$ hours. Lesha can read the notes in arbitrary order, however, he can't start reading a note in the first day and finish its reading in the second day.Thus, the student has to fully read several lecture notes today, spending at most $$$a$$$ hours in total, and fully read several lecture notes tomorrow, spending at most $$$b$$$ hours in total. What is the maximum number of notes Lesha can read in the remaining time? Which notes should he read in the first day, and which — in the second?

The only line of input contains two integers $$$a$$$ and $$$b$$$ ($$$0 \leq a, b \leq 10^{9}$$$) — the number of hours Lesha has today and the number of hours Lesha has tomorrow.

In the first line print a single integer $$$n$$$ ($$$0 \leq n \leq a$$$) — the number of lecture notes Lesha has to read in the first day. In the second line print $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \leq p_i \leq a$$$), the sum of all $$$p_i$$$ should not exceed $$$a$$$. In the third line print a single integer $$$m$$$ ($$$0 \leq m \leq b$$$) — the number of lecture notes Lesha has to read in the second day. In the fourth line print $$$m$$$ distinct integers $$$q_1, q_2, \ldots, q_m$$$ ($$$1 \leq q_i \leq b$$$), the sum of all $$$q_i$$$ should not exceed $$$b$$$. All integers $$$p_i$$$ and $$$q_i$$$ should be distinct. The sum $$$n + m$$$ should be largest possible.

NoteIn the first example Lesha can read the third note in $$$3$$$ hours in the first day, and the first and the second notes in one and two hours correspondingly in the second day, spending $$$3$$$ hours as well. Note that Lesha can make it the other way round, reading the first and the second notes in the first day and the third note in the second day.In the second example Lesha should read the third and the sixth notes in the first day, spending $$$9$$$ hours in total. In the second day Lesha should read the first, second fourth and fifth notes, spending $$$12$$$ hours in total.

open Printf open Scanf
module Lib = struct
	let i32,i64,ist = Int64.(to_int,of_int,to_string)
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
	let labs = Int64.abs
	let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
	let (+=) r v = r := !r + v
	let (-=) r v = r := !r - v
	let ( *= ) r v = r := !r * v
	let (/=) r v = r := !r / v
	let (%=) r v = r := !r % v
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* io *)
	let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
	(* utils *)
	let alen a = i64 @@ Array.length a
	let llen l = i64 @@ List.length l
	let string_of_list ?(separator=" ") f ls =
		ls |> List.map f |> String.concat separator
	let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
	let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
	let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	(* imperative *)
	let rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done
	let repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done
	let repm f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m
	let repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done
	let repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done
	let repim f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m
	(* debug *)
	(* let dump_list f ls = ls |> List.map f |> String.concat " " |> print_endline
	let dump_array f a = a |> Array.to_list |> dump_list f *)
	let dump_list f ls = string_of_list f ls |> print_endline
end open Lib

let binary_search ng ok f =
	let rec f0 ng ok =
		if labs (ok - ng) <= 1L then ok
		else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
	in let d = if ng < ok then 1L else -1L
	in f0 (ng-1L*d) (ok+1L*d)

(* let a,b = get_2_i64 0
let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
let rec f0 ra rb la lb = function
	| 0L -> (la,lb)
	| v ->
		if ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)
		else f0 ra (rb-v) la (v::lb) (v-1L)
let (la,lb) = f0 a b [] [] sum
let () =
	printf "%d\n" @@ List.length la;
	dump_list Int64.to_string la;
	printf "%d\n" @@ List.length lb;
	dump_list Int64.to_string lb; *)

let ist = Int64.to_string
let () =
	let a,b = get_2_i64 0 in
	let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
	in
	(* printf "%Ld\n" sum; *)
	let d1,d2 = ref [],ref [] in
	let r1,r2 = ref a,ref b in
	(* rep 1L sum (fun i ->
		let i = sum - i + 1L in
		if !ra > !rb then (
			la := i::!la; ra -= i;
		) else (
			lb := i::!lb; rb -= i;
		)
	); *)
	let i = ref sum in
	while !i >= 1L do
		if !r2 <= !r1 then (
			r1 := !r1 - !i;
			d1 := !i :: !d1
		) else (
			r2 := !r2 - !i;
			d2 := !i :: !d2
		);
		i := !i - 1L
	done;
	printf "%d\n" @@ List.length !d1;
	dump_list ist !d1;
	printf "%d\n" @@ List.length !d2;
	dump_list ist !d2;

let (++),(--),labs,(//),( ** ),i64,ist = Int64.(add,sub,abs,div,mul,of_int,to_string)
let binary_search ng ok f =
	let rec f0 ng ok =
		if labs (ok -- ng) <= 1L then ok
		else let mid = ng ++ (ok -- ng) // 2L in if f mid then f0 ng mid else f0 mid ok
	in let d = if ng < ok then 1L else -1L
	in f0 (ng--d) (ok++d)
let dump_list ls = ls
	|> List.map ist
	|> String.concat " "
	|> print_endline
let () = Scanf.scanf " %Ld %Ld" @@ fun a b ->
	let sum = binary_search 2000000018L 0L (fun v -> v**(v++1L)//2L <= a++b)
	in
	let d1,d2 = ref [], ref [] in
	let a = ref a in
	let i = ref sum in
	while !i >= 1L do
		if !i <= !a then (
			a := !a -- !i;
			d1 := !i :: !d1
		) else d2 := !i :: !d2;
		i := !i -- 1L
	done;
	Printf.printf "%d\n" @@ List.length !d1;
	dump_list !d1;
	Printf.printf "%d\n" @@ List.length !d2;
	dump_list !d2;

open Printf open Scanf
module Lib = struct
	let i32,i64 = Int64.to_int,Int64.of_int
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
	let labs = Int64.abs
	let (+),(-),( * ),(/),(mod),(%) = Int64.add,Int64.sub,Int64.mul,Int64.div,Int64.rem,Int64.rem
	let (+=) r v = r := !r + v
	let (-=) r v = r := !r - v
	let ( *= ) r v = r := !r * v
	let (/=) r v = r := !r / v
	let (%=) r v = r := !r % v
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* io *)
	let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
	(* utils *)
	let alen a = i64 @@ Array.length a
	let llen l = i64 @@ List.length l
	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 string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
	let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
	let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	(* imperative *)
	let rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done
	let repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done
	let repm f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m
	let repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done
	let repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done
	let repim f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m
	(* debug *)
	let dump_list f ls = string_of_list f ls |> print_endline
	let dump_array f a = string_of_array f a |> print_endline
end open Lib

let binary_search ng ok f =
	let rec f0 ng ok =
		if labs (ok - ng) <= 1L then ok
		else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
	in let d = if ng < ok then 1L else -1L
	in f0 (ng-1L*d) (ok+1L*d)

(* let a,b = get_2_i64 0
let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
let rec f0 ra rb la lb = function
	| 0L -> (la,lb)
	| v ->
		if ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)
		else f0 ra (rb-v) la (v::lb) (v-1L)
let (la,lb) = f0 a b [] [] sum
let () =
	printf "%d\n" @@ List.length la;
	dump_list Int64.to_string la;
	printf "%d\n" @@ List.length lb;
	dump_list Int64.to_string lb; *)

let ist = Int64.to_string
let dump_list ls = ls
	|> List.map ist
	|> String.concat " "
	|> print_endline
let () =
	let a,b = get_2_i64 0 in
	let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
	in
	(* printf "%Ld\n" sum; *)
	let d1,d2 = ref [],ref [] in
	let r1,r2 = ref a,ref b in
	(* rep 1L sum (fun i ->
		let i = sum - i + 1L in
		if !ra > !rb then (
			la := i::!la; ra -= i;
		) else (
			lb := i::!lb; rb -= i;
		)
	); *)
	let i = ref sum in
	while !i >= 1L do
		if !r2 <= !r1 then (
			r1 := !r1 - !i;
			d1 := !i :: !d1
		) else (
			r2 := !r2 - !i;
			d2 := !i :: !d2
		);
		i := !i - 1L
	done;
	printf "%d\n" @@ List.length !d1;
	dump_list !d1;
	printf "%d\n" @@ List.length !d2;
	dump_list !d2;

open Printf open Scanf
module Lib = struct
	let i32,i64,ist = Int64.(to_int,of_int,to_string)
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
	let labs = Int64.abs
	let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
	let (+=) r v = r := !r + v
	let (-=) r v = r := !r - v
	let ( *= ) r v = r := !r * v
	let (/=) r v = r := !r / v
	let (%=) r v = r := !r % v
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* io *)
	let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
	(* utils *)
	let alen a = i64 @@ Array.length a
	let llen l = i64 @@ List.length l
	let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
	let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
	let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
	let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	(* imperative *)
	let rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done
	let repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done
	let repm f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m
	let repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done
	let repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done
	let repim f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m
	(* debug *)
	let dump_list f ls = string_of_list f ls |> print_endline
	let dump_array f a = string_of_array f a |> print_endline
	let dump_list_test f ls = List.iter (fun v -> printf "%s " @@ f v) ls; print_newline ()
end open Lib

let binary_search ng ok f =
	let rec f0 ng ok =
		if labs (ok - ng) <= 1L then ok
		else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
	in let d = if ng < ok then 1L else -1L
	in f0 (ng-1L*d) (ok+1L*d)

(* let a,b = get_2_i64 0
let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
let rec f0 ra rb la lb = function
	| 0L -> (la,lb)
	| v ->
		if ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)
		else f0 ra (rb-v) la (v::lb) (v-1L)
let (la,lb) = f0 a b [] [] sum
let () =
	printf "%d\n" @@ List.length la;
	dump_list Int64.to_string la;
	printf "%d\n" @@ List.length lb;
	dump_list Int64.to_string lb; *)

let ist = Int64.to_string
let () =
	let a,b = get_2_i64 0 in
	let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
	in
	(* printf "%Ld\n" sum; *)
	let d1,d2 = ref [],ref [] in
	let r1,r2 = ref a,ref b in
	(* rep 1L sum (fun i ->
		let i = sum - i + 1L in
		if !ra > !rb then (
			la := i::!la; ra -= i;
		) else (
			lb := i::!lb; rb -= i;
		)
	); *)
	let i = ref sum in
	while !i >= 1L do
		if !r2 <= !r1 then (
			r1 := !r1 - !i;
			d1 := !i :: !d1
		) else (
			r2 := !r2 - !i;
			d2 := !i :: !d2
		);
		i := !i - 1L
	done;
	printf "%d\n" @@ List.length !d1;
	dump_list_test ist !d1;
	printf "%d\n" @@ List.length !d2;
	dump_list_test ist !d2;

open Printf open Scanf
module Lib = struct
	let i32,i64,ist = Int64.(to_int,of_int,to_string)
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
	let labs = Int64.abs
	let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
	let (+=) r v = r := !r + v
	let (-=) r v = r := !r - v
	let ( *= ) r v = r := !r * v
	let (/=) r v = r := !r / v
	let (%=) r v = r := !r % v
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* io *)
	let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
	(* utils *)
	let alen a = i64 @@ Array.length a
	let llen l = i64 @@ List.length l
	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 string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
	let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
	let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	(* imperative *)
	let rep f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done
	let repf f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done
	let repm f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m
	let repi f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done
	let repif f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done
	let repim f t m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m
	(* debug *)
	let dump_list_slow f ls = string_of_list f ls |> print_endline
	let dump_array_slow f a = string_of_array f a |> print_endline
	let dump_i64_list ls = ls
		|> List.map ist
end open Lib

let binary_search ng ok f =
	let rec f0 ng ok =
		if labs (ok - ng) <= 1L then ok
		else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
	in let d = if ng < ok then 1L else -1L
	in f0 (ng-1L*d) (ok+1L*d)

(* let a,b = get_2_i64 0
let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
let rec f0 ra rb la lb = function
	| 0L -> (la,lb)
	| v ->
		if ra > rb then f0 (ra-v) rb (v::la) lb (v-1L)
		else f0 ra (rb-v) la (v::lb) (v-1L)
let (la,lb) = f0 a b [] [] sum
let () =
	printf "%d\n" @@ List.length la;
	dump_list Int64.to_string la;
	printf "%d\n" @@ List.length lb;
	dump_list Int64.to_string lb; *)

let ist = Int64.to_string
let dump_list f ls = ls
	|> List.map f
	|> String.concat " "
	|> print_endline
let () =
	let a,b = get_2_i64 0 in
	let sum = binary_search (2000000018L) 0L (fun v -> v*(v+1L)/2L <= a+b)
	in
	(* printf "%Ld\n" sum; *)
	let d1,d2 = ref [],ref [] in
	let r1,r2 = ref a,ref b in
	(* rep 1L sum (fun i ->
		let i = sum - i + 1L in
		if !ra > !rb then (
			la := i::!la; ra -= i;
		) else (
			lb := i::!lb; rb -= i;
		)
	); *)
	let i = ref sum in
	while !i >= 1L do
		if !r2 <= !r1 then (
			r1 := !r1 - !i;
			d1 := !i :: !d1
		) else (
			r2 := !r2 - !i;
			d2 := !i :: !d2
		);
		i := !i - 1L
	done;
	printf "%d\n" @@ List.length !d1;
	dump_list ist !d1;
	printf "%d\n" @@ List.length !d2;
	dump_list ist !d2;

let (++),(--),labs,(//),( ** ),i64,ist = Int64.(add,sub,abs,div,mul,of_int,to_string)
let binary_search ng ok f =
	let rec f0 ng ok =
		if labs (ok -- ng) <= 1L then ok
		else let mid = ng ++ (ok -- ng) // 2L in if f mid then f0 ng mid else f0 mid ok
	in let d = if ng < ok then 1L else -1L
	in f0 (ng--d) (ok++d)
let dump_list ls = ls
	|> List.map ist
	|> String.concat " "
	|> print_endline
let () = Scanf.scanf " %Ld %Ld" @@ fun a b ->
	let sum = binary_search 2000000018L 0L (fun v -> v**(v++1L)//2L <= a++b)
	in
	let d1,d2 = ref [], ref [] in
	let r1,r2 = ref a, ref b in
	let i = ref sum in
	while !i >= 1L do
		if !r2 <= !r1 then (
			r1 := !r1 -- !i;
			d1 := !i :: !d1
		) else (
			r2 := !r2 -- !i;
			d2 := !i :: !d2
		);
		i := !i -- 1L
	done;
	Printf.printf "%d\n" @@ List.length !d1;
	dump_list !d1;
	Printf.printf "%d\n" @@ List.length !d2;
	dump_list !d2;


Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer.Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that.

The first line contains integer n (1 ≤ n ≤ 2·105) — the number of throws of the first team. Then follow n integer numbers — the distances of throws ai (1 ≤ ai ≤ 2·109).  Then follows number m (1 ≤ m ≤ 2·105) — the number of the throws of the second team. Then follow m integer numbers — the distances of throws of bi (1 ≤ bi ≤ 2·109).

Print two numbers in the format a:b — the score that is possible considering the problem conditions where the result of subtraction a - b is maximum. If there are several such scores, find the one in which number a is maximum.

(* Codeforces 493C VasiaBasketball *)

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

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

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

let mcomp a b = a-b;;

(* count elements less than d using binary search *)
let rec countd a i0 i1 d =
	if i1 = i0+1 then
		begin
			(*printarri a;
			print_string " d = "; print_int d;
			print_string " i0 = "; print_int i0;
			print_string " i1 = "; print_int i1;
			print_string " cnt = ";*)
			let cnt = 2*i1 + 3*((length a)-i1) + (if a.(i0)>d then 1 else 0) in
			  cnt
		end
	else
		let i = (i0 + i1)/2 in
		if a.(i)>d then countd a i0 i d
		else countd a i i1 d;;

let diff aa bb d =
	let da = countd aa 0 (length aa) d in
	let db = countd bb 0 (length bb) d in
	(da, db,d);;

let mprcomp pra prb =
	let (a0,a1,d) = pra in
	let (b0,b1,d) = prb in
	let da = a0-a1 in
	let db = b0-b1 in
	if da-db != 0 then db - da
	else  b0 - a0;;

let main () =
	let n = gr () in
	let a = readlist n [] in
	let aa = Array.of_list (List.sort mcomp a) in
	let m = gr() in
	let b = readlist m [] in
	let bb = Array.of_list (List.sort mcomp b) in
	let ab = (0 :: (a @ b)) in
	let abpr = List.map (fun d -> diff aa bb d) ab in
	let abprso = List.sort mprcomp abpr in
	let (x,y,d) = List.hd abprso in
	begin
	  print_int x;
		print_string ":";
		print_int y;
		(*print_string " d= "; print_int d*)
	end;;

main();;


Omkar has received a message from Anton saying "Your story for problem A is confusing. Just make a formal statement." Because of this, Omkar gives you an array $$$a = [a_1, a_2, \ldots, a_n]$$$ of $$$n$$$ distinct integers. An array $$$b = [b_1, b_2, \ldots, b_k]$$$ is called nice if for any two distinct elements $$$b_i, b_j$$$ of $$$b$$$, $$$|b_i-b_j|$$$ appears in $$$b$$$ at least once. In addition, all elements in $$$b$$$ must be distinct. Can you add several (maybe, $$$0$$$) integers to $$$a$$$ to create a nice array $$$b$$$ of size at most $$$300$$$? If $$$a$$$ is already nice, you don't have to add any elements.For example, array $$$[3, 6, 9]$$$ is nice, as $$$|6-3|=|9-6| = 3$$$, which appears in the array, and $$$|9-3| = 6$$$, which appears in the array, while array $$$[4, 2, 0, 6, 9]$$$ is not nice, as $$$|9-4| = 5$$$ is not present in the array.For integers $$$x$$$ and $$$y$$$, $$$|x-y| = x-y$$$ if $$$x > y$$$ and $$$|x-y| = y-x$$$ otherwise.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \leq t \leq 50$$$), the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \cdots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$) — the elements of the array $$$a$$$.

For each test case, output one line containing YES if Omkar can create a nice array $$$b$$$ by adding elements to $$$a$$$ and NO otherwise. The case of each letter does not matter, so yEs and nO will also be accepted. If the first line is YES, output a second line containing a single integer $$$k$$$ ($$$n \leq k \leq 300$$$).  Then output one line containing $$$k$$$ distinct integers $$$b_1, b_2, \cdots, b_k$$$ ($$$-10^9 \leq b_i \leq 10^9$$$), the elements of the nice array $$$b$$$. $$$b_1, b_2, \cdots, b_k$$$ can be in any order. For each $$$a_i$$$ in $$$a$$$, $$$a_i$$$ must appear at least once in $$$b$$$. It can be proved that if Omkar can create such an array $$$b$$$, then he can also do so in a way that satisfies the above constraints. If multiple solutions exist, you can print any.

open Printf
open Scanf

let rec gcd a b = if a=0 then b else gcd (b mod a) a
let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let a = Array.init n read_int in
    Array.sort compare a;
    if a.(0) < 0 then printf "NO\n" else (
      let g = fold 0 (n-1) (fun i ac -> gcd ac a.(i)) 0 in
      let allg = fold 1 (a.(n-1)/g) (fun i ac -> (i*g)::ac) (Array.to_list a) in
      let ans = List.sort_uniq compare allg in
      printf "YES\n";
      printf "%d\n" (List.length ans);
      List.iter (printf "%d ") ans;
      print_newline()
    )
  done


You are given a digital clock with $$$n$$$ digits. Each digit shows an integer from $$$0$$$ to $$$9$$$, so the whole clock shows an integer from $$$0$$$ to $$$10^n-1$$$. The clock will show leading zeroes if the number is smaller than $$$10^{n-1}$$$.You want the clock to show $$$0$$$ with as few operations as possible. In an operation, you can do one of the following:   decrease the number on the clock by $$$1$$$, or  swap two digits (you can choose which digits to swap, and they don't have to be adjacent). Your task is to determine the minimum number of operations needed to make the clock show $$$0$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — number of digits on the clock. The second line of each test case contains a string of $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_1, s_2, \ldots, s_n \le 9$$$) — the number on the clock. Note: If the number is smaller than $$$10^{n-1}$$$ the clock will show leading zeroes.

For each test case, print one integer: the minimum number of operations needed to make the clock show $$$0$$$.

NoteIn the first example, it's optimal to just decrease the number $$$7$$$ times.In the second example, we can first swap the first and last position and then decrease the number by $$$1$$$.In the third example, the clock already shows $$$0$$$, so we don't have to perform any operations.

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 l2n c = (int_of_char c) - (int_of_char '0')

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 d = read_int() in
    let s = read_string() in
    let answer = sum 0 (d-1) (fun i ->
      let x = l2n s.[i] in
      (if i = (d-1) || x=0 then 0 else 1) + x
    ) in
    printf "%d\n" answer
  done


Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

The first line contains one integer n — the number of vertices in the tree (3 ≤ n ≤ 1 000). Each of the next n - 1 lines contains one integer pi (1 ≤ i ≤ n - 1) — the index of the parent of the i + 1-th vertex (1 ≤ pi ≤ i). Vertex 1 is the root. It's guaranteed that the root has at least 2 children.

Print "Yes" if the tree is a spruce and "No" otherwise.

NoteThe first example:The second example:It is not a spruce, because the non-leaf vertex 1 has only 2 leaf children.The third example:

type spruce = Leaf of int
            | Node of spruce list

let rec split num str =
  match str with
  | "" -> []
  | s ->
    let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in
    beg :: (split num rest)

let rec returnIntList strList one =
  match strList with
  | h :: t -> if (compare h " " == 0 || compare h "\n" == 0) then
    (int_of_string one) ::(returnIntList t "")
    else returnIntList t (one^h)
  | _ -> (int_of_string one) :: []

let splitToList line =
  let lineList = split 1 line in
  returnIntList lineList ""

let rec makePairList numList num =
  match numList with
  | h :: t -> (h, num) :: (makePairList t (num+1))
  | _ -> []

let rec makeNode pairList num =
  match pairList with
  | (a,b) :: t ->
    if (num == a) then
      Node (Leaf(b) :: (makeNode t b)) :: (makeNode t num)
    else makeNode t num
  | _ -> []

let rec countLeaf node =
  match node with
  | Node(Leaf(a) :: []) ::t -> 1 + countLeaf t
  | Node(Leaf(a) :: t) :: tail -> countLeaf tail
  | _ -> 0

let rec checkNotAllNode node =
  match node with
  | Node (Leaf(b) :: []) :: tail -> true
  | Node (Leaf(a) :: t) :: [] -> false
  | Node (Leaf(a) :: t) :: tail -> checkNotAllNode tail
  | _ -> true

let rec countSpruce spruce =
  match spruce with
  | Node (Leaf(a) :: t) :: tail ->
    let num = countLeaf t in
    if (num >= 3 || num == 0) && (checkNotAllNode t) == true then
      countSpruce t && countSpruce tail
    else false
  | _ -> true

let printLeaf leaf =
  match leaf with
  | Leaf(a) -> print_string "[Leaf : ";print_int a; print_string "]"
  | _ -> print_string " "

let rec printNode node =
  match node with
  | Node (h :: t) :: tail ->
    print_string "[Node : ";printLeaf h; printNode t;print_string"]";
    printNode tail
  | _ -> print_string " "

let n = read_int()
let rec numList k =
  if (k < n) then
    let m = read_int() in
    m :: (numList (k+1))
  else []

let pairList = makePairList (numList 1) 2

let newSpruce =
  Node (Leaf(1) :: (makeNode pairList 1)) :: []

let _ =
  if (countSpruce newSpruce) then print_string "Yes"
  else print_string "No"

(* Codeforces 913 B Christmas Spruce *)

(* 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;;

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

let rec revert l acc = match l with
	| [] -> acc
	| h :: t ->
			let aa = h :: acc in
			revert t aa;;

let rec setna na li idx =
	if idx = 0 then
		begin
			na.(0) <- [];
			setna na li (idx + 1)
		end
	else
		match li with
		| [] -> ()
		| h :: t ->
				begin
					na.(h - 1) <- idx :: na.(h - 1);
					setna na t (idx + 1)
				end;;

(* count elements of numa array with idndexes in li *)
let rec arr_count numa li = match li with
	| [] -> 0
	| h :: t -> numa.(h) + arr_count numa t;;

let is_leaf li = match li with
	| [] -> 1
	| _ -> 0;;

(* count lefes for current root, returns (isLeaf, good) *)
let check_node na is_leafa idx =
	(* let _ = begin
		print_string "\n check_node ";
		print_int idx;
	    print_string " na_idx ";
			printlisti na.(idx)
	 end in *)
	let lcnt = arr_count is_leafa na.(idx) in
	if is_leafa.(idx) = 0 then lcnt >= 3
	else true;;

let rec all_true idx f nmax =
	if idx < nmax then (f idx) && all_true (idx + 1) f nmax
	else true;;

let main() =
	let n = gr() in
	let a = readlist (n - 1) [] in
	let ar = revert a [] in
  (* let _ = printlisti ar in *)
	let na = Array.make n [] in
	let _ = setna na ar 0 in
	let is_leafa = Array.map is_leaf na in
	begin
		(*print_string "\n is_leafa: ";
		printarri is_leafa;*)
		let simp_check i = check_node na is_leafa i in
		let ok = all_true 0 simp_check n in
		if ok then print_string "Yes"
		else print_string "No"
	end;;

main();;

type spruce = Leaf of int
            | Node of spruce list

let rec split num str =
  match str with
  | "" -> []
  | s ->
    let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in
    beg :: (split num rest)

let rec returnIntList strList one =
  match strList with
  | h :: t -> if (compare h " " == 0 || compare h "\n" == 0) then
    (int_of_string one) ::(returnIntList t "")
    else returnIntList t (one^h)
  | _ -> (int_of_string one) :: []

let splitToList line =
  let lineList = split 1 line in
  returnIntList lineList ""

let rec makePairList numList num =
  match numList with
  | h :: t -> (h, num) :: (makePairList t (num+1))
  | _ -> []

let rec makeNode pairList num =
  match pairList with
  | (a,b) :: t ->
    if (num == a) then
      Node (Leaf(b) :: (makeNode t b)) :: (makeNode t num)
    else makeNode t num
  | _ -> []

let rec countLeaf node =
  match node with
  | Node(Leaf(a) :: []) ::t -> 1 + countLeaf t
  | Node(Leaf(a) :: t) :: tail -> countLeaf tail
  | _ -> 0

let rec checkNotAllNode node =
  match node with
  | Node (Leaf(b) :: []) :: tail -> true
  | Node (Leaf(a) :: t) :: [] -> false
  | Node (Leaf(a) :: t) :: tail -> checkNotAllNode tail
  | _ -> true

let rec countSpruce spruce =
  match spruce with
  | Node (Leaf(a) :: t) :: tail ->
    let num = countLeaf t in
    if (num == 3 || num == 0) && (checkNotAllNode t == true) then
      countSpruce t && countSpruce tail
    else false
  | _ -> true

let printLeaf leaf =
  match leaf with
  | Leaf(a) -> print_string "[Leaf : ";print_int a; print_string "]"
  | _ -> print_string " "

let rec printNode node =
  match node with
  | Node (h :: t) :: tail ->
    print_string "[Node : ";printLeaf h; printNode t;print_string"]";
    printNode tail
  | _ -> print_string " "

let n = read_int()
let rec numList k =
  if (k < n) then
    let m = read_int() in
    m :: (numList (k+1))
  else []

let pairList = makePairList (numList 1) 2

let newSpruce =
  Node (Leaf(1) :: (makeNode pairList 1)) :: []

let _ =
  if (countSpruce newSpruce) then print_string "Yes"
  else print_string "No"

type spruce = Leaf of int
            | Node of spruce list

let rec split num str =
  match str with
  | "" -> []
  | s ->
    let (beg, rest) = (String.sub str 0 num, String.sub str num(String.length str - num)) in
    beg :: (split num rest)

let rec returnIntList strList one =
  match strList with
  | h :: t -> if (compare h " " == 0 || compare h "\n" == 0) then
    (int_of_string one) ::(returnIntList t "")
    else returnIntList t (one^h)
  | _ -> (int_of_string one) :: []

let splitToList line =
  let lineList = split 1 line in
  returnIntList lineList ""

let rec makePairList numList num =
  match numList with
  | h :: t -> (h, num) :: (makePairList t (num+1))
  | _ -> []

let rec makeNode pairList num =
  match pairList with
  | (a,b) :: t ->
    if (num == a) then
      Node (Leaf(b) :: (makeNode t b)) :: (makeNode t num)
    else makeNode t num
  | _ -> []

let rec countLeaf node =
  match node with
  | Node(Leaf(a) :: []) ::t -> 1 + countLeaf t
  | Node(Leaf(a) :: t) :: tail -> countLeaf tail
  | _ -> 0

let rec countSpruce spruce =
  match spruce with
  | Node (Leaf(a) :: t) :: tail ->
    let num = countLeaf t in
    if (num == 3 || num == 0) then
      countSpruce t && countSpruce tail
    else false
  | _ -> true

let printLeaf leaf =
  match leaf with
  | Leaf(a) -> print_string "[Leaf : ";print_int a; print_string "]"
  | _ -> print_string " "

let rec printNode node =
  match node with
  | Node (h :: t) :: tail ->
    print_string "[Node : ";printLeaf h; printNode t;print_string"]";
    printNode tail
  | _ -> print_string " "

let n = read_int()
let rec numList k =
  if (k < n) then
    let m = read_int() in
    m :: (numList (k+1))
  else []

let pairList = makePairList (numList 1) 2

let newSpruce =
  Node (Leaf(1) :: (makeNode pairList 1)) :: []

let _ =
  if (countSpruce newSpruce) then print_string "Yes"
  else print_string "No"


There are some beautiful girls in Arpa’s land as mentioned before.Once Arpa came up with an obvious problem:Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that , where  is bitwise xor operation (see notes for explanation).  Immediately, Mehrdad discovered a terrible solution that nobody trusted. Now Arpa needs your help to implement the solution to that problem.

First line contains two integers n and x (1 ≤ n ≤ 105, 0 ≤ x ≤ 105) — the number of elements in the array and the integer x. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the elements of the array.

Print a single integer: the answer to the problem.

NoteIn the first sample there is only one pair of i = 1 and j = 2.  so the answer is 1.In the second sample the only two pairs are i = 3, j = 4 (since ) and i = 1, j = 5 (since ).A bitwise xor takes two bit integers of equal length and performs the logical xor operation on each pair of corresponding bits. The result in each position is 1 if only the first bit is 1 or only the second bit is 1, but will be 0 if both are 0 or both are 1. You can read more about bitwise xor operation here: https://en.wikipedia.org/wiki/Bitwise_operation#XOR.

open Printf
open Scanf

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

let long x = Int64.of_int x

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

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

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

  let get k = try Hashtbl.find h k with Not_found -> 0 in

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

  let answer = if x = 0 then (
    Hashtbl.fold (fun _ c ac -> let c = long c in ac ++ c**(c--1L)//2L) h 0L
  ) else (
    (sum 0 (n-1) (fun i -> long (get (x lxor a.(i))))) // 2L
  )
  in

  printf "%Ld\n" answer


Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.One day Valera counted the shortest distances from one of the graph vertices to all other ones and wrote them out in array d. Thus, element d[i] of the array shows the shortest distance from the vertex Valera chose to vertex number i.Then something irreparable terrible happened. Valera lost the initial graph. However, he still has the array d. Help him restore the lost graph.

The first line contains two space-separated integers n and k (1 ≤ k < n ≤ 105). Number n shows the number of vertices in the original graph. Number k shows that at most k edges were adjacent to each vertex in the original graph. The second line contains space-separated integers d[1], d[2], ..., d[n] (0 ≤ d[i] < n). Number d[i] shows the shortest distance from the vertex Valera chose to the vertex number i.

If Valera made a mistake in his notes and the required graph doesn't exist, print in the first line number -1. Otherwise, in the first line print integer m (0 ≤ m ≤ 106) — the number of edges in the found graph. In each of the next m lines print two space-separated integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi), denoting the edge that connects vertices with numbers ai and bi. The graph shouldn't contain self-loops and multiple edges. If there are multiple possible answers, print any of them.

let n = Scanf.scanf "%d " (fun x -> x);;
let k = Scanf.scanf "%d\n" (fun x -> x);;

let tab = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x));;

let liste = ref [];;

for i=0 to n-1 do
  liste := (tab.(i), i)::!liste;
done;

liste := List.sort (fun (x,_) -> fun (y,_) -> x - y) !liste;

let _,debut = List.hd !liste in
liste := List.tl !liste;

let en_cours = Queue.create () in
let arete = Array.make n [] in
let nb_arete = Array.make n 0 in
let res = ref 0 in

Queue.push debut en_cours;

while not (Queue.is_empty en_cours) do
  let actuel = Queue.pop en_cours in
  while (nb_arete.(actuel) < k)
      & (!liste <> [])
      & (tab.(snd (List.hd !liste)) = tab.(actuel) + 1) do
    let suivant = snd (List.hd !liste) in
    arete.(actuel) <- suivant::arete.(actuel);
    nb_arete.(actuel) <- 1 + nb_arete.(actuel);
    nb_arete.(suivant) <- 1 + nb_arete.(suivant);
    res := !res + 1;
    Queue.push suivant en_cours;
    liste := List.tl !liste;
  done;
done;

let tab2 = Array.make n 1000000000 in
tab2.(debut) <- 0;
Queue.push debut en_cours;

while not (Queue.is_empty en_cours) do
  let actuel = Queue.pop en_cours in
  List.iter (fun x -> if tab2.(x) = 1000000000 then begin
                        Queue.push x en_cours;
                        tab2.(x) <- tab2.(actuel) + 1
                      end) arete.(actuel);
done;

let valide = ref true in
for i=0 to n-1 do
  if tab.(i) <> tab2.(i)
    then valide := false;
done;

if !valide then begin
  print_int !res;
  print_newline ();
  for i=0 to n-1 do
    List.iter (fun x -> print_int (i+1);
                        print_string " ";
                        print_int (x+1);
                        print_newline()) arete.(i);
  done;
end else print_string "-1\n";

let n = Scanf.scanf "%d " (fun x -> x);;
let k = Scanf.scanf "%d\n" (fun x -> x);;

let tab = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x));;

let liste = ref [];;

for i=0 to n-1 do
  liste := (tab.(i), i)::!liste;
done;

liste := List.sort (fun (x,_) -> fun (y,_) -> x - y) !liste;

let _,debut = List.hd !liste in
liste := List.tl !liste;

let en_cours = Queue.create () in
let arete = Array.make n [] in
let nb_arete = Array.make n 0 in
let res = ref 0 in

Queue.push debut en_cours;

while not (Queue.is_empty en_cours) do
  let actuel = Queue.pop en_cours in
  while (nb_arete.(actuel) < k)
      & (!liste <> [])
      & (tab.(snd (List.hd !liste)) = tab.(actuel) + 1) do
    let suivant = snd (List.hd !liste) in
    arete.(actuel) <- suivant::arete.(actuel);
    nb_arete.(actuel) <- 1 + nb_arete.(actuel);
    nb_arete.(suivant) <- 1 + nb_arete.(suivant);
    res := !res + 1;
    Queue.push suivant en_cours;
    liste := List.tl !liste;
  done;
done;

let tab2 = Array.make n 1000000000 in
tab2.(debut) <- 0;
Queue.push debut en_cours;

while not (Queue.is_empty en_cours) do
  let actuel = Queue.pop en_cours in
  List.iter (fun x -> if tab2.(x) = 1000000000 then begin
                        Queue.push x en_cours;
                        tab2.(x) <- tab2.(actuel) + 1
                      end) arete.(actuel);
done;

let valide = ref true in
for i=0 to n-1 do
  if tab.(i) <> tab2.(i)
    then valide := false;
done;

if !valide then begin
  print_int !res;
  print_newline ();
end else print_string "-1\n";
for i=0 to n-1 do
  List.iter (fun x -> print_int (i+1);
                      print_string " ";
                      print_int (x+1);
                      print_newline()) arete.(i);
done

let n = Scanf.scanf "%d " (fun x -> x);;
let k = Scanf.scanf "%d\n" (fun x -> x);;

let tab = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x));;

let liste = ref [];;

for i=0 to n-1 do
  liste := (tab.(i), i)::!liste;
done;

liste := List.sort (fun (x,_) -> fun (y,_) -> x - y) !liste;

let _,debut = List.hd !liste in
liste := List.tl !liste;

let en_cours = Queue.create () in
let arete = Array.make n [] in
let nb_arete = Array.make n 0 in
let res = ref 0 in

Queue.push debut en_cours;

while not (Queue.is_empty en_cours) do
  let actuel = Queue.pop en_cours in
  while (nb_arete.(actuel) < k)
      & (!liste <> [])
      & (tab.(snd (List.hd !liste)) = tab.(actuel) + 1) do
    let suivant = snd (List.hd !liste) in
    arete.(actuel) <- suivant::arete.(actuel);
    nb_arete.(actuel) <- 1+ nb_arete.(actuel);
    res := !res + 1;
    Queue.push suivant en_cours;
    liste := List.tl !liste;
  done;
done;

let tab2 = Array.make n 1000000000 in
tab2.(debut) <- 0;
Queue.push debut en_cours;

while not (Queue.is_empty en_cours) do
  let actuel = Queue.pop en_cours in
  List.iter (fun x -> if tab2.(x) = 1000000000 then begin
                        Queue.push x en_cours;
                        tab2.(x) <- tab2.(actuel) + 1
                      end) arete.(actuel);
done;

let valide = ref true in
for i=0 to n-1 do
  if tab.(i) <> tab2.(i)
    then valide := false;
done;

if !valide then begin
  print_int !res;
  print_newline ();
end else print_string "-1\n";
for i=0 to n-1 do
  List.iter (fun x -> print_int (i+1);
                      print_string " ";
                      print_int (x+1);
                      print_newline()) arete.(i);
done


The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

The first line contains integer n (1 ≤ n ≤ 105) — the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 — the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.

Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".

let read () = Scanf.scanf "%d " (fun n -> n)
let print str = Printf.printf "%s\n" str

let check int n =
    if int >= n
    then
        true
    else
        false

let () =
    let n = read () in
    let rec loop i quart half =
        if i < n
        then
            let cash = read () in
            match cash with
            | 25 -> loop (i + 1) (quart + 1) half
            | 50 ->
                if check quart 1
                then
                    loop (i + 1) (quart - 1) (half + 1)
                else
                    print "NO"
            | 100 ->
                if check half 1 && check quart 1
                then
                    loop (i + 1) (quart - 1) (half - 1)
                else
                    if check quart 3
                    then
                        loop (i + 1) (quart - 3) half
                    else
                        print "NO"
        else
            print "YES"
    in loop 0 0 0

(* Codeforces 349 A Cinema Line *)

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

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

let rec can_change l n50 n25 = match l with
	| [] -> "YES"
	| h :: t -> match h with
			| 25 -> can_change t n50 (n25 + 1)
			| 50 -> if n25 ==0 then "NO" else can_change t (n50 +1) (n25 -1)
			| 100 -> if (2 * n50 + n25 < 3) || (n25 == 0)then "NO"
					else if n50 >0 then can_change t (n50 -1) (n25 -1)
					else can_change t n50 (n25 -3)
			| _ -> "Error, wrong n";;

let main() =
	let n = gr() in
	let l = readlist (n) [] in
	let li = List.rev l in
	let ans = can_change li 0 0 in
	begin
		print_string (ans ^ "\n")
	end;;

main();;

let read () = Scanf.scanf "%d " (fun n -> n)
let print str = Printf.printf "%s\n" str

let check int n =
    if int >= n
    then
        true
    else
        false

let () =
    let n = read () in
    let rec loop i quart half =
        if i < n
        then
            let cash = read () in
            match cash with
            | 25 -> loop (i + 1) (quart + 1) half
            | 50 ->
                if check quart 1
                then
                    loop (i + 1) (quart - 1) (half + 1)
                else
                    print "NO"
            | 100 ->
                if check half 1 && check quart 1 || check quart 3
                then
                    loop (i + 1) (quart - 1) (half - 1)
                else
                    if check quart 3
                    then
                        loop (i + 1) (quart - 3) half
                    else
                        print "NO"
        else
            print "YES"
    in loop 0 0 0

(* Codeforces 349 A Cinema Line *)

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

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

let rec can_change l n50 n25 = match l with
	| [] -> "YES"
	| h :: t -> match h with
			| 25 -> can_change t n50 (n25 + 1)
			| 50 -> if n25 ==0 then "NO" else can_change t (n50 +1) (n25 -1)
			| 100 -> if (2 * n50 + n25 < 3) || (n50 == 0)then "NO"
					else if n50 >0 then can_change t (n50 -1) (n25 -1)
					else can_change t n50 (n25 -3)
			| _ -> "Error, wrong n";;

let main() =
	let n = gr() in
	let l = readlist (n) [] in
	let li = List.rev l in
	let ans = can_change li 0 0 in
	begin
		print_string (ans ^ "\n")
	end;;

main();;


Qwerty the Ranger arrived to the Diatar system with a very important task. He should deliver a special carcinogen for scientific research to planet Persephone. This is urgent, so Qwerty has to get to the planet as soon as possible. A lost day may fail negotiations as nobody is going to pay for an overdue carcinogen.You can consider Qwerty's ship, the planet Persephone and the star Diatar points on a plane. Diatar is located in the origin of coordinate axes — at point (0, 0). Persephone goes round Diatar along a circular orbit with radius R in the counter-clockwise direction at constant linear speed vp (thus, for instance, a full circle around the star takes  of time). At the initial moment of time Persephone is located at point (xp, yp).At the initial moment of time Qwerty's ship is at point (x, y). Qwerty can move in any direction at speed of at most v (v > vp). The star Diatar is hot (as all stars), so Qwerty can't get too close to it. The ship's metal sheathing melts at distance r (r < R) from the star.Find the minimum time Qwerty needs to get the carcinogen to planet Persephone.

The first line contains space-separated integers xp, yp and vp ( - 104 ≤ xp, yp ≤ 104, 1 ≤ vp < 104) — Persephone's initial position and the speed at which it goes round Diatar. The second line contains space-separated integers x, y, v and r ( - 104 ≤ x, y ≤ 104, 1 < v ≤ 104, 1 ≤ r ≤ 104) — The intial position of Qwerty's ship, its maximum speed and the minimum safe distance to star Diatar. It is guaranteed that r2 < x2 + y2, r2 < xp2 + yp2 and vp < v.

Print a single real number — the minimum possible delivery time. The answer will be considered valid if its absolute or relative error does not exceed 10 - 6.

let pi = 4.0 *. atan 1.0
let pi2 = 2.0 *. pi
let sqr x = x *. x

let circle_zero_tangent x y r =
  let sxy = sqr x +. sqr y in
  let d = sxy -. sqr r in
    if d > 0.0 then (
      let sd = sqrt d in
      let c1 = (-. r *. x +. y *. sd) /. sxy in
      let c2 = (-. r *. x -. y *. sd) /. sxy in
      let check t =
	(x +. r *. cos t) *. (r *. cos t) +.
	  (y +. r *. sin t) *. (r *. sin t)
      in
      let t1 = acos c1
      and t2 = -. acos c1
      and t3 = acos c2
      and t4 = -. acos c2 in
      let t11 =
	if abs_float (check t1) < abs_float (check t2)
	then t1
	else t2
      in
      let t21 =
	if abs_float (check t3) <= abs_float (check t4)
	then t3
	else t4
      in
	Some (t11, t21)
	(*Some (acos c1, -. acos c1, acos c2, -. acos c2,
		check (acos c1), check (-. acos c1),
		check (acos c2), check (-. acos c2))*)
(*	if abs_float c1 <= 1.0 then
	  Some (acos c1, -. acos c1)
	else if abs_float c2 <= 1.0 then
	  Some (acos c2, -. acos c2)
	else
	  None*)
    ) else
      None

let point_circle_tangent x1 y1 x2 y2 r2 =
  match circle_zero_tangent (x2 -. x1) (y2 -. y1) r2 with
    | Some (t1, t2) ->
	let t1 = t1 +. pi /. 2.0
	and t2 = t2 +. pi /. 2.0 in
	  Some ((-. sin t1, cos t1, x1 *. sin t1 -. y1 *. cos t1),
		(-. sin t2, cos t2, x1 *. sin t2 -. y1 *. cos t2))
    | None -> None

let norm x y =
  sqrt (sqr x +. sqr y)

let dist x1 y1 x2 y2 =
  norm (x1 -. x2) (y1 -. y2)

let point_line_distance x y a b c =
  let sab = sqr a +. sqr b in
    abs_float (a *. x +. b *. y +. c) /. sqrt sab

let point_line_projection x y a b c =
  let sab = sqr a +. sqr b in
  let ab = sqrt sab in
  let d = -. (a *. x +. b *. y +. c) /. ab in
  let dx = d *. a /. ab
  and dy = d *. b /. ab in
    (x +. dx, y +. dy)

let point_line_projection_vec x y a b c =
  let sab = sqr a +. sqr b in
  let ab = sqrt sab in
  let r =
    if (a *. x +. b *. y +. c) >= 0.
    then -1.0
    else 1.0
  in
  let dx = r *. a /. ab
  and dy = r *. b /. ab in
    (dx, dy)

let point_line_projection_dist x y a b c r =
  let (dx, dy) = point_line_projection_vec x y a b c in
    (x +. r *. dx, y +. r *. dy)

let point_segment_dist x y x1 y1 x2 y2 =
  let vx = x2 -. x1
  and vy = y2 -. y1
  and wx = x -. x1
  and wy = y -. y1 in
  let c1 = wx *. vx +. wy *. vy in
    if c1 <= 0.0 then
      dist x y x1 y1
    else
      let c2 = sqr vx +. sqr vy in
	if c2 <= c1 then
	  dist x y x2 y2
	else
	  let b = c1 /. c2 in
	  let px = x1 +. b *. vx
	  and py = y1 +. b *. vy in
	    dist x y px py

let _ =
  let sb = Scanf.Scanning.stdib in
  let xp = Scanf.bscanf sb "%f " (fun s -> s) in
  let yp = Scanf.bscanf sb "%f " (fun s -> s) in
  let vp = Scanf.bscanf sb "%f " (fun s -> s) in
  let x = Scanf.bscanf sb "%f " (fun s -> s) in
  let y = Scanf.bscanf sb "%f " (fun s -> s) in
  let v = Scanf.bscanf sb "%f " (fun s -> s) in
  let r = Scanf.bscanf sb "%f " (fun s -> s) in
  let omega = 2.0 *. pi *. sqrt (sqr xp +. sqr yp) /. vp in
  let ppos t =
    let alpha = 2.0 *. pi *. t /. omega in
    let x = xp *. cos alpha -. yp *. sin alpha in
    let y = xp *. sin alpha +. yp *. cos alpha in
      (x, y)
  in
  let tr = 2.0 *. (sqrt (sqr (xp -. x) +. sqr (yp -. y)) +. r) /. (v -. vp) in
  let tl = 0.0 in
  let tr = ref tr in
  let tl = ref tl in
    for i = 1 to 100 do
      let tm = (!tl +. !tr) /. 2.0 in
      let (xp, yp) = ppos tm in
      let t =
	if point_segment_dist 0.0 0.0 x y xp yp < r then (
	  let (x11, y11, x12, y12) =
	    match point_circle_tangent x y 0.0 0.0 r with
	      | Some ((a1, b1, c1), (a2, b2, c2)) ->
		  let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in
		  let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in
		    (x1 *.r , y1 *. r, x2 *.r , y2 *. r)
	      | None -> assert false
	  in
	  let (x21, y21, x22, y22) =
	    match point_circle_tangent xp yp 0.0 0.0 r with
	      | Some ((a1, b1, c1), (a2, b2, c2)) ->
		  let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in
		  let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in
		    (x1 *.r , y1 *. r, x2 *.r , y2 *. r)
	      | None -> assert false
	  in
	  let t = ref infinity in
	    List.iter
	      (fun (x1, y1, x2, y2) ->
		 let c = dist x1 y1 x2 y2 in
		 let beta = acos ((2.0 *. sqr r -. sqr c) /. (2.0 *. sqr r)) in
(*Printf.printf "qwe %f %f %f %f  %f\n" x1 y1 x2 y2 beta;*)
		 let d =
		   dist x y x1 y1 +. beta *. r +. dist x2 y2 xp yp
		 in
		 let t' = d /. v in
		   t := min !t t'
	      ) [ (x11, y11, x21, y21);
		  (x11, y11, x22, y22);
		  (x12, y12, x21, y21);
		  (x12, y12, x22, y22);
		];
	    !t
	) else (
	  dist x y xp yp /. v
	)
      in
(*Printf.printf "asd %f %f  %f %f\n" tm t xp yp;*)
	if t < tm
	then tr := tm
	else tl := tm
    done;
    let res = (!tl +. !tr) /. 2.0 in
      Printf.printf "%.6f\n" res

let pi = 4.0 *. atan 1.0
let pi2 = 2.0 *. pi
let sqr x = x *. x

let circle_zero_tangent x y r =
  let sxy = sqr x +. sqr y in
  let d = sxy -. sqr r in
    if d > 0.0 then (
      let sd = sqrt d in
      let c1 = (-. r *. x +. y *. sd) /. sxy in
      let c2 = (-. r *. x -. y *. sd) /. sxy in
      let check t =
	(x +. r *. cos t) *. (r *. cos t) +.
	  (y +. r *. sin t) *. (r *. sin t)
      in
      let t1 = acos c1
      and t2 = -. acos c1
      and t3 = acos c2
      and t4 = -. acos c2 in
      let t11 =
	if abs_float (check t1) < abs_float (check t2)
	then t1
	else t2
      in
      let t21 =
	if abs_float (check t3) <= abs_float (check t4)
	then t3
	else t4
      in
	Some (t11, t21)
	(*Some (acos c1, -. acos c1, acos c2, -. acos c2,
		check (acos c1), check (-. acos c1),
		check (acos c2), check (-. acos c2))*)
(*	if abs_float c1 <= 1.0 then
	  Some (acos c1, -. acos c1)
	else if abs_float c2 <= 1.0 then
	  Some (acos c2, -. acos c2)
	else
	  None*)
    ) else
      None

let point_circle_tangent x1 y1 x2 y2 r2 =
  match circle_zero_tangent (x2 -. x1) (y2 -. y1) r2 with
    | Some (t1, t2) ->
	let t1 = t1 +. pi /. 2.0
	and t2 = t2 +. pi /. 2.0 in
	  Some ((-. sin t1, cos t1, x1 *. sin t1 -. y1 *. cos t1),
		(-. sin t2, cos t2, x1 *. sin t2 -. y1 *. cos t2))
    | None -> None

let norm x y =
  sqrt (sqr x +. sqr y)

let dist x1 y1 x2 y2 =
  norm (x1 -. x2) (y1 -. y2)

let point_line_distance x y a b c =
  let sab = sqr a +. sqr b in
    abs_float (a *. x +. b *. y +. c) /. sqrt sab

let point_line_projection x y a b c =
  let sab = sqr a +. sqr b in
  let ab = sqrt sab in
  let d = -. (a *. x +. b *. y +. c) /. ab in
  let dx = d *. a /. ab
  and dy = d *. b /. ab in
    (x +. dx, y +. dy)

let point_line_projection_vec x y a b c =
  let sab = sqr a +. sqr b in
  let ab = sqrt sab in
  let r =
    if (a *. x +. b *. y +. c) >= 0.
    then -1.0
    else 1.0
  in
  let dx = r *. a /. ab
  and dy = r *. b /. ab in
    (dx, dy)

let point_line_projection_dist x y a b c r =
  let (dx, dy) = point_line_projection_vec x y a b c in
    (x +. r *. dx, y +. r *. dy)

let point_segment_dist x y x1 y1 x2 y2 =
  let vx = x2 -. x1
  and vy = y2 -. y1
  and wx = x -. x1
  and wy = y -. y1 in
  let c1 = wx *. vx +. wy *. vy in
    if c1 <= 0.0 then
      dist x y x1 y1
    else
      let c2 = sqr vx +. sqr vy in
	if c2 <= c1 then
	  dist x y x2 y2
	else
	  let b = c1 /. c2 in
	  let px = x1 +. b *. vx
	  and py = y1 +. b *. vy in
	    dist x y px py

let _ =
  let sb = Scanf.Scanning.stdib in
  let xp = Scanf.bscanf sb "%f " (fun s -> s) in
  let yp = Scanf.bscanf sb "%f " (fun s -> s) in
  let vp = Scanf.bscanf sb "%f " (fun s -> s) in
  let x = Scanf.bscanf sb "%f " (fun s -> s) in
  let y = Scanf.bscanf sb "%f " (fun s -> s) in
  let v = Scanf.bscanf sb "%f " (fun s -> s) in
  let r = Scanf.bscanf sb "%f " (fun s -> s) in
  let omega = 2.0 *. pi *. sqrt (sqr xp +. sqr yp) /. vp in
  let ppos t =
    let alpha = 2.0 *. pi *. t /. omega in
    let x = xp *. cos alpha -. yp *. sin alpha in
    let y = xp *. sin alpha +. yp *. cos alpha in
      (x, y)
  in
  let tr = 2.0 *. (sqrt (sqr (xp -. x) +. sqr (yp -. y)) +. r) /. v in
  let tl = 0.0 in
  let tr = ref tr in
  let tl = ref tl in
    for i = 1 to 100 do
      let tm = (!tl +. !tr) /. 2.0 in
      let (xp, yp) = ppos tm in
      let t =
	if point_segment_dist 0.0 0.0 x y xp yp < r then (
	  let (x11, y11, x12, y12) =
	    match point_circle_tangent x y 0.0 0.0 r with
	      | Some ((a1, b1, c1), (a2, b2, c2)) ->
		  let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in
		  let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in
		    (x1 *.r , y1 *. r, x2 *.r , y2 *. r)
	      | None -> assert false
	  in
	  let (x21, y21, x22, y22) =
	    match point_circle_tangent xp yp 0.0 0.0 r with
	      | Some ((a1, b1, c1), (a2, b2, c2)) ->
		  let (x1, y1) = point_line_projection_vec 0.0 0.0 a1 b1 c1 in
		  let (x2, y2) = point_line_projection_vec 0.0 0.0 a2 b2 c2 in
		    (x1 *.r , y1 *. r, x2 *.r , y2 *. r)
	      | None -> assert false
	  in
	  let t = ref infinity in
	    List.iter
	      (fun (x1, y1, x2, y2) ->
		 let c = dist x1 y1 x2 y2 in
		 let beta = acos ((2.0 *. sqr r -. sqr c) /. (2.0 *. sqr r)) in
(*Printf.printf "qwe %f %f %f %f  %f\n" x1 y1 x2 y2 beta;*)
		 let d =
		   dist x y x1 y1 +. beta *. r +. dist x2 y2 xp yp
		 in
		 let t' = d /. v in
		   t := min !t t'
	      ) [ (x11, y11, x21, y21);
		  (x11, y11, x22, y22);
		  (x12, y12, x21, y21);
		  (x12, y12, x22, y22);
		];
	    !t
	) else (
	  dist x y xp yp /. v
	)
      in
(*Printf.printf "asd %f %f  %f %f\n" tm t xp yp;*)
	if t < tm
	then tr := tm
	else tl := tm
    done;
    let res = (!tl +. !tr) /. 2.0 in
      Printf.printf "%.6f\n" res


George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of rooms. The i-th of the next n lines contains two integers pi and qi (0 ≤ pi ≤ qi ≤ 100) — the number of people who already live in the i-th room and the room's capacity.

Print a single integer — the number of rooms where George and Alex can move in.

let list_init n f =
    let rec read_input n new_list =
        if n > 0
        then
            let new_element = f() in
            read_input (n - 1) (new_element :: new_list)
        else
            List.rev new_list
    in read_input n []

let room_data n = list_init n (fun i -> Scanf.scanf "%d %d " (fun s0 s1 -> (s0, s1)))

let input () =
    let number_of_rooms = Scanf.scanf "%d " (fun n -> n) in
    room_data number_of_rooms

let solve list = List.length(List.filter(fun (a, b) -> b - a >= 2) list)

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

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

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

let rec solve n ak =
  if n = 0 then
    ak
  else
    let p = read_int () in
    let q = read_int () in
    if q - p < 2 then
      solve (n - 1) ak
    else
      solve (n - 1) (ak + 1)

let () =
  let n = read_int () in
  Printf.printf "%d" (solve n 0)

let list_init n f =
  let rec read_input n new_list =
    if n > 0
    then
      let new_element = f() in
      read_input (n - 1) (new_element :: new_list)
    else
      List.rev new_list
  in read_input n []

let room_data n = list_init n (fun i -> Scanf.scanf "%d %d " (fun s0 s1 -> (s0, s1)))

let input () =
  let number_of_rooms = Scanf.scanf "%d " (fun n -> n) in
  room_data number_of_rooms

let solve list = List.length(List.filter(fun (a, b) -> b - a >= 2) list)

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

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

open Printf
type room = R of int*int

let n =  Scanf.scanf "%d " ( fun x -> x) in
let read_int () =  Scanf.scanf "%d %d " ( fun x y -> R(x,y)) in
let a = Array.init n (fun i -> read_int ()) in
let f = function
  | R (p,q) -> if q-p >=2 then true else false
in Array.to_list a |>List.filter (fun x -> f x) |> List.length |> printf "%d\n"

open Scanf
open Printf

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

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

  print_int (Array.fold_left (fun acc pair -> if (fst(pair) + 2 <= snd(pair)) then acc + 1 else acc) 0 a);
  print_newline ();


Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?

The first line contains the only integer n (1 ≤ n ≤ 100) — the number of cookie bags Anna and Maria have. The second line contains n integers ai (1 ≤ ai ≤ 100) — the number of cookies in the i-th bag.

Print in the only line the only number — the sought number of ways. If there are no such ways print 0.

NoteIn the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies — 5 + 3 = 8 ways in total.In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2 * 9 + 99 = 117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies.

(* Read first line input and return numbers *)
let read_nums str =
  let nstrings = Str.split (Str.regexp " ") str in
  List.map (fun x -> int_of_string x) nstrings
in
ignore (read_line ());
let p = read_line () in
let pck = read_nums p in
let methods_count packs =
  let count = ref 0 in
  let list_sum list =
    let sum = ref 0 in
    List.iter (fun x -> sum := !sum + x) list;
    !sum
  in
  let lsum = list_sum packs in
  let even = lsum mod 2 = 0 in
  let comparefun' e =
    match e with
	true -> fun x -> x mod 2 = 0
      | false -> fun x -> x mod 2 <> 0
  in
  let compare = comparefun' even in
  List.iter (fun x -> if compare x then
      count := !count + 1
  ) packs;
  !count
in
print_int (methods_count pck)


Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k.

The only line contains three space-separated integers k, a and b (1 ≤ k ≤ 1018; - 1018 ≤ a ≤ b ≤ 1018).

let [x; a; b] = List.map (Int64.of_string) (Str.split (Str.regexp " ") (read_line ()));;
let k = ref (Int64.div a x);;
if ((Int64.mul !k x) < a) then k := Int64.add !k 1L;;
let t = Int64.sub b (Int64.mul x !k) and ans = ref 0L;;
if t >= 0L then	ans := Int64.add (Int64.div t x) 1L;;
print_string (Int64.to_string !ans);;

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let c = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let a = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let b = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let quot x y =
    let d = x /| y in
    let x' = d *| y in
      if x' <= x
      then d
      else d -| 1L
  in
  let res = quot b c -| quot (a -| 1L) c in
    Printf.printf "%Ld\n" res


You are the gym teacher in the school.There are $$$n$$$ students in the row. And there are two rivalling students among them. The first one is in position $$$a$$$, the second in position $$$b$$$. Positions are numbered from $$$1$$$ to $$$n$$$ from left to right.Since they are rivals, you want to maximize the distance between them. If students are in positions $$$p$$$ and $$$s$$$ respectively, then distance between them is $$$|p - s|$$$. You can do the following operation at most $$$x$$$ times: choose two adjacent (neighbouring) students and swap them.Calculate the maximum distance between two rivalling students after at most $$$x$$$ swaps.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains four integers $$$n$$$, $$$x$$$, $$$a$$$ and $$$b$$$ ($$$2 \le n \le 100$$$, $$$0 \le x \le 100$$$, $$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the number of students in the row, the number of swaps which you can do, and positions of first and second rivaling students respectively.

For each test case print one integer — the maximum distance between two rivaling students which you can obtain.

NoteIn the first test case you can swap students in positions $$$3$$$ and $$$4$$$. And then the distance between the rivals is equal to $$$|4 - 2| = 2$$$.In the second test case you don't have to swap students. In the third test case you can't swap students.

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

let _ =
    let (t : int ref) = ref (wczytaj ()) in
        while !t > 0 do
            let n = wczytaj () and
                x = wczytaj () and
                a = wczytaj () and
                b = wczytaj () in
                let a = min a b and
                b = max a b in
            let odl = (b - a) in
            let delta = min (a - 1 + (n - b)) x in
            Printf.printf "%d\n" (odl + delta);
            t := !t - 1;
        done
;;


Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s ≠ t) if si < ti where i is the smallest index such that si ≠ ti. (so sj = tj for all j < i)

The first line of input contains a string s of length n (1 ≤ n ≤ 3·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially.

The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally.

NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx.

module Letters =
struct
   type t = char * int
   let compare = Pervasives.compare
end

module Heap = Set.Make(Letters)

let rec oleg deb fin igr olg =
   if Heap.is_empty olg
   then (deb, fin)
   else if Heap.is_empty igr || fst (Heap.min_elt olg) >= fst (Heap.max_elt igr)
         then let x = Heap.max_elt olg in
              let olg_rmv = Heap.remove x olg in
                  igor deb (x::fin) igr olg_rmv
         else let y = Heap.min_elt olg in
              let olg_rmv = Heap.remove y olg in
                  igor (y::deb) fin igr olg_rmv
and igor deb fin igr olg =
   if Heap.is_empty igr
   then (deb, fin)
   else if Heap.is_empty olg || fst (Heap.max_elt igr) <= fst (Heap.min_elt olg)
         then let x = Heap.min_elt igr in
              let igr_rmv = Heap.remove x igr in
                  oleg deb (x::fin) igr_rmv olg
         else let y = Heap.max_elt igr in
              let igr_rmv = Heap.remove y igr in
                  oleg (y::deb) fin igr_rmv olg

let rec first_aux acc k = function
   | x::l when k > 0 -> first_aux (x::acc) (k-1) l
   | _ -> acc

let first = first_aux []

let not_cmp x y = - (compare x y)

let _ =
   let igr = ref [] and olg = ref [] in
   let (s,t) = Scanf.scanf "%s %s" (fun s t -> s,t) in
   let n = String.length s in
      String.iteri (fun i x -> olg := (x,i)::!olg) s;
      String.iteri (fun i x -> igr := (x,i)::!igr) t;
      olg := List.sort compare !olg;
      igr := List.sort not_cmp !igr;
      olg := first ((n + 1) / 2) !olg;
      igr := first (n / 2) !igr;
   let (deb, fin) = oleg [] [] (Heap.of_list !igr) (Heap.of_list !olg)
   in
      List.iter (fun (x,_) -> print_char x) (List.rev deb);
      List.iter (fun (x,_) -> print_char x) fin