Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s.The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS".Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message.

The first line contains line s (1 ≤ |s| ≤ 2·105), consisting of uppercase and lowercase English letters — the text of Tanya's message. The second line contains line t (|s| ≤ |t| ≤ 2·105), consisting of uppercase and lowercase English letters — the text written in the newspaper. Here |a| means the length of the string a.

Print two integers separated by a space:   the first number is the number of times Tanya shouts "YAY!" while making the message,  the second number is the number of times Tanya says "WHOOPS" while making the message.

let compte mot =
	let tab = Array.make 123 0 in
	for i=0 to String.length mot-1 do
		tab.(int_of_char (mot.[i])) <- 1 + tab.(int_of_char (mot.[i]));
	done;
	tab;;

let f mot1 mot2 =
	let tab1 = compte mot1 and tab2 = compte mot2
	and compteur = ref 0 and compteur2 = ref 0 in
	for i=0 to 122 do
		let a = min (tab1.(i)) (tab2.(i)) in
			compteur := a + !compteur;
			tab1.(i) <- tab1.(i) - a;
			tab2.(i) <- tab2.(i) - a;
	done;
	let tab_r1 = Array.init 26 (fun i -> tab1.(65 +i) + tab1.(97 + i))
	and tab_r2 = Array.init 26 (fun i -> tab2.(65 +i) + tab2.(97 + i))
	in
	for i=0 to 25 do
		let a = min (tab_r1.(i)) (tab_r2.(i)) in
			compteur2 := a + !compteur2;
			tab_r1.(i) <- tab_r1.(i) - a;
			tab_r2.(i) <- tab_r2.(i) - a;
	done;
	!compteur, !compteur2;;

let main () =
	let mot1 = Scanf.scanf "%s " (fun i -> String.trim i) in
	let mot2 = Scanf.scanf "%s " (fun i -> String.trim i) in
	let (a,b) = f mot1 mot2 in
		Printf.printf "%d %d " a b;;

main ();;

open Printf
open Scanf

let isupper c = c <= 'Z' && c >= 'A'
let l2n c = (int_of_char c) - (int_of_char 'a')
let l2N c = (int_of_char c) - (int_of_char 'A')

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

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

  let compute_hist s =
    let h = Array.make_matrix 26 2 0 in
    let n = String.length s in
    for i=0 to n-1 do
      if isupper s.[i] then (
	let x = l2N s.[i] in
	h.(x).(1) <- h.(x).(1) + 1;
      ) else (
	let x = l2n s.[i] in
	h.(x).(0) <- h.(x).(0) + 1;
      )
    done;
    h
  in

  let hist_s = compute_hist s in
  let hist_t = compute_hist t in

  let ( ++ ) (a,b) (c,d) = (a+c, b+d) in

  let eval_letter ls hs lt ht =
    let yay = (min ls lt) + (min hs ht) in
    let short = min (ls+hs) (lt+ht) in
    (yay, short-yay)
  in

  let (x,y) = fold 0 25 (
    fun i ac ->
      (eval_letter hist_s.(i).(0) hist_s.(i).(1) hist_t.(i).(0) hist_t.(i).(1)) ++ ac
  ) (0,0)
  in

  printf "%d %d\n" x y


Stepan has the newest electronic device with a display. Different digits can be shown on it. Each digit is shown on a seven-section indicator like it is shown on the picture below.  So, for example, to show the digit 3 on the display, 5 sections must be highlighted; and for the digit 6, 6 sections must be highlighted. The battery of the newest device allows to highlight at most n sections on the display. Stepan wants to know the maximum possible integer number which can be shown on the display of his newest device. Your task is to determine this number. Note that this number must not contain leading zeros. Assume that the size of the display is enough to show any integer.

The first line contains the integer n (2 ≤ n ≤ 100 000) — the maximum number of sections which can be highlighted on the display.

Print the maximum integer which can be shown on the display of Stepan's newest device.

open Printf;;

let n=read_int();;

(if (n mod 2 == 1) then
    printf "%d" (7)
);

for i = 1 to (n / 2 - (n mod 2)) do
    printf "%d" (1)
done;;

let n=read_int();;
if n == 1 then print_endline("0")
else
	for i = 1 to n/2 do
	    if n mod 2 == 1 && i==1 then Printf.printf "%d" 7
    	else Printf.printf "%d" 1
 	done;;

let a = read_int();;
let n = ref a;;

if (a mod 2 == 1) then
	print_int 7;
	n := a-3;;

if (a mod 2 == 0) then
	n := a;;

let x = (!n)/2
for i=1 to x do
	Printf.printf "1"
done

let n=read_int();;
let g = n;
if n mod 2 == 1 then print_string("7");
let n = if n mod 2 == 1 then n - 3 else n in
for i = 1 to n / 2 do
print_string("1");
done;;

open Printf;;
let n=read_int();;

if n mod 2 > 0 then begin
    printf "7";
    for i=1 to (n-3)/2 do
        printf "1"
    done
end
else begin
  for i=1 to n/2 do
    printf "1"
    done
end;;

let rec print1 n =
  for i = 1 to n do
  	Printf.printf "1";
  done;;

let n = read_int () ;;
if n mod 2 == 0 then print1 (n / 2)
else begin
	print_int 7;
	print1 (n / 2 - 1)
end

let rec print1 n =
  for i = 1 to n do
  	Printf.printf "1";
  done;;

let n = read_int () ;;
if n mod 2 == 0 then print1 (n / 2)
else begin
	print1 (n / 2 - 1) ;
	print_int 7
end

let rec print1 n =
  match n with
  | -1  -> true;
  | 0  -> true;
  | nn -> print_int 1 ; print1 (n-1)

let n = read_int () ;;
if n mod 2 == 0 then print1 (n / 2)
else begin
	print1 (n / 2 - 1) ;
	print_int 7;
	true
end


Amr has got a large array of size n. Amr doesn't like large arrays so he intends to make it smaller.Amr doesn't care about anything in the array except the beauty of it. The beauty of the array is defined to be the maximum number of times that some number occurs in this array. He wants to choose the smallest subsegment of this array such that the beauty of it will be the same as the original array.Help Amr by choosing the smallest subsegment possible.

The first line contains one number n (1 ≤ n ≤ 105), the size of the array. The second line contains n integers ai (1 ≤ ai ≤ 106), representing elements of the array.

Output two integers l, r (1 ≤ l ≤ r ≤ n), the beginning and the end of the subsegment chosen respectively. If there are several possible answers you may output any of them.

NoteA subsegment B of an array A from l to r is an array of size r - l + 1 where Bi = Al + i - 1 for all 1 ≤ i ≤ r - l + 1

open Printf
open Scanf

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

  let h = Hashtbl.create 10 in

  let add_to t index =
    let c = try Hashtbl.find h t with Not_found -> [] in
    Hashtbl.replace h t (index::c)
  in

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

  let len = Hashtbl.fold (fun _ v ac -> max ac (List.length v)) h 0 in

  let (first,last) = Hashtbl.fold (
    fun _ v (f,l) ->
      if List.length v <> len then (f,l)
      else
	let l1 = List.hd v in
	let f1 = List.nth v (len-1) in
	if l1-f1 < l-f then (f1,l1) else (f,l)
  ) h (0,n-1) in

  printf "%d %d\n" (first+1) (last+1)


Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water.It turned out that among Pasha's friends there are exactly n boys and exactly n girls and all of them are going to come to the tea party. To please everyone, Pasha decided to pour the water for the tea as follows:  Pasha can boil the teapot exactly once by pouring there at most w milliliters of water;  Pasha pours the same amount of water to each girl;  Pasha pours the same amount of water to each boy;  if each girl gets x milliliters of water, then each boy gets 2x milliliters of water. In the other words, each boy should get two times more water than each girl does.Pasha is very kind and polite, so he wants to maximize the total amount of the water that he pours to his friends. Your task is to help him and determine the optimum distribution of cups between Pasha's friends.

The first line of the input contains two integers, n and w (1 ≤ n ≤ 105, 1 ≤ w ≤ 109) — the number of Pasha's friends that are boys (equal to the number of Pasha's friends that are girls) and the capacity of Pasha's teapot in milliliters. The second line of the input contains the sequence of integers ai (1 ≤ ai ≤ 109, 1 ≤ i ≤ 2n) — the capacities of Pasha's tea cups in milliliters.

Print a single real number — the maximum total amount of water in milliliters that Pasha can pour to his friends without violating the given conditions. Your answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

NotePasha also has candies that he is going to give to girls but that is another task...

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

let () =
  let min x y =
    if x < y then x
    else y
  in
  let n = xint() and w = xint() in
  let a = Array.make (n * 2) 0 in
  for i = 0 to (n * 2 - 1) do
    a.(i) <- xint();
  done;
  Array.sort compare a;
  let x = a.(0) and y = a.(n) in
  let z = min (float_of_int y) ((float_of_int x) *. 2.) in
  Printf.printf "%.10f\n" (min (float_of_int w) (z *. 1.5 *. (float_of_int n)));

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

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

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

let id x = x
let id2 x y = (x, y)
let id3 x y z = (x, y, z)
let id4 a b c d = (a, b, c, d)
let id5 a b c d e = (a, b, c, d, e)

let err s = raise (Failure s)

let inf = 1000000000
let eps = 1e-11

let _ =
  let n, w = sf "%d %f " id2 in
  let a = A.make (2 * n) 0. in
  for i = 0 to 2 * n - 1 do
    let ai = sf "%d " id in
    a.(i) <- float ai
  done;
  A.sort compare a;
  let r = A.mapi (fun x y -> if x < n then 2. *. y else y) a |> A.fold_left min 1e9 in
  r *. 1.5 *. float n |> min w |> pf "%.9f\n"
;;

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

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

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

let id x = x
let id2 x y = (x, y)
let id3 x y z = (x, y, z)
let id4 a b c d = (a, b, c, d)
let id5 a b c d e = (a, b, c, d, e)

let err s = raise (Failure s)

let inf = 1000000000
let eps = 1e-11

let _ =
  let n, w = sf "%d %d " id2 in
  let a = A.make (2 * n) 0. in
  for i = 0 to 2 * n - 1 do
    let ai = sf "%d " id in
    a.(i) <- float ai
  done;
  A.sort compare a;
  let r = A.mapi (fun x y -> if x < n then 2. *. y else y) a |> A.fold_left min 1e9 in
  r *. 1.5 *. float n |> max 1. |> pf "%.9f\n"
;;

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

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

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

let id x = x
let id2 x y = (x, y)
let id3 x y z = (x, y, z)
let id4 a b c d = (a, b, c, d)
let id5 a b c d e = (a, b, c, d, e)

let err s = raise (Failure s)

let inf = 1000000000
let eps = 1e-11

let _ =
  let n, w = sf "%d %d " id2 in
  let a = A.make (2 * n) 0. in
  for i = 0 to 2 * n - 1 do
    let ai = sf "%d " id in
    a.(i) <- float ai
  done;
  A.sort compare a;
  let r = A.mapi (fun x y -> if x < n then 2. *. y else y) a |> A.fold_left min 1e9 in
  pf "%.9f\n" @@ r *. 1.5 *. float n
;;


Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an.While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1, b2, ..., bn. Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.

The first line contains three integers n, l, r (1 ≤ n ≤ 105, 1 ≤ l ≤ r ≤ n) — the number of Vasya's cubes and the positions told by Stepan. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ n) — the sequence of integers written on cubes in the Vasya's order. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ n) — the sequence of integers written on cubes after Stepan rearranged their order. It is guaranteed that Stepan did not remove or add other cubes, he only rearranged Vasya's cubes.

Print "LIE" (without quotes) if it is guaranteed that Stepan deceived his brother. In the other case, print "TRUTH" (without quotes).

NoteIn the first example there is a situation when Stepan said the truth. Initially the sequence of integers on the cubes was equal to [3, 4, 2, 3, 1]. Stepan could at first swap cubes on positions 2 and 3 (after that the sequence of integers on cubes became equal to [3, 2, 4, 3, 1]), and then swap cubes in positions 3 and 4 (after that the sequence of integers on cubes became equal to [3, 2, 3, 4, 1]).In the second example it is not possible that Stepan said truth because he said that he swapped cubes only between positions 1 and 2, but we can see that it is guaranteed that he changed the position of the cube which was on the position 3 at first. So it is guaranteed that Stepan deceived his brother.In the third example for any values l and r there is a situation when Stepan said the truth.

open List;;
let inp = Array.of_list (map (fun x -> int_of_string x) (Str.split (Str.regexp "[ \t]+") (read_line())));;
let n = Array.get inp 0;;
let l = (Array.get inp 1) - 1;;
let r = (Array.get inp 2) - 1;;
let a = Array.of_list (map (fun x -> int_of_string x) (Str.split (Str.regexp "[ \t]+") (read_line())));;
let b = Array.of_list (map (fun x -> int_of_string x) (Str.split (Str.regexp "[ \t]+") (read_line())));;
let flag2 = (Array.sub a 0 l) = (Array.sub b 0 l);;
let flag3 = (Array.sub a (r + 1) (n - r - 1)) = (Array.sub b (r + 1) (n - r - 1));;
(Array.sort compare a);;
(Array.sort compare b);;
let flag1 = a = b;;
print_string (if (flag1 && flag2 && flag3) then ("TRUTH") else ("LIE"));;


Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area.

The first line contains integer n (1 ≤ n ≤ 2000) — the number of the points painted on the plane.  Next n lines contain two integers each xi, yi ( - 100 ≤ xi, yi ≤ 100) — the coordinates of the i-th point. It is guaranteed that no two given points coincide.

In the first line print an integer — the number of triangles with the non-zero area among the painted points.

NoteNote to the first sample test. There are 3 triangles formed: (0, 0) - (1, 1) - (2, 0); (0, 0) - (2, 2) - (2, 0); (1, 1) - (2, 2) - (2, 0).Note to the second sample test. There is 1 triangle formed: (0, 0) - (1, 1) - (2, 0).Note to the third sample test. A single point doesn't form a single triangle.

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

let () =
  let slope x y =
    if y == 0 then 1e12
    else (float_of_int x) /. (float_of_int y)
  in
  let n = xint () in
  if n <= 2 then (
    print_endline "0";
    exit 0;
  );
  let x = Array.make n 0 and y = Array.make n 0 in
  for i = 0 to n - 1 do
    x.(i) <- xint ();
    y.(i) <- xint ();
  done;
  let ret = ref 0l in
  for i = 0 to n - 1 do
    let v = Array.make (n - i - 1) 0.0 in
    for j = i + 1 to n - 1 do
      v.(j - i - 1) <- slope (y.(j) - y.(i)) (x.(j) - x.(i));
    done;
    Array.sort compare v;
    let cnt = ref 0 in
    for x = 1 to n - i - 2 do
      if v.(x) = v.(x - 1) then cnt := !cnt + 1
      else cnt := 0;
      ret := Int32.add !ret (Int32.of_int !cnt);
    done;
  done;
  let total = ref (Int64.of_int n) in
  total := Int64.mul !total (Int64.of_int (n - 1));
  total := Int64.mul !total (Int64.of_int (n - 2));
  total := Int64.div !total 6L;
  total := Int64.sub !total (Int64.of_int32 !ret);
  print_endline (Int64.to_string !total);

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

let () =
  let rec gcd a b =
    if b == 0 then a
    else gcd b (a mod b)
  in
  let abs x =
    if x < 0 then -x
    else x
  in
  let n = xint () in
  if n <= 2 then (
    print_endline "0";
    exit 0;
  );
  let x = Array.make n 0 and y = Array.make n 0 in
  for i = 0 to n - 1 do
    x.(i) <- xint ();
    y.(i) <- xint ();
  done;
  let ret = ref 0L in
  let a = Array.make n 0 in
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      let dx = ref (x.(j) - x.(i)) in
      let dy = ref (y.(j) - y.(i)) in
      let g = gcd (abs !dx) (abs !dy) in
      if g != 0 then (
        dx := !dx / g;
        dy := !dy / g;
        if !dx < 0 then (
          dx := 0 - !dx; dy := 0 - !dy;
        )
      );
      a.(j) <- !dx * 100000 + !dy;
    done;
    Array.sort compare a;
    let s = ref 0 in
    while !s < n do
      let t = ref !s in
      while !t < n && a.(!t) == a.(!s) do
        t := !t + 1;
      done;
      if a.(!s) != 0 then (
        let c = !t - !s in
        ret := Int64.add !ret (Int64.of_int (c * (n - c - 1)));
      );
      s := !t;
    done;
  done;
  ret := Int64.div !ret 6L;
  print_endline (Int64.to_string !ret);


There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1 ≤ i ≤ n - 1), such that ai + 1 > ai.

The first line of the input contains integer n (1 ≤ n ≤ 1000) — the number of painting. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where ai means the beauty of the i-th painting.

Print one integer — the maximum possible number of neighbouring pairs, such that ai + 1 > ai, after the optimal rearrangement.

NoteIn the first sample, the optimal order is: 10, 20, 30, 40, 50.In the second sample, the optimal order is: 100, 200, 100, 200.

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

let () =
  let n = read_int() in
  let hist = Array.make 1000 0 in
  for i=0 to n-1 do
    let a = read_int() - 1 in
    hist.(a) <- hist.(a) + 1
  done;

  let rec loop remain a ac = if remain=0 then List.rev ac else (
    if hist.(a) > 0 then (
      hist.(a) <- hist.(a) - 1;
      loop (remain-1) ((a+1) mod 1000) (a::ac)
    ) else loop remain ((a+1) mod 1000) ac
  ) in

  let list = loop n 0 [] in

  let rec countup ac li = match li with
    | [] -> ac
    | x::[] -> ac
    | x::(y::t) ->
      let ac = ac + (if x < y then 1 else 0) in
      countup ac (y::t)
  in

  printf "%d\n" (countup 0 list)


Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original edge to the opposite edge. Gerald loses in this game in each of the three cases:  At least one of the chips at least once fell to the banned cell.  At least once two chips were on the same cell.  At least once two chips swapped in a minute (for example, if you stand two chips on two opposite border cells of a row with even length, this situation happens in the middle of the row). In that case he loses and earns 0 points. When nothing like that happened, he wins and earns the number of points equal to the number of chips he managed to put on the board. Help Gerald earn the most points.

The first line contains two space-separated integers n and m (2 ≤ n ≤ 1000, 0 ≤ m ≤ 105) — the size of the field and the number of banned cells. Next m lines each contain two space-separated integers. Specifically, the i-th of these lines contains numbers xi and yi (1 ≤ xi, yi ≤ n) — the coordinates of the i-th banned cell. All given cells are distinct. Consider the field rows numbered from top to bottom from 1 to n, and the columns — from left to right from 1 to n.

Print a single integer — the maximum points Gerald can earn in this game.

NoteIn the first test the answer equals zero as we can't put chips into the corner cells.In the second sample we can place one chip into either cell (1, 2), or cell (3, 2), or cell (2, 1), or cell (2, 3). We cannot place two chips.In the third sample we can only place one chip into either cell (2, 1), or cell (2, 4).

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

let (m, n) = (read_int(), read_int()) in
let frow = Array.make (n + 1) 1 in
let fcol = Array.make (n + 1) 1 in
for i = 1 to m do
    let (a, b) = (read_int(), read_int()) in (frow.(a) <- 0; fcol.(b) <- 0)
done;
let rec accum_res i =
    if i = 1 then 0
    else (accum_res (i - 1)) + frow.(i) + fcol.(i)
in
    Printf.printf "%d\n" ((accum_res (n - 1)) + (if (n mod 2 = 1) & (frow.((n + 1) / 2) == 1) & (fcol.((n + 1) / 2) == 1) then -1 else 0))


Alice has just learned addition. However, she hasn't learned the concept of "carrying" fully — instead of carrying to the next column, she carries to the column two columns to the left.For example, the regular way to evaluate the sum $$$2039 + 2976$$$ would be as shown:   However, Alice evaluates it as shown:   In particular, this is what she does:   add $$$9$$$ and $$$6$$$ to make $$$15$$$, and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$0$$$ $$$9$$$";  add $$$3$$$ and $$$7$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column "$$$2$$$ $$$2$$$";  add $$$1$$$, $$$0$$$, and $$$9$$$ to make $$$10$$$ and carry the $$$1$$$ to the column two columns to the left, i. e. to the column above the plus sign;  add $$$1$$$, $$$2$$$ and $$$2$$$ to make $$$5$$$;  add $$$1$$$ to make $$$1$$$.  Thus, she ends up with the incorrect result of $$$15005$$$.Alice comes up to Bob and says that she has added two numbers to get a result of $$$n$$$. However, Bob knows that Alice adds in her own way. Help Bob find the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$. Note that pairs $$$(a, b)$$$ and $$$(b, a)$$$ are considered different if $$$a \ne b$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 10^9$$$) — the number Alice shows Bob.

For each test case, output one integer — the number of ordered pairs of positive integers such that when Alice adds them, she will get a result of $$$n$$$.

open Printf
open Scanf

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

let count ci co d =
(* given carry in, carry out and d, how many ways to do it? *)
  let s = 10*co + d - ci in
  if s <= 9 then s+1 else 19-s

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 rec digits n ac =
      if n = 0 then List.rev ac else
	digits (n/10) ((n mod 10) :: ac)
    in

    let dig = Array.of_list (digits n []) in
    let nd = Array.length dig in  (* number of digits *)
(*
    for i=0 to nd-1 do
      printf "%d " dig.(i)
    done;
    print_newline();
*)
    let count_solutions_with_carry c =
(*      printf "count_solns.. c= " ;
      for i= 7 downto 0 do
	printf "%d" ((c lsr i) land 1)
      done;
*)
      let c' = c lsl 2 in
      let rec prod_loop i ac =
	if ac=0 || i >= 10 then ac else (
	  let ci = (c' lsr i) land 1 in
	  let co= (c lsr i) land 1 in
	  prod_loop (i+1) (ac * (count ci co (if i >= nd then 0 else dig.(i))))
	) in
      let ans = prod_loop 0 1 in
(*      printf "   answer = %d\n" ans; *)
      ans
    in

    let answer = sum 0 255 (fun c -> count_solutions_with_carry c) in
    printf "%d\n" (answer - 2)
  done


Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has $$$n$$$ warriors, he places them on a straight line in front of the main gate, in a way that the $$$i$$$-th warrior stands right after $$$(i-1)$$$-th warrior. The first warrior leads the attack.Each attacker can take up to $$$a_i$$$ arrows before he falls to the ground, where $$$a_i$$$ is the $$$i$$$-th warrior's strength.Lagertha orders her warriors to shoot $$$k_i$$$ arrows during the $$$i$$$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $$$t$$$, they will all be standing to fight at the end of minute $$$t$$$.The battle will last for $$$q$$$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \leq 200\,000$$$) — the number of warriors and the number of minutes in the battle. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) that represent the warriors' strengths. The third line contains $$$q$$$ integers $$$k_1, k_2, \ldots, k_q$$$ ($$$1 \leq k_i \leq 10^{14}$$$), the $$$i$$$-th of them represents Lagertha's order at the $$$i$$$-th minute: $$$k_i$$$ arrows will attack the warriors.

Output $$$q$$$ lines, the $$$i$$$-th of them is the number of standing warriors after the $$$i$$$-th minute.

NoteIn the first example:   after the 1-st minute, the 1-st and 2-nd warriors die.  after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive.  after the 3-rd minute, the 1-st warrior dies.  after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1.  after the 5-th minute, the 2-nd warrior dies.

module type Num_caml = sig
  type t
  val zero: t
  val add: t -> t -> t
end

module Prefix_sum (N : Num_caml) = struct
  let compute (src: N.t array): N.t array =
    let t = ref N.zero in
    Array.init (Array.length src) (fun i ->
        t := N.add !t src.(i);
        !t
      )
end

(* spec: find the index of first element with value strictly > v,
 * or length if not found *)
let linear_search_range (v: 'a) (src: 'a array): int =
  let l = Array.length src - 1 in
  let rec f i = if i > l || src.(i) > v then i else f (i + 1) in
  f 0

let bin_search_range (v: 'a) (src: 'a array): int =
  let len = Array.length src in
  let rec f l r =
    if l = r
    then l
    else
      let m = (l + r) / 2 in
      if v > src.(m)
      then f (m + 1) r
      else if v < src.(m)
      then f l m
      else f (m + 1) r
  in
  f 0 len

let test_random_int ?(min: int = 0) ~(max: int): int =
  Random.int (max - min) + min

let test_generate_sorted_array ~(len: int) ~(range: int * int): 'a array =
  let min, max = range in
  let ret = Array.init len (fun _ -> test_random_int ~min ~max) in
  Array.sort compare ret;
  ret

let test_do ?(len: int = 24) ?(range: int * int = (-96, 96)) (): unit =
  let min, max = range in
  let values = test_generate_sorted_array ~len ~range in
  print_string "Test Array:";
  Array.iter (fun i -> Printf.printf " %d" i) values;
  print_newline ();
  for i = 1 to 12 do
    let r = test_random_int ~min ~max in
    Printf.printf "%d " r;
    Printf.printf "%d %d\n"
      (linear_search_range r values)
      (bin_search_range r values);
    flush stdout;
  done

let () =
  (* n - #warrior, q - duration *)
  let open Int64 in
  let n, q = Scanf.scanf " %d %d" (fun n q -> n, q) in
  let hps = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> of_int i)) in
  let arrows = Array.init q (fun _ -> Scanf.scanf " %Ld" (fun i -> i)) in

  let module P = Prefix_sum(Int64) in
  let hpps = P.compute hps in
  (* index of first standing warrior *)
  let total_damage = ref zero in
  for i = 1 to q do
    total_damage := add !total_damage arrows.(i - 1);
    let nlost = bin_search_range !total_damage hpps in
    if nlost = n then total_damage := zero;
    Printf.printf "%d\n" (n - if nlost = n then 0 else nlost)
  done


You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.

Print the answer to this problem in decimal notation modulo $$$998244353$$$.

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

module CumulSumArray = struct
	let make a =
		let ln = Array.length a
		in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1
	let sum l r a = (* 0-origin,closed *)
		(* let l,r = i32 l, i32 r in *)
		if l>r then 0L else (a.(r+$1) - a.(l))
	let sum_1orig l r a = (* codeforces *)
		(* let l,r = i32 l, i32 r in *) sum (l-$1) (r-$1) a
end
let md = 998244353L
let () =
	let _,m = get_2_i64 0 in
	let a,b = scanf " %s %s" (fun u v -> u,v) in
	let b = char_list_of_string b |> List.rev |> List.map (fun c -> (int_of_char c -$ int_of_char '0') |> i64) |> Array.of_list in
	let bsum = Array.fold_left (+) 0L b in
	let bs = CumulSumArray.make b in
	(* dump_array bs; *)
	a |> char_list_of_string |> List.rev
	|> List.fold_left (fun (i,sum,prod) v ->
		if v='1' && i <= i32 m then (
			let q = bsum - bs.(i) in
			(* printf "sum += prod * (bsum - bs.(%d)) = %Ld * %Ld (= %Ld)\n" i prod q (prod*q); *)
			(i+$1,(sum+prod*q)%md,(prod*2L)%md)
		) else (i+$1,sum,(prod*2L)%md)
	) (0,0L,1L)
	|> (fun (_,s,_) -> printf "%Ld\n" s)

	(* for i=String.length a -$1 downto 0 do done *)

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

module CumulSumArray = struct
	let make a =
		let ln = Array.length a
		in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1
	let sum l r a = (* 0-origin,closed *)
		(* let l,r = i32 l, i32 r in *)
		if l>r then 0L else (a.(r+$1) - a.(l))
	let sum_1orig l r a = (* codeforces *)
		(* let l,r = i32 l, i32 r in *) sum (l-$1) (r-$1) a
end
let md = 998244353L
let () =
	let _,_ = get_2_i64 0 in
	let a,b = scanf " %s %s" (fun u v -> u,v) in
	let b = char_list_of_string b |> List.map (fun c -> (int_of_char c -$ int_of_char '0') |> i64) |> Array.of_list in
	let bsum = Array.fold_left (+) 0L b in
	let bs = CumulSumArray.make b in
	a |> char_list_of_string |> List.rev
	|> List.fold_left (fun (i,sum,prod) v ->
		if v='1' then (
			let q = bsum - bs.(i) in
			(* printf "sum += %Ld * %Ld (= %Ld)\n" prod q (prod*q); *)
			(i+$1,(sum%md+prod*q)%md,(prod*2L)%md)
		) else (i+$1,sum,(prod*2L)%md)
	) (0,0L,1L)
	|> (fun (_,s,_) -> printf "%Ld\n" (s%md))

	(* for i=String.length a -$1 downto 0 do done *)


You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";;
let b2i x = if x == true then 1 else 0;;

let n = scan_int() and m = scan_int();;
let a = Array.make n 0 and b = Array.make m (0, 0) and wyn = Array.make m 0;;

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

for i = 0 to m - 1 do
  b.(i) <- (scan_int (), i);
done;

Array.sort compare a; Array.sort compare b;

let cnt = ref 0 and l = ref 0 in

for i = 0 to m - 1 do
  while (!l < n) && a.(!l) <= fst (b.(i)) do
    incr cnt; incr l;
  done;
  wyn.(snd b.(i)) <- !cnt;
done;

for i = 0 to m - 1 do
  print_int(wyn.(i)); psp();
done;

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";;
let b2i x = if x == true then 1 else 0;;

let n = scan_int() and m = scan_int();;
let a = Array.make n 0 and b = Array.make m (0, 0) and wyn = Array.make m 0;;

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

for i = 0 to m - 1 do
  b.(i) <- (scan_int (), i);
done;

Array.fast_sort compare a; Array.fast_sort compare b;

let cnt = ref 0 and l = ref 0 in

for i = 0 to m - 1 do
  while (!l < n) && a.(!l) <= fst (b.(i)) do
    incr cnt; incr l;
  done;
  wyn.(snd b.(i)) <- !cnt;
done;

for i = 0 to m - 1 do
  print_int(wyn.(i)); psp();
done;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = Array.make m 0 in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    for i = 0 to m - 1 do
      b.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a;
    for i = 0 to m - 1 do
      let l = ref (-1)
      and r = ref n in
	while !l < !r - 1 do
	  let m = (!l + !r) / 2 in
	    if a.(m) <= b.(i)
	    then l := m
	    else r := m
	done;
	Printf.printf "%d " !r;
    done;
    Printf.printf "\n"


Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.

The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1 ≤ fi ≤ s, 1 ≤ ti ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.

Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.

NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.

let r2 = Scanf.scanf " %d %d" ;;
let n, s = r2 (fun x y -> (x, y)) ;;

let a = Array.make s 0 ;;
for _ = 1 to n do
    let f, t = r2 (fun x y -> (x-1, y)) in
    a.(f) <- max a.(f) t
done ;;

let rec time f t = match f with
    | 0 -> t
    | f -> time (f-1) (1 + max t a.(f-1) )
;;
print_int @@ time s 0

type passenger = {
    mutable f : int;
    mutable t : int;
};;

(* Echange deux éléments d'un tableau *)
let echange tab i j =
    let z = tab.(i) in
        tab.(i) <- tab.(j);
        tab.(j) <- z;;

(* Quicksort : Sort on the floor of each passenger *)
let partition tab p r =
    let x = tab.(r) in (* Pivot *)
    let i = ref (p - 1) in
        for j = p to r - 1 do
            if tab.(j).f <= x.f then begin
                i := !i + 1 ;
                echange tab !i j
            end
        done ; echange tab (!i + 1) r ;
        (!i + 1);;
let rec quickSort tab p r =
    if p < r then begin
        let q = partition tab p r in
            quickSort tab p (q-1) ;
            quickSort tab (q + 1) r
    end;;

let n, s = Scanf.scanf "%d %d " (fun n' s' -> n', s') in
    let passengers = Array.init n (fun _i ->
        let pass_f, pass_t = Scanf.scanf "%d %d " (fun f' t' -> f', t') in
            {f = pass_f ; t = pass_t}
    ) in
        quickSort passengers 0 (n-1) ;
        let time = ref 0 in
        let floor = ref s in
            for i = 0 to (n-1) do
                time := !time + (!floor - (passengers.(i).f)); (* Temps de descente *)
                floor := passengers.(i).f;
                if !time < passengers.(i).t then
                    time := !time + (passengers.(i).t - !time) (* Temps d'attente *)
            done ;
            time := !time + !floor ; (* On descend tout en bas *)
            print_int !time;;

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let s = read_int () in
  let pass = Array.init n (fun _ -> read_pair()) in
  let arrive = Array.make (s+1) 0 in

  for i=0 to n-1 do
    let (f,t) = pass.(i) in
    arrive.(f) <- max arrive.(f) t
  done;

  let rec loop floor time = if floor = 0 then time else
  (* at floor arrive at time *)
      let time = max time arrive.(floor) in
      loop (floor-1) (time+1)
  in

  printf "%d\n" (loop s 0)


For an array $$$b$$$ of length $$$m$$$ we define the function $$$f$$$ as  $$$ f(b) = \begin{cases} b[1] & \quad \text{if } m = 1 \\ f(b[1] \oplus b[2],b[2] \oplus b[3],\dots,b[m-1] \oplus b[m]) & \quad \text{otherwise,} \end{cases} $$$ where $$$\oplus$$$ is bitwise exclusive OR.For example, $$$f(1,2,4,8)=f(1\oplus2,2\oplus4,4\oplus8)=f(3,6,12)=f(3\oplus6,6\oplus12)=f(5,10)=f(5\oplus10)=f(15)=15$$$You are given an array $$$a$$$ and a few queries. Each query is represented as two integers $$$l$$$ and $$$r$$$. The answer is the maximum value of $$$f$$$ on all continuous subsegments of the array $$$a_l, a_{l+1}, \ldots, a_r$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 2^{30}-1$$$) — the elements of the array. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 100\,000$$$) — the number of queries. Each of the next $$$q$$$ lines contains a query represented as two integers $$$l$$$, $$$r$$$ ($$$1 \le l \le r \le n$$$).

Print $$$q$$$ lines — the answers for the queries.

NoteIn first sample in both queries the maximum value of the function is reached on the subsegment that is equal to the whole segment.In second sample, optimal segment for first query are $$$[3,6]$$$, for second query — $$$[2,5]$$$, for third — $$$[3,4]$$$, for fourth — $$$[1,2]$$$.

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";; let pnl () = print_newline ();;
let b2i x = if x == true then 1 else 0;;
let dbg x = print_int(x); pnl();;

let n = scan_int();;
let a = Array.init n (fun i -> scan_int());;

let f = Array.make_matrix n n 0 and wyn = Array.make_matrix n n 0;;
for i = 0 to (n - 1) do
  f.(i).(i) <- a.(i);
  wyn.(i).(i) <- a.(i);
done;;

for i = 2 to n do
  for j = 0 to (n - i) do
    let r = j + i - 1 in
    f.(j).(r) <- f.(j + 1).(r) lxor f.(j).(r - 1);
    wyn.(j).(r) <- max (f.(j).(r)) (max wyn.(j+1).(r) wyn.(j).(r - 1));
  done;
done;;

let q = scan_int();;
for i = 1 to q do
  let a = scan_int() and b = scan_int() in
  print_int(wyn.(a - 1).(b - 1)); pnl();
done;;

open Printf
open Scanf

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

let build_answer n b =
  let v = Array.make_matrix n n 0 in
  for i=0 to n-1 do
    v.(i).(i) <- b.(i)
  done;

  for d=2 to n do
    for l=0 to n-d do
      let r = l+d-1 in
      v.(l).(r) <- v.(l+1).(r) lxor v.(l).(r-1)
    done
  done;

  for r=1 to n-1 do
    for l=r-1 downto 0 do
      v.(l).(r) <- max v.(l).(r) v.(l+1).(r)
    done
  done;

  for r=1 to n-1 do
    for l=r-1 downto 0 do
      v.(l).(r) <- max v.(l).(r) v.(l).(r-1)
    done
  done;

  v

let () =
  let n = read_int () in
  let b = Array.init n read_int in
  let q = read_int () in

  let v = build_answer n b in

  for i=1 to q do
    let l = read_int() -1 in
    let r = read_int() -1 in
    printf "%d\n" v.(l).(r)
  done

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";; let pnl () = print_newline ();;
let b2i x = if x == true then 1 else 0;;
let dbg x = print_int(x); pnl();;

let n = scan_int();;
let a = Array.init n (fun i -> scan_int());;

let f = Array.make_matrix n n 0 and wyn = Array.make_matrix n n 0;;
for i = 0 to (n - 1) do
  f.(i).(i) <- a.(i);
  wyn.(i).(i) <- a.(i);
done;;

for i = 2 to n do
  for j = 0 to (n - i) do
    let r = j + i - 1 in
    f.(j).(r) <- f.(j + 1).(r) lxor f.(j).(r - 1);
    wyn.(j).(r) <- max f.(j).(r) (max f.(j+1).(r) f.(j).(r - 1));
  done;
done;;

let q = scan_int();;
for i = 1 to q do
  let a = scan_int() and b = scan_int() in
  print_int(wyn.(a - 1).(b - 1)); pnl();
done;;


Let's call some positive integer classy if its decimal representation contains no more than $$$3$$$ non-zero digits. For example, numbers $$$4$$$, $$$200000$$$, $$$10203$$$ are classy and numbers $$$4231$$$, $$$102306$$$, $$$7277420000$$$ are not.You are given a segment $$$[L; R]$$$. Count the number of classy integers $$$x$$$ such that $$$L \le x \le R$$$.Each testcase contains several segments, for each of them you are required to solve the problem separately.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of segments in a testcase. Each of the next $$$T$$$ lines contains two integers $$$L_i$$$ and $$$R_i$$$ ($$$1 \le L_i \le R_i \le 10^{18}$$$).

Print $$$T$$$ lines — the $$$i$$$-th line should contain the number of classy integers on a segment $$$[L_i; R_i]$$$.

let rec range ?(left: int = 0) (right: int): int list =
	if left >= right then [] else left :: range ~left:(left + 1) right

let split_on_space (str: string): string list =
	let length = String.length str in
	let is_space: int -> bool =
		fun index ->
			if (index < 0) || (index >= length) then true
			else str.[index] = ' '
	in
	let is_start: int -> bool =
		fun index -> not (is_space index) && is_space (index - 1)
	in
	let is_end: int -> bool =
		fun index -> not (is_space index) && is_space (index + 1)
	in
	let indices = range length in
	let start_pos = List.filter is_start indices in
	let end_pos = List.filter is_end indices in
	let make_substring: string list -> int -> int -> string list =
		fun tokens left right ->
			let new_token = String.sub str left (right - left + 1) in
			new_token :: tokens
	in
	let tokens = List.fold_left2 make_substring [] start_pos end_pos in
	List.rev tokens

class reader channel =
	object (this)

	val mutable tokens = []

  method private get_tokens () =
    let new_line = read_line () in
    let tokens = split_on_space new_line in
    match tokens with
    | [] -> this#get_tokens ()
    | _ -> tokens

	method next_string () =
    if (List.length tokens = 0) then tokens <- this#get_tokens();
    let result = List.hd tokens in
    tokens <- List.tl tokens; result

  method next_int () =
    let str = this#next_string() in (Int64.of_string) str

  method next_float () =
    let str = this#next_string() in (float_of_string) str

end

let reader = new reader stdin

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

let get_digits (number: int64): int array =
	let char_to_int: char -> int =
		fun c -> (Char.code c) - (Char.code '0')
	in
	let str = Int64.to_string number in
	let num_digit = String.length str in
	Array.init num_digit (fun index -> char_to_int str.[num_digit - index - 1])

let rec count_number (left: int64) (right: int64): int64 =
	if right < left then Int64.zero else
		if left > Int64.zero then (count_number Int64.zero right) -. (count_number Int64.zero (left -. Int64.one)) else
			let digits = get_digits right in
			let num_digit = Array.length digits in

			let init_1d: int -> int64 = fun _ -> Int64.zero in
			let init_2d: int -> int64 array = fun _ -> Array.init 2 init_1d in
			let init_3d: int -> int64 array array = fun _ -> Array.init 4 init_2d in
			let f: int64 array array array = Array.init (num_digit + 1) init_3d in
			f.(0).(0).(1) <- Int64.one;

			let pos_range = range num_digit in
			let used_range = range 4 in
			let comp_range = range 2 in
			let next_range = range 10 in

			List.iter (fun pos ->
				List.iter (fun used ->
					List.iter (fun comp ->
						let cur = f.(pos).(used).(comp) in
						if cur > Int64.zero then
							List.iter (fun next ->
								let used' = if next = 0 then used else used + 1 in
								let comp' = if next = digits.(pos) then comp else
									if next < digits.(pos) then 1 else 0
								in
								if used' <= 3 then
									f.(pos + 1).(used').(comp') <- f.(pos + 1).(used').(comp') +. cur
								) next_range
						) comp_range
					) used_range
				) pos_range;

			List.fold_left (fun sum used -> sum +. f.(num_digit).(used).(1) ) Int64.zero used_range

let () =
	let q = reader#next_int () in
	let q = Int64.to_int q in
	for i = 1 to q do
		let l = reader#next_int () in
		let r = reader#next_int () in
		let res = count_number l r in
		print_endline (Int64.to_string res)
	done


There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too.Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from li to ri. Wet Shark has it's favourite prime number p, and he really likes it! If for any pair of neighbouring sharks i and j the product si·sj is divisible by p, then Wet Shark becomes happy and gives 1000 dollars to each of these sharks.At the end of the day sharks sum all the money Wet Shark granted to them. Find the expectation of this value.

The first line of the input contains two space-separated integers n and p (3 ≤ n ≤ 100 000, 2 ≤ p ≤ 109) — the number of sharks and Wet Shark's favourite prime number. It is guaranteed that p is prime. The i-th of the following n lines contains information about i-th shark — two space-separated integers li and ri (1 ≤ li ≤ ri ≤ 109), the range of flowers shark i can produce. Remember that si is chosen equiprobably among all integers from li to ri, inclusive.

Print a single real number — the expected number of dollars that the sharks receive in total. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteA prime number is a positive integer number that is divisible only by 1 and itself. 1 is not considered to be prime.Consider the first sample. First shark grows some number of flowers from 1 to 2, second sharks grows from 420 to 421 flowers and third from 420420 to 420421. There are eight cases for the quantities of flowers (s0, s1, s2) each shark grows: (1, 420, 420420): note that s0·s1 = 420, s1·s2 = 176576400, and s2·s0 = 420420. For each pair, 1000 dollars will be awarded to each shark. Therefore, each shark will be awarded 2000 dollars, for a total of 6000 dollars. (1, 420, 420421): now, the product s2·s0 is not divisible by 2. Therefore, sharks s0 and s2 will receive 1000 dollars, while shark s1 will receive 2000. The total is 4000. (1, 421, 420420): total is 4000  (1, 421, 420421): total is 0.  (2, 420, 420420): total is 6000.  (2, 420, 420421): total is 6000.  (2, 421, 420420): total is 6000. (2, 421, 420421): total is 4000.The expected value is .In the second sample, no combination of quantities will garner the sharks any money.

open Printf
open Scanf

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

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac +. (f i))

let ceil a b = (a ++ b -- 1L) // b
let floor a b = a // b
let float = Int64.to_float

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

let () =
  let n = read_int () in
  let p = long(read_int()) in
  let range = Array.init n (fun _ -> read_pair()) in

  let prob_p_divides i =
    let (l,r) = range.(i) in
    let len = r -- l ++ 1L in
    let first = (ceil l p) ** p in
    let last = (floor r p) ** p in
    if last < first then 0.0 else (
      (float ((last -- first)//p ++ 1L)) /. (float len)
    )
  in

  let exp2 i =
    let j = (i+1) mod n in
    let pri = prob_p_divides i in
    let prj = prob_p_divides j in
    2000.0 *. pri *. prj +.
    2000.0 *. pri *. (1.0 -. prj) +.
    2000.0 *. (1.0 -. pri) *. prj
  in

  printf "%.8f\n" (sum 0 (n-1) exp2 0.0)


In the school computer room there are n servers which are responsible for processing several computing tasks. You know the number of scheduled tasks for each server: there are mi tasks assigned to the i-th server.In order to balance the load for each server, you want to reassign some tasks to make the difference between the most loaded server and the least loaded server as small as possible. In other words you want to minimize expression ma - mb, where a is the most loaded server and b is the least loaded one.In one second you can reassign a single task. Thus in one second you can choose any pair of servers and move a single task from one server to another.Write a program to find the minimum number of seconds needed to balance the load of servers.

The first line contains positive number n (1 ≤ n ≤ 105) — the number of the servers.  The second line contains the sequence of non-negative integers m1, m2, ..., mn (0 ≤ mi ≤ 2·104), where mi is the number of tasks assigned to the i-th server.

Print the minimum number of seconds required to balance the load.

NoteIn the first example two seconds are needed. In each second, a single task from server #2 should be moved to server #1. After two seconds there should be 3 tasks on server #1 and 4 tasks on server #2.In the second example the load is already balanced.A possible sequence of task movements for the third example is:  move a task from server #4 to server #1 (the sequence m becomes: 2 2 3 3 5);  then move task from server #5 to server #1 (the sequence m becomes: 3 2 3 3 4);  then move task from server #5 to server #2 (the sequence m becomes: 3 3 3 3 3). The above sequence is one of several possible ways to balance the load of servers in three seconds.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0L in
  let s = ref 0L in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s);
      s := !s +| a.(i);
    done;
    Array.sort compare a;
    let ma = !s /| Int64.of_int n in
    let mb =
      ma +| if ma *| Int64.of_int n = !s then 0L else 1L
    in
    let x = ref 0L in
    let y = ref 0L in
      for i = 0 to n - 1 do
	if a.(i) < ma
	then x := !x +| ma -| a.(i)
	else if a.(i) > mb
	then y := !y +| a.(i) -| mb
      done;
      let res = max !x !y in
      Printf.printf "%Ld\n" res

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let ( ++ ) a b = Int64.add a b
let ( ** ) a b = Int64.mul 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 sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))

let () =

  let n = read_int() in
  let nn = long n in
  let m = Array.init n (fun _ -> long (read_int())) in
  let s = sum 0 (n-1) (fun i -> m.(i)) 0L in

  let p = s//nn in
  let q = (s++(nn--1L)) // nn in

  let total_above_q = sum 0 (n-1) (fun i -> max 0L (m.(i) -- q)) 0L in
  let total_below_p = sum 0 (n-1) (fun i -> max 0L (p -- m.(i))) 0L in

  printf "%Ld\n" (max total_above_q total_below_p)

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let ( ++ ) a b = Int64.add a b
let ( ** ) a b = Int64.mul 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 sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))

let () =

  let n = read_int() in
  let nn = long n in
  let m = Array.init n (fun _ -> long (read_int())) in
  let s = sum 0 (n-1) (fun i -> m.(i)) 0L in

  let p = s//nn in
  let q = (s++(nn--1L)) // nn in

  let total_above_q = sum 0 (n-1) (fun i -> max 0L (m.(i) -- q)) 0L in
  let total_below_p = sum 0 (n-1) (fun i -> min 0L (p -- m.(i))) 0L in

  printf "%Ld\n" (max total_above_q total_below_p)


Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.

The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence.  The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105).

Print a single integer — the maximum number of points that Alex can earn.

NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points.

let ( + ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( * ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( - ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( / ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( ~- ) : 'a -> 'a -> 'a = fun x y -> assert false

let pf = Printf.printf

let epf = Printf.eprintf

let sf = Scanf.scanf

let ( |> ) x f = f x

let ( @@ ) f x = f x

module Array = ArrayLabels

module List =
  struct
    include ListLabels

    let rec repeat n a =
      if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)

    let rec drop n a =
      if n = 0
      then a
      else
        (match a with
         | [] -> failwith "cannot take"
         | x :: xs -> drop (Pervasives.( - ) n 1) xs)

  end

module H = Hashtbl

let solve n arr =
  (Array.sort ~cmp: compare arr;
   let prev = ref arr.(0) in
   let cnt = ref 1L in
   let ls = ref []
   in
     (for i = 1 to Pervasives.( - ) n 1 do
        if !prev = arr.(i)
        then cnt := Int64.add !cnt 1L
        else (ls := ((!prev), (!cnt)) :: !ls; prev := arr.(i); cnt := 1L)
      done;
      ls := ((!prev), (!cnt)) :: !ls;
      let arr = Array.of_list !ls in
      let n = Array.length arr
      in
        (Array.iter arr ~f: (fun (v, c) -> epf "(%Ld, %Ld), " v c);
         epf "\n";
         let mul (x, y) = Int64.mul (x : int64) y in
         let memo = H.create 10 in
         let rec iter i =
           if i = n
           then 0L
           else
             if i = (Pervasives.( - ) n 1)
             then mul arr.(i)
             else
               if H.mem memo i
               then H.find memo i
               else
                 if
                   (Int64.sub (fst arr.(i)) 1L) =
                     (fst arr.(Pervasives.( + ) i 1))
                 then
                   (let v =
                      max
                        (Int64.add (iter (Pervasives.( + ) i 2))
                           (mul arr.(i)))
                        (iter (Pervasives.( + ) i 1))
                    in (H.add memo i v; v))
                 else
                   (let v =
                      Int64.add (mul arr.(i)) (iter (Pervasives.( + ) i 1))
                    in (H.add memo i v; v))
         in (pf "%Ld\n") @@ (iter 0))))

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

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

let list_init n f =
    let rec loop i list =
        if i < n
        then
            let element = f(i) in
            loop (i + 1) (element :: list)
        else
            List.rev list
    in loop 0 []

let count list =
    let rec loop count acc = function
        | a :: (b :: _ as tl) -> if a = b then loop (count + 1) acc tl
                                    else loop 0 ((a, count + 1) :: acc) tl
        | [x] -> (x, count + 1) :: acc
        | [] -> []
    in List.rev (loop 0 [] list)

let multiply list = List.map (fun (x, n) -> (x, Int64.mul (Int64.of_int x) (Int64.of_int n))) list

let score list =
    let rec loop prev sum_if_prev_taken sum_if_prev_skipped rest =
        let sum_if_unconstrained = Pervasives.max sum_if_prev_taken sum_if_prev_skipped in
        match rest with
        | [] -> sum_if_unconstrained
        | (a, v) :: tl ->
            let sum_if_a_taken =
                if a - 1 = prev
                then
                    Int64.add v sum_if_prev_skipped
                else
                    Int64.add v sum_if_unconstrained
            in
            let sum_if_a_skipped = sum_if_unconstrained in
            loop a sum_if_a_taken sum_if_a_skipped tl
    in loop (-1) 0L 0L list

let input () =
    let n = read () in
    let numbers = List.sort (Pervasives.compare) (list_init n (fun i -> read ())) in
    (numbers, n)

let solve (numbers, n) =
    let score = score (multiply (count numbers)) in
    score

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

open Scanf;;
open String;;
open Printf;;
open Num;;

let n = bscanf Scanning.stdin "%d " (fun x -> x);;

let nn = 100000 + 5;;
let count = Array.make nn (num_of_int 0);;
let indx = Array.make nn 0;;
let score = Array.make nn (num_of_int 0);;

let p = Array.init n (fun x -> 0);;

for i=0 to n-1 do
  let  f = bscanf Scanning.stdin "%d " (fun x -> x)  in
  count.(f) <- count.(f) +/ (num_of_int f)
done;;

let l = ref 1;;

for i=1 to nn-1 do
  if count.(i) >/ num_of_int 0 then
    begin
      indx.(!l) <- i;
      l := !l + 1
    end
done;;

(*For testing
for i=1 to !l-1 do
  printf "%d %d\n" indx.(i) count.(indx.(i));
done;;*)

score.(0) <- num_of_int 0;;
score.(1) <- count.(indx.(1));;
let cur_indx = ref indx.(1) in
for i=2 to !l-1 do
  let x1 = !cur_indx in
  let x2 = indx.(i) in
  if x2 > x1 + 1 then
    begin
      score.(i)<-score.(i-1) +/  count.(x2);
      cur_indx := indx.(i)
    end
  else
    begin
      let tscore = score.(i-2) +/ count.(x2) in
      if tscore >/ score.(i-1) then
        begin
          score.(i) <- tscore;
          cur_indx := x2
        end
      else
        begin
          score.(i) <- score.(i-1);
          cur_indx := indx.(i-1)
        end
    end
done;;

print_endline (string_of_num (score.(!l-1)));;

let ( + ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( * ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( - ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( / ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( ~- ) : 'a -> 'a -> 'a = fun x y -> assert false

let pf = Printf.printf

let epf = Printf.eprintf

let sf = Scanf.scanf

let ( |> ) x f = f x

let ( @@ ) f x = f x

module Array = ArrayLabels

module List =
  struct
    include ListLabels

    let rec repeat n a =
      if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)

    let rec drop n a =
      if n = 0
      then a
      else
        (match a with
         | [] -> failwith "cannot take"
         | x :: xs -> drop (Pervasives.( - ) n 1) xs)

  end

module H = Hashtbl

let solve n arr =
  (Array.sort ~cmp: compare arr;
   let prev = ref arr.(0) in
   let cnt = ref 1L in
   let ls = ref []
   in
     (for i = 1 to Pervasives.( - ) n 1 do
        if !prev = arr.(i)
        then cnt := Int64.add !cnt 1L
        else (ls := ((!prev), (!cnt)) :: !ls; prev := arr.(i); cnt := 1L)
      done;
      ls := ((!prev), (!cnt)) :: !ls;
      let arr = Array.of_list !ls in
      let n = Array.length arr
      in
        (Array.iter arr ~f: (fun (v, c) -> epf "(%Ld, %Ld), " v c);
         epf "\n";
         let mul (x, y) = Int64.mul (x : int64) y in
         let memo = H.create 10 in
         let rec iter i =
           if i = n
           then 0L
           else
             if i = (Pervasives.( - ) n 1)
             then mul arr.(i)
             else
               if H.mem memo i
               then H.find memo i
               else
                 if
                   (Int64.sub (fst arr.(i)) 1L) =
                     (fst arr.(Pervasives.( + ) i 1))
                 then
                   (let v =
                      max
                        (Int64.add (iter (Pervasives.( + ) i 2))
                           (mul arr.(i)))
                        (iter (Pervasives.( + ) i 1))
                    in (H.add memo i v; v))
                 else
                   (let v =
                      Int64.add (mul arr.(i)) (iter (Pervasives.( + ) i 2))
                    in (H.add memo i v; v))
         in (pf "%Ld\n") @@ (iter 0))))

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

let ( + ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( * ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( - ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( / ) : 'a -> 'a -> 'a = fun x y -> assert false

let ( ~- ) : 'a -> 'a -> 'a = fun x y -> assert false

let pf = Printf.printf

let epf = Printf.eprintf

let sf = Scanf.scanf

let ( |> ) x f = f x

let ( @@ ) f x = f x

module Array = ArrayLabels

module List =
  struct
    include ListLabels

    let rec repeat n a =
      if n = 0 then [] else a :: (repeat (Pervasives.( - ) n 1) a)

    let rec drop n a =
      if n = 0
      then a
      else
        (match a with
         | [] -> failwith "cannot take"
         | x :: xs -> drop (Pervasives.( - ) n 1) xs)

  end

module H = Hashtbl

let solve n arr =
  (Array.sort ~cmp: compare arr;
   let prev = ref arr.(0) in
   let cnt = ref 1L in
   let ls = ref []
   in
     (for i = 1 to Pervasives.( - ) n 1 do
        if !prev = arr.(i)
        then cnt := Int64.add !cnt 1L
        else (ls := ((!prev), (!cnt)) :: !ls; prev := arr.(i); cnt := 1L)
      done;
      ls := ((!prev), (!cnt)) :: !ls;
      let arr = Array.of_list !ls in
      let n = Array.length arr
      in
        (Array.iter arr ~f: (fun (v, c) -> epf "(%Ld, %Ld), " v c);
         epf "\n";
         let mul (x, y) = Int64.mul (x : int64) y in
         let memo = H.create 10 in
         let rec iter i =
           if i = n
           then 0L
           else
             if i = (Pervasives.( - ) n 1)
             then mul arr.(i)
             else
               if H.mem memo i
               then H.find memo i
               else
                 if
                   (Int64.sub (fst arr.(i)) 1L) =
                     (fst arr.(Pervasives.( + ) i 1))
                 then
                   (let v =
                      max
                        (Int64.add (iter (Pervasives.( + ) i 2))
                           (mul arr.(i)))
                        (iter (Pervasives.( + ) i 1))
                    in (H.add memo i v; v))
                 else
                   (let v =
                      Int64.add
                        (Int64.add (mul arr.(i))
                           (mul arr.(Pervasives.( + ) i 1)))
                        (iter (Pervasives.( + ) i 2))
                    in (H.add memo i v; v))
         in (pf "%Ld\n") @@ (iter 0))))

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

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

let list_init n f =
    let rec loop i list =
        if i < n
        then
            let element = f(i) in
            loop (i + 1) (element :: list)
        else
            List.rev list
    in loop 0 []

let count list =
    let rec loop count acc = function
        | a :: (b :: _ as tl) -> if a = b then loop (count + 1) acc tl
                                    else loop 0 ((a, count + 1) :: acc) tl
        | [x] -> (x, count + 1) :: acc
        | [] -> []
    in List.rev (loop 0 [] list)

let multiply list = List.map (fun (x, n) -> (x, x * n)) list

let score list =
    let rec loop prev sum_if_prev_taken sum_if_prev_skipped rest =
        let sum_if_unconstrained = Pervasives.max sum_if_prev_taken sum_if_prev_skipped in
        match rest with
        | [] -> sum_if_unconstrained
        | (a, v) :: tl ->
            let sum_if_a_taken =
                if a - 1 = prev
                then
                    v + sum_if_prev_skipped
                else
                    v + sum_if_unconstrained
            in
            let sum_if_a_skipped = sum_if_unconstrained in
            loop a sum_if_a_taken sum_if_a_skipped tl
    in loop (-1) 0 0 list

let input () =
    let n = read () in
    let numbers = List.sort (Pervasives.compare) (list_init n (fun i -> read ())) in
    (numbers, n)

let solve (numbers, n) =
    let score = score (multiply (count numbers)) in
    score

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

open Scanf;;
open String;;
open Printf;;

let n = bscanf Scanning.stdin "%d " (fun x -> x);;

let nn = 100000 + 2;;
let count = Array.make nn 0;;
let indx = Array.make nn 0;;
let score = Array.make nn 0;;

let p = Array.init n (fun x -> 0);;

for i=0 to n-1 do
  let  f = bscanf Scanning.stdin "%d " (fun x -> x)  in
  count.(f) <- count.(f) + f
done;;

let l = ref 1;;

for i=1 to nn-1 do
  if count.(i) > 0 then
    begin
      indx.(!l) <- i;
      l := !l + 1
    end
done;;

(* For testing
for i=1 to !l-1 do
  printf "%d %d\n" indx.(i) count.(indx.(i));
done;;
*)

score.(0) <- 0;;
score.(1) <- count.(indx.(1));;
for i=2 to !l-1 do
  let x1 = indx.(i-1) in
  let x2 = indx.(i) in
  if x2 > x1 + 1 then
    begin
      score.(i)<-score.(i+1)+count.(x2)
    end
  else
    begin
      let tscore = score.(i-2) + count.(x2) in
      if tscore > score.(i-1) then
        score.(i) <- tscore
      else
        score.(i) <- score.(i-1)
    end
done;;

print_int score.(!l-1); print_endline "";;

open Scanf;;
open String;;
open Printf;;
open Num;;

let n = bscanf Scanning.stdin "%d " (fun x -> x);;

let nn = 100000 + 2;;
let count = Array.make nn 0;;
let indx = Array.make nn 0;;
let score = Array.make nn (num_of_int 0);;

let p = Array.init n (fun x -> 0);;

for i=0 to n-1 do
  let  f = bscanf Scanning.stdin "%d " (fun x -> x)  in
  count.(f) <- count.(f) + f
done;;

let l = ref 1;;

for i=1 to nn-1 do
  if count.(i) > 0 then
    begin
      indx.(!l) <- i;
      l := !l + 1
    end
done;;

(*For testing
for i=1 to !l-1 do
  printf "%d %d\n" indx.(i) count.(indx.(i));
done;;*)

score.(0) <- num_of_int 0;;
score.(1) <- num_of_int count.(indx.(1));;
let cur_indx = ref indx.(1) in
for i=2 to !l-1 do
  let x1 = !cur_indx in
  let x2 = indx.(i) in
  if x2 > x1 + 1 then
    begin
      score.(i)<-score.(i-1)+/ (num_of_int count.(x2));
      cur_indx := indx.(i)
    end
  else
    begin
      let tscore = score.(i-2) +/ num_of_int (count.(x2)) in
      if tscore >/ score.(i-1) then
        begin
          score.(i) <- tscore;
          cur_indx := x2
        end
      else
        begin
          score.(i) <- score.(i-1);
          cur_indx := indx.(i-1)
        end
    end
done;;

print_endline (string_of_num (score.(!l-1)));;

open Scanf;;
open String;;
open Printf;;

let n = bscanf Scanning.stdin "%d " (fun x -> x);;

let nn = 100000 + 2;;
let count = Array.make nn 0;;
let indx = Array.make nn 0;;
let score = Array.make nn 0;;

let p = Array.init n (fun x -> 0);;

for i=0 to n-1 do
  let  f = bscanf Scanning.stdin "%d " (fun x -> x)  in
  count.(f) <- count.(f) + f
done;;

let l = ref 1;;

for i=1 to nn-1 do
  if count.(i) > 0 then
    begin
      indx.(!l) <- i;
      l := !l + 1
    end
done;;

(*For testing
for i=1 to !l-1 do
  printf "%d %d\n" indx.(i) count.(indx.(i));
done;;*)

score.(0) <- 0;;
score.(1) <- count.(indx.(1));;
let cur_indx = ref indx.(1) in
for i=2 to !l-1 do
  let x1 = !cur_indx in
  let x2 = indx.(i) in
  if x2 > x1 + 1 then
    begin
      score.(i)<-score.(i-1)+count.(x2);
      cur_indx := indx.(i)
    end
  else
    begin
      let tscore = score.(i-2) + count.(x2) in
      if tscore > score.(i-1) then
        begin
          score.(i) <- tscore;
          cur_indx := x2
        end
      else
        begin
          score.(i) <- score.(i-1);
          cur_indx := indx.(i-1)
        end
    end
done;;

print_int score.(!l-1); print_endline "";;


Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the power of the stones.

For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int () in
    let a = Array.init n read_int in

    let (_,max_loc) = maxf 0 (n-1) (fun i -> (a.(i), i)) in
    let (_,min_loc) = minf 0 (n-1) (fun i -> (a.(i), i)) in

    let ltor = 1 + max max_loc min_loc in
    let rtol = max (n-max_loc) (n-min_loc) in
    let both_ends = (1 + min max_loc min_loc) + (min (n-max_loc) (n-min_loc)) in

    printf "%d\n" (min ltor (min rtol both_ends))
  done


Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.

The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix. The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i. The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i.

If there is no matrix satisfying the given constraints in the first line, output "NO". Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0L in
  let b = Array.make m 0L in
  let c = Array.make_matrix n m 0L in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
    for j = 0 to m - 1 do
      b.(j) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
  in
  let x = ref 0L in
  let y = ref 0L in
    for i = 0 to n - 1 do
      x := Int64.logxor !x a.(i)
    done;
    for i = 0 to m - 1 do
      y := Int64.logxor !y b.(i)
    done;
    if !x <> !y
    then Printf.printf "NO\n"
    else (
      c.(0).(0) <- Int64.logxor !x (Int64.logxor a.(0) b.(0));
      for i = 1 to n - 1 do
	c.(i).(0) <- a.(i)
      done;
      for j = 1 to m - 1 do
	c.(0).(j) <- b.(j)
      done;
      Printf.printf "YES\n";
      for i = 0 to n - 1 do
	for j = 0 to m - 1 do
	  Printf.printf "%Ld " c.(i).(j)
	done;
	Printf.printf "\n"
      done;
    )

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0L in
  let b = Array.make m 0L in
  let c = Array.make_matrix n m 0L in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
    for j = 0 to m - 1 do
      b.(j) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
  in
  let x = ref 0L in
  let y = ref 0L in
    for i = 0 to n - 1 do
      x := Int64.logxor !x a.(i)
    done;
    for i = 0 to m - 1 do
      y := Int64.logxor !y b.(i)
    done;
    if !x <> !y
    then Printf.printf "NO\n"
    else (
      c.(0).(0) <- Int64.logxor !x (Int64.logxor a.(0) b.(0));
      for i = 1 to n - 1 do
	c.(i).(0) <- a.(i)
      done;
      for j = 1 to m - 1 do
	c.(0).(j) <- b.(j)
      done;
      for i = 0 to n - 1 do
	for j = 0 to m - 1 do
	  Printf.printf "%Ld " c.(i).(j)
	done;
	Printf.printf "\n"
      done;
    )


The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.

The first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 10 000) — the number of teams that will be present on each of the days.

If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).

NoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days.

let read_nums () =
    let s = read_line () in
    let nums = List.map int_of_string (Str.split (Str.regexp " ") s) in
    nums

;;

let rec is_possible lst =
    match lst with
        | [] -> true
        | [a] -> (a mod 2 = 0)
        | a :: b :: tl -> if a < 0 then
                            false
                          else if a mod 2 = 0 then
                            is_possible (b::tl)
                          else
                            is_possible ((b-1)::tl)
;;

let main () =
    let _n = read_int () in
    let lst = read_nums () in
    if is_possible lst then
        print_string "YES\n"
    else
        print_string "NO\n"
;;

main () ;;

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

let () =
  let n = read_int () in
  let data = Array.init n (fun i ->
      if i = 0 then read_int () mod 2
      else read_int ()
    )
  in
  let possible = ref "YES" in
  let reminder = ref 0 in
  for i = 0 to n - 1 do
    let r = data.(i) - !reminder in
    if r < 0 || i = n - 1 && r mod 2 != 0
    then possible := "NO"
    else reminder := r mod 2
  done;
  print_endline !possible

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

let () =
  let n = read_int () in
  let data = Array.init n (fun i ->
      if i = 0 then read_int () mod 2
      else read_int ()
    )
  in
  let possible = ref "YES" in
  let init = data.(0) in
  let reminder = ref init in
  for i = 1 to n - 1 do
    let r = data.(i) - !reminder in
    if r < 0 || i = n - 1 && data.(i) mod 2 != 0
    then possible := "NO"
    else reminder := data.(i) mod 2
  done;
  print_endline !possible

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

let () =
  let n = read_int () in
  let data = Array.init n (fun i ->
      if i = 0 then read_int () mod 2
      else read_int ()
    )
  in
  let possible = ref "YES" in
  let init = data.(0) in
  let reminder = ref init in
  for i = 1 to n - 1 do
    let r = data.(i) - !reminder in
    if r < 0 || i = n - 1 && data.(i) != 0
    then possible := "NO"
    else reminder := data.(i) mod 2
  done;
  print_endline !possible


This problem differs from one which was on the online contest.The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.

The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.

In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.

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

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let m = read_int 0 in
  let b = Array.init m read_int in
  let s = Array.make_matrix n m 0 in
  let p = Array.make_matrix n m m in
  let rec go i j optl opti optx =
    if i >= 0 then
      if j < 0 then
        go (i-1) (m-1) 0 m (-1)
      else (
        if i+1 < n then (
          s.(i).(j) <- s.(i+1).(j);
          p.(i).(j) <- p.(i+1).(j);
        );
        if a.(i) = b.(j) && optl+1 > s.(i).(j) then (
          s.(i).(j) <- optl+1;
          p.(i).(j) <- opti;
        );
        let optl',opti',optx' = if i+1 < n && a.(i) < b.(j) && (s.(i).(j) > optl || s.(i).(j) = optl && b.(j) <= optx) then
            s.(i).(j),j,b.(j)
          else
            optl,opti,optx in
        go i (j-1) optl' opti' optx'
      )
  in
  go (n-1) (m-1) 0 m (-1);

  let rec plan i j =
    if i < n && j < m then
      if a.(i) <> b.(j) then
        plan (i+1) j
      else (
        Printf.printf "%d " a.(i);
        plan (i+1) p.(i).(j)
      )
  in
  let rec find i opt opti =
    if i >= m then (
      Printf.printf "%d\n" opt;
      plan 0 opti
    ) else if s.(0).(i) > opt then
      find (i+1) s.(0).(i) i
    else
      find (i+1) opt opti
  in
  find 0 0 m