It's the year 4527 and the tanks game that we all know and love still exists. There also exists Great Gena's code, written in 2016. The problem this code solves is: given the number of tanks that go into the battle from each country, find their product. If it is turns to be too large, then the servers might have not enough time to assign tanks into teams and the whole game will collapse!There are exactly n distinct countries in the world and the i-th country added ai tanks to the game. As the developers of the game are perfectionists, the number of tanks from each country is beautiful. A beautiful number, according to the developers, is such number that its decimal representation consists only of digits '1' and '0', moreover it contains at most one digit '1'. However, due to complaints from players, some number of tanks of one country was removed from the game, hence the number of tanks of this country may not remain beautiful.Your task is to write the program that solves exactly the same problem in order to verify Gena's code correctness. Just in case.

The first line of the input contains the number of countries n (1 ≤ n ≤ 100 000). The second line contains n non-negative integers ai without leading zeroes — the number of tanks of the i-th country. It is guaranteed that the second line contains at least n - 1 beautiful numbers and the total length of all these number's representations doesn't exceed 100 000.

Print a single number without leading zeroes — the product of the number of tanks presented by each country.

NoteIn sample 1 numbers 10 and 1 are beautiful, number 5 is not not.In sample 2 number 11 is not beautiful (contains two '1's), all others are beautiful.In sample 3 number 3 is not beautiful, all others are beautiful.

open Printf
open Scanf

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

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

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

let iszero s first last = forall first last (fun i -> s.[i] = '0')

let is_power10 s =
  let n = String.length s in
  s.[0] = '1' && iszero s 1 (n-1)

let rec log10 s = (* assuming it's a power of 10 *) -1+String.length s

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

  if exists 0 (n-1) (fun i -> iszero a.(i) 0 (-1 + String.length a.(i))) then (
    printf "0\n"
  ) else (

    let rec find_bad_index i ac = if i=n then ac else
	if is_power10 a.(i) then find_bad_index (i+1) ac else i
    in

    let bad_index = find_bad_index 0 (-1) in

    let zeros = sum 0 (n-1) (fun i -> if i = bad_index then 0 else log10 a.(i)) in

    if bad_index < 0 then printf "1" else printf "%s" a.(bad_index);

    for i=1 to zeros do
      printf "0"
    done;

    print_newline()
  )

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 rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0

let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

let rec is_power a b = if a=1 then true else a mod b = 0 && is_power (a/b) b

let rec log10 x = if x=1 then 0 else 1+(log10 (x/10))

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

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

    let rec find_bad i ac = if i=n then ac else
	if is_power a.(i) 10 then find_bad (i+1) ac else a.(i)
    in

    let bad = find_bad 0 1 in

    printf "bad = %d\n" bad;

    let zeros = sum 0 (n-1) (fun i -> if a.(i) = bad then 0 else log10 a.(i)) in

    printf "%d" bad;

    for i=1 to zeros do
      printf "0"
    done;

    print_newline()
  )


Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. The generic syntax for declaring a macro is the following:#define macro_name macro_valueAfter the macro has been declared, "macro_name" is replaced with "macro_value" each time it is met in the program (only the whole tokens can be replaced; i.e. "macro_name" is replaced only when it is surrounded by spaces or other non-alphabetic symbol). A "macro_value" within our model can only be an arithmetic expression consisting of variables, four arithmetic operations, brackets, and also the names of previously declared macros (in this case replacement is performed sequentially). The process of replacing macros with their values is called substitution.One of the main problems arising while using macros — the situation when as a result of substitution we get an arithmetic expression with the changed order of calculation because of different priorities of the operations.Let's consider the following example. Say, we declared such a #define construction:#define sum x + yand further in the program the expression "2 * sum" is calculated. After macro substitution is performed we get "2 * x + y", instead of intuitively expected "2 * (x + y)".Let's call the situation "suspicious", if after the macro substitution the order of calculation changes, falling outside the bounds of some macro. Thus, your task is to find out by the given set of #define definitions and the given expression if this expression is suspicious or not.Let's speak more formally. We should perform an ordinary macros substitution in the given expression. Moreover, we should perform a "safe" macros substitution in the expression, putting in brackets each macro value; after this, guided by arithmetic rules of brackets expansion, we can omit some of the brackets. If there exist a way to get an expression, absolutely coinciding with the expression that is the result of an ordinary substitution (character-by-character, but ignoring spaces), then this expression and the macros system are called correct, otherwise — suspicious.Note that we consider the "/" operation as the usual mathematical division, not the integer division like in C/C++. That's why, for example, in the expression "a*(b/c)" we can omit brackets to get the expression "a*b/c".

The first line contains the only number n (0 ≤ n ≤ 100) — the amount of #define constructions in the given program. Then there follow n lines, each of them contains just one #define construction. Each construction has the following syntax: #define name expression where   name — the macro name,  expression — the expression with which the given macro will be replaced. An expression is a non-empty string, containing digits,names of variables, names of previously declared macros, round brackets and operational signs +-*/. It is guaranteed that the expression (before and after macros substitution) is a correct arithmetic expression, having no unary operations. The expression contains only non-negative integers, not exceeding 109.  All the names (#define constructions' names and names of their arguments) are strings of case-sensitive Latin characters. It is guaranteed that the name of any variable is different from any #define construction. Then, the last line contains an expression that you are to check. This expression is non-empty and satisfies the same limitations as the expressions in #define constructions. The input lines may contain any number of spaces anywhere, providing these spaces do not break the word "define" or the names of constructions and variables. In particular, there can be any number of spaces before and after the "#" symbol. The length of any line from the input file does not exceed 100 characters.

Output "OK", if the expression is correct according to the above given criterion, otherwise output "Suspicious".

4
#define sum  x + y
#define mul  a * b
#define div  a / b
#define expr sum + mul * div * mul
expr

3
#define SumSafe   (a+b)
#define DivUnsafe  a/b
#define DenominatorUnsafe  a*b
((SumSafe) + DivUnsafe/DivUnsafe + x/DenominatorUnsafe)

let (|>) x f = f x

let isalnum c =
  'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9'

let parse pri body =
  let isp = Hashtbl.create 10 in
  List.iter (fun (x,y) -> Hashtbl.add isp x y)
    ['\000',0; '+',3; '-',3; '*',5; '/',5; '(',1; ')',6];
  let icp = Hashtbl.create 10 in
  List.iter (fun (x,y) -> Hashtbl.add icp x y)
    ['\000',0; '+',2; '-',2; '*',4; '/',4; '(',6; ')',1];

  let len = String.length body in
  let rec go i (vs : int list) ops =
    (*Printf.printf "== %d [ " i;*)
    (*List.iter (fun x -> Printf.printf "%c" x) ops;*)
    (*Printf.printf " ] [ ";*)
    (*List.iter (fun x -> Printf.printf "%d" x) vs;*)
    (*Printf.printf " ]";*)
    (*print_endline "";*)

    if i = len && List.hd ops = '\000' then
      List.hd vs
    else
      let ic = if i = len then '\000' else body.[i] in
      (* space *)
      if ic = ' ' then
        go (i+1) vs ops
      else
        try
          (* operator *)
          let ic_ = Hashtbl.find icp ic in
          let is = List.hd ops in
          let is_ = Hashtbl.find isp is in
          if is_ <= ic_ then
            go (i+1) vs (ic::ops)
          else
            match is with
            | '+' | '-' ->
              (match vs with | v::u::vs' ->
                let t = if u >= is_ && (v > is_ || v = is_ && is = '+') then is_ else 0 in
                go i (t::vs') (List.tl ops))
            | '*' | '/' ->
              (match vs with | v::u::vs' ->
                let t = if u >= is_ && (v > is_ || v = is_ && is = '*') then is_ else 0 in
                go i (t::vs') (List.tl ops))
            | ')' ->
              (match vs with | v::vs' ->
                let t = if v > 0 then 6 else 0 in
                go i (t::vs') (List.tl ops |> List.tl))
        with Not_found ->
          (* identifier/literal *)
          let rec go2 i =
            if i >= len || not (isalnum body.[i]) then
              i
            else
              go2 (i+1)
          in
          let j = go2 i in
          let ident = String.sub body i (j-i) in
          go j ((try Hashtbl.find pri ident with Not_found -> 7)::vs) ops
  in

  go 0 [] ['\000']

let () =
  let n = read_int () in
  let pri = Hashtbl.create n in
  for i = 1 to n do
    let line = read_line () in
    Scanf.sscanf line " # %s %s %[^\n]" (fun _ head body ->
      let r = parse pri body in
      Hashtbl.add pri head r
    );
  done;
  print_endline (if parse pri (read_line ()) = 0 then "Suspicious" else "OK")

let (|>) x f = f x

let isalnum c =
  'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9'

let parse pri body =
  let isp = Hashtbl.create 10 in
  List.iter (fun (x,y) -> Hashtbl.add isp x y)
    ['\000',0; '+',3; '-',3; '*',5; '/',5; '(',1; ')',6];
  let icp = Hashtbl.create 10 in
  List.iter (fun (x,y) -> Hashtbl.add icp x y)
    ['\000',0; '+',2; '-',2; '*',4; '/',4; '(',6; ')',1];

  let len = String.length body in
  let rec go i (vs : int list) ops =
    (*Printf.printf "== %d [ " i;*)
    (*List.iter (fun x -> Printf.printf "%c" x) ops;*)
    (*Printf.printf " ] [ ";*)
    (*List.iter (fun x -> Printf.printf "%d" x) vs;*)
    (*Printf.printf " ]";*)
    (*print_endline "";*)

    if i = len && List.hd ops = '\000' then
      List.hd vs
    else
      let ic = if i = len then '\000' else body.[i] in
      (* space *)
      if ic = ' ' then
        go (i+1) vs ops
      else
        try
          (* operator *)
          let ic_ = Hashtbl.find icp ic in
          let is = List.hd ops in
          let is_ = Hashtbl.find isp is in
          if is_ <= ic_ then
            go (i+1) vs (ic::ops)
          else
            match is with
            | '+' | '-' ->
              (match vs with | v::u::vs' ->
                let t = if u >= is_ && (v > is_ || v = is_ && is = '+') then is_ else 0 in
                go i (t::vs') (List.tl ops))
            | '*' | '/' ->
              (match vs with | v::u::vs' ->
                let t = if u >= is_ && (v > is_ || v = is_ && is = '*') then is_ else 0 in
                go i (t::vs') (List.tl ops))
            | ')' ->
              (match vs with | v::vs' ->
                let t = if v > 0 then 6 else 0 in
                go i (t::vs') (List.tl ops |> List.tl))
        with Not_found ->
          (* identifier/literal *)
          let rec go2 i =
            if i >= len || not (isalnum body.[i]) then
              i
            else
              go2 (i+1)
          in
          let j = go2 i in
          let ident = String.sub body i (j-i) in
          go j ((try Hashtbl.find pri ident with Not_found -> 7)::vs) ops
  in

  go 0 [] ['\000']

let () =
  let n = read_int () in
  let pri = Hashtbl.create n in
  for i = 1 to n do
    let line = read_line () in
    Scanf.sscanf line "#define %s %[^\n]" (fun head body ->
      Printf.printf "++ %s %s\n" head body;
      let r = parse pri body in
      Hashtbl.add pri head r;
      Printf.printf "-- %s %s %d\n" head body r
    );
  done;
  print_endline (if parse pri (read_line ()) = 0 then "Suspicious" else "OK")


DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:  where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies:  ;  edge  if and only if , and edge ;  the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected.

The first line contains two space-separated integers n (1 ≤ n ≤ 500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges.

Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9.

NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal.

open Printf
open Scanf

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

  let best = ref 0.0 in

  for i=0 to m-1 do
    let vc = x.(-1+read_int()) + x.(-1+read_int()) in
    let ec = read_int () in
    best := max !best ((float vc) /. (float ec))
  done;

  printf "%.10f\n" !best;


After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).If a carrier with d ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take d ice cream packs comes to the house, then Kay and Gerda will give him d packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.

The first line contains two space-separated integers n and x (1 ≤ n ≤ 1000, 0 ≤ x ≤ 109). Each of the next n lines contains a character '+' or '-', and an integer di, separated by a space (1 ≤ di ≤ 109). Record "+ di" in i-th line means that a carrier with di ice cream packs occupies i-th place from the start of the queue, and record "- di" means that a child who wants to take di packs stands in i-th place.

Print two space-separated integers — number of ice cream packs left after all operations, and number of kids that left the house in distress.

NoteConsider the first sample.  Initially Kay and Gerda have 7 packs of ice cream.  Carrier brings 5 more, so now they have 12 packs.  A kid asks for 10 packs and receives them. There are only 2 packs remaining.  Another kid asks for 20 packs. Kay and Gerda do not have them, so the kid goes away distressed.  Carrier bring 40 packs, now Kay and Gerda have 42 packs.  Kid asks for 20 packs and receives them. There are 22 packs remaining.

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

let store = ref (Int64.of_int x)
let sad = ref 0

let step sign amount =
  let open Int64 in
  let amount = of_int amount in
  match sign with
  | '+' ->
     store := Int64.add !store amount
  | '-' ->
     if !store >= amount then
       store := Int64.sub !store amount
     else
       incr sad
  | _ -> assert false

let () =
  for i = 1 to n do
    Scanf.scanf "%c %d\n" step
  done;
  Printf.printf "%s %d\n" (Int64.to_string !store) !sad

open Big_int

let (+.) = add_big_int

let rec f init dis = function
   | t::q when ge_big_int t zero_big_int -> f (init +. t) dis q
   | t::q              -> if lt_big_int (init +. t) zero_big_int
                         then f init (dis + 1) q
                         else f (init +. t) dis q
   | _                 -> (init,dis)

let _ =
   let (n,init) = Scanf.scanf "%d %s" (fun i j -> i,big_int_of_string j) in
   let l = ref [] in
      for i = 1 to n do Scanf.scanf " %c %d" (fun c x ->
         l := (big_int_of_int (x * if c = '+' then 1 else -1))::!l);
      done;
   let (a,b) = f init 0 (List.rev !l) in
      Printf.printf "%s %d" (string_of_big_int a) b

(* Codeforces 686 A Free Ice Cream *)

(* 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 x = ref (Int64.of_int 0);;
let ndistress = ref 0;;

(* c - + or -, d - nuym of ice cream *)
let one_step c d =
	(* let _ = begin print_int !x; print_string "\n" end in *)
	if c == '+' then
		begin
			x := Int64.add !x d
		end
	else
  		if !x < d then
  			begin
  				ndistress := !ndistress + 1
  			end
			else
				begin
		  		x := Int64.sub !x d
				end;;

let main() =
	let n = gr() in
	let xx = gr () in
	begin
		x := Int64.of_int xx;
		for i = 1 to n do
			let c = grc () in
			let d = Int64.of_int (gr ()) in
			one_step c d
		done;
		print_string (Int64.to_string !x);
		print_string " ";
		print_int !ndistress;
		print_string "\n"
	end;;

main();;

open Printf
open Scanf

let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let long x = Int64.of_int x

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

let () =
  let n = read_int () in
  let x = long (read_int ()) in

  let rec loop i packs distress = if i=n then (packs,distress) else (
    let s = read_string() in
    let q = long (read_int()) in
    match s with
      |	"+" -> loop (i+1) (packs ++ q) distress
      | "-" ->
	if q > packs then loop (i+1) packs (distress+1)
	else loop (i+1) (packs -- q) distress
      | _ -> failwith "bad input"
  ) in

  let (packs, distress) = loop 0 x 0 in

  printf "%Ld %d\n" packs distress

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

let store = ref x
let sad = ref 0

let step sign amount =
  match sign with
  | '+' ->
     store := !store + amount
  | '-' ->
     if !store >= amount then
       store := !store - amount
     else
       incr sad
  | _ -> assert false

let () =
  for i = 1 to n do
    Scanf.scanf "%c %d\n" step
  done;
  Printf.printf "%d %d\n" !store !sad

(* Codeforces 686 A Free Ice Cream *)

(* 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 x = ref 0;;
let ndistress = ref 0;;

(* c - + or -, d - nuym of ice cream *)
let one_step c d =
	(* let _ = begin print_int !x; print_string "\n" end in *)
	if c == '+' then
		begin
			x := !x + d
		end
	else
  		if !x < d then
  			begin
  				ndistress := !ndistress + 1
  			end
			else
				begin
		  		x := !x-d
				end;;

let main() =
	let n = gr() in
	let xx = gr () in
	begin
		x := xx;
		for i = 1 to n do
			let c = grc () in
			let d = gr () in
			one_step c d
		done;
		print_int !x;
		print_string " ";
		print_int !ndistress;
		print_string "\n"
	end;;

main();;


Little penguin Polo adores strings. But most of all he adores strings of length n.One day he wanted to find a string that meets the following conditions:  The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.  No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n).  Among all strings that meet points 1 and 2, the required string is lexicographically smallest. Help him find such string or state that such string doesn't exist.String x = x1x2... xp is lexicographically less than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there is such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The characters of the strings are compared by their ASCII codes.

In a single line print the required string. If there isn't such string, print "-1" (without the quotes).

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

let read_pair () = let a = read_int () in (a , read_int ());;

let n , k = read_pair ();;

let ans = String.create n;;

for i = 0 to (n-1) do
   if i mod 2 = 0 then ans.[i] <- 'a'
   else ans.[i] <- 'b'
done;;

if n = 1 && k = 1 then Printf.printf "a\n"
else if n != 1 && k = 1 then Printf.printf "-1\n"
else if k > n then Printf.printf "-1\n"
else begin
   for i = (n-k+2) to (n-1) do ans.[i] <- Char.chr ((Char.code 'c') + i - (n-k+2)) done;
   Printf.printf "%s\n" ans
end ;;

(* Little penguin Polo adores strings. But most of all he adores strings of length n.

One day he wanted to find a string that meets the following conditions:

  The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.
  No two neighbouring letters of a string coincide; that is, if we represent a string as s = s1s2... sn, then the following inequality holds, si ≠ si + 1(1 ≤ i < n).
  Among all strings that meet points 1 and 2, the required string is lexicographically smallest.
  Help him find such string or state that such string doesn't exist.

  Input
  A single line contains two positive integers n and k (1 ≤ n ≤ 106, 1 ≤ k ≤ 26) — the string's length and the number of distinct letters.

  string.length = n, string.distinct_letters = k, string.neighbouring_letters = false *)

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

let () =
  let n = read_int() in
  let k = read_int() in
  let s = String.create n in

  let answer =
    if n < k then "-1"
    else if n=1 then "a"
    else if k<2 then "-1"
    else (
      for i=0 to n-(k-2)-1 do
        s.[i] <- if i mod 2 = 0 then 'a' else 'b';
      done;
      for i=n-(k-2) to n-1 do
        let j = i-(n-(k-2)) in
        let c = char_of_int ((int_of_char 'c') + j) in
        s.[i] <- c;
      done;
      s
        )
        in
    print_string answer;
    print_newline();


Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at volume v (1 ≤ v ≤ ai; v is an integer) both on the piano and the guitar. They should retain harmony, so the total volume with which the i-th note was played on the guitar and the piano must equal bi. If Dima and Inna cannot play a note by the described rules, they skip it and Sereja's joy drops by 1. But if Inna and Dima play the i-th note at volumes xi and yi (xi + yi = bi) correspondingly, Sereja's joy rises by xi·yi. Sereja has just returned home from the university and his current joy is 0. Help Dima and Inna play the song so as to maximize Sereja's total joy after listening to the whole song!

The first line of the input contains integer n (1 ≤ n ≤ 105) — the number of notes in the song. The second line contains n integers ai (1 ≤ ai ≤ 106). The third line contains n integers bi (1 ≤ bi ≤ 106).

In a single line print an integer — the maximum possible joy Sereja feels after he listens to a song.

NoteIn the first sample, Dima and Inna play the first two notes at volume 1 (1 + 1 = 2, the condition holds), they should play the last note at volumes 1 and 2. Sereja's total joy equals: 1·1 + 1·1 + 1·2 = 4.In the second sample, there is no such pair (x, y), that 1 ≤ x, y ≤ 2, x + y = 5, so Dima and Inna skip a note. Sereja's total joy equals -1.

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let a=Array.init n (fun i->read_int());;
let b=Array.init n (fun i->read_int());;
let s=ref Int64.zero;;
for i=0 to n-1 do
   let m=b.(i)/2 in
   if b.(i)=2*m then (if m<=a.(i) then s:=Int64.add !s (Int64.mul (Int64.of_int(m)) (Int64.of_int(m))) else s:=Int64.pred !s)
   else (if (m+1<=a.(i))&&(m<>0) then s:=Int64.add !s (Int64.mul (Int64.of_int(m)) (Int64.of_int(m+1))) else s:=Int64.pred !s)
done;;
print_string (Int64.to_string !s);;

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let a=Array.init n (fun i->read_int());;
let b=Array.init n (fun i->read_int());;
let s=ref Int64.zero;;
for i=0 to n-1 do
   let m=b.(i)/2 in
   if b.(i)=2*m then (if m<=a.(i) then s:=Int64.add !s (Int64.of_int (m*m)) else s:=Int64.pred !s)
   else (if (m+1<=a.(i))&&(m<>0) then s:=Int64.add !s (Int64.of_int (m*(m+1))) else s:=Int64.pred !s)
done;;
print_string (Int64.to_string !s);;

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let a=Array.init n (fun i->read_int());;
let b=Array.init n (fun i->read_int());;
let s=ref 0;;
for i=0 to n-1 do
   let m=b.(i)/2 in
   if b.(i)=2*m then (if m<=a.(i) then s:= !s+m*m else s:= !s-1)
   else (if m+1<=a.(i) then s:= !s+m*(m+1) else s:= !s-1)
done;;
print_int !s;;

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let a=Array.init n (fun i->read_int());;
let b=Array.init n (fun i->read_int());;
let s=ref 0;;
for i=0 to n-1 do
   let m=b.(i)/2 in
   if b.(i)=2*m then (if m<=a.(i) then s:= !s+m*m else s:= !s-1)
   else (if (m+1<=a.(i))&&(m<>0) then s:= !s+m*(m+1) else s:= !s-1)
done;;
print_int !s;;


According to Berland laws it is only allowed to sell alcohol to people not younger than 18 years. Vasya's job is to monitor the law's enforcement. Tonight he entered a bar and saw n people sitting there. For every one of them Vasya happened to determine either the age or the drink the person is having. Vasya can check any person, i.e. learn his age and the drink he is having at the same time. What minimal number of people should Vasya check additionally to make sure that there are no clients under 18 having alcohol drinks?The list of all alcohol drinks in Berland is: ABSINTH, BEER, BRANDY, CHAMPAGNE, GIN, RUM, SAKE, TEQUILA, VODKA, WHISKEY, WINE

The first line contains an integer n (1 ≤ n ≤ 100) which is the number of the bar's clients. Then follow n lines, each describing one visitor. A line either contains his age (an integer from 0 to 1000) or his drink (a string of capital Latin letters from 1 to 100 in length). It is guaranteed that the input data does not contain spaces and other unnecessary separators. Only the drinks from the list given above should be considered alcohol.

Print a single number which is the number of people Vasya should check to guarantee the law enforcement.

NoteIn the sample test the second and fifth clients should be checked.

let n = read_int ();;
let tests = ref 0;;
let drinks = ["ABSINTH";"BEER";"BRANDY";"CHAMPAGNE";"GIN";"RUM";"SAKE";"TEQUILA";"VODKA";"WHISKEY";"WINE"];;

for i = 1 to n do
	let ln = read_line () in
	try
		let age = int_of_string ln in
		if age < 18 then incr(tests)
	with _ ->
		if List.mem ln drinks then incr(tests)
done;

print_int (!tests);;


The new generation external memory contains an array of integers $$$a[1 \ldots n] = [a_1, a_2, \ldots, a_n]$$$.This type of memory does not support changing the value of an arbitrary element. Instead, it allows you to cut out any segment of the given array, cyclically shift (rotate) it by any offset and insert it back into the same place.Technically, each cyclic shift consists of two consecutive actions:   You may select arbitrary indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) as the boundaries of the segment.  Then you replace the segment $$$a[l \ldots r]$$$ with it's cyclic shift to the left by an arbitrary offset $$$d$$$. The concept of a cyclic shift can be also explained by following relations: the sequence $$$[1, 4, 1, 3]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$1$$$ and the sequence $$$[4, 1, 3, 1]$$$ is a cyclic shift of the sequence $$$[3, 1, 4, 1]$$$ to the left by the offset $$$2$$$. For example, if $$$a = [1, \color{blue}{3, 2, 8}, 5]$$$, then choosing $$$l = 2$$$, $$$r = 4$$$ and $$$d = 2$$$ yields a segment $$$a[2 \ldots 4] = [3, 2, 8]$$$. This segment is then shifted by the offset $$$d = 2$$$ to the left, and you get a segment $$$[8, 3, 2]$$$ which then takes the place of of the original elements of the segment. In the end you get $$$a = [1, \color{blue}{8, 3, 2}, 5]$$$.Sort the given array $$$a$$$ using no more than $$$n$$$ cyclic shifts of any of its segments. Note that you don't need to minimize the number of cyclic shifts. Any method that requires $$$n$$$ or less cyclic shifts will be accepted.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain the descriptions of the test cases.  The first line of each test case description contains an integer $$$n$$$ ($$$2 \leq n \leq 50$$$) — the length of the array. The second line consists of space-separated elements of the array $$$a_i$$$ ($$$-10^9 \leq a_i \leq 10^9$$$). Elements of array $$$a$$$ may repeat and don't have to be unique.

Print $$$t$$$ answers to all input test cases.  The first line of the answer of each test case should contain an integer $$$k$$$ ($$$0 \le k \le n$$$) — the number of actions to sort the array. The next $$$k$$$ lines should contain descriptions of the actions formatted as "$$$l$$$ $$$r$$$ $$$d$$$" (without quotes) where $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) are the boundaries of the segment being shifted, while $$$d$$$ ($$$1 \le d \le r - l$$$) is the offset value. Please remember that only the cyclic shifts to the left are considered so the chosen segment will be shifted by the offset $$$d$$$ to the to the left. Note that you are not required to find the minimum number of cyclic shifts needed for sorting. Any sorting method where the number of shifts does not exceed $$$n$$$ will be accepted. If the given array $$$a$$$ is already sorted, one of the possible answers is $$$k = 0$$$ and an empty sequence of cyclic shifts. If there are several possible answers, you may print any of them.

NoteExplanation of the fourth data set in the example:   The segment $$$a[2 \ldots 4]$$$ is selected and is shifted to the left by $$$2$$$: $$$[2, \color{blue}{5, 1, 4}, 3] \longrightarrow [2, \color{blue}{4, 5, 1}, 3]$$$  The segment $$$a[1 \ldots 5]$$$ is then selected and is shifted to the left by $$$3$$$: $$$[\color{blue}{2, 4, 5, 1, 3}] \longrightarrow [\color{blue}{1, 3, 2, 4, 5}]$$$  After that the segment $$$a[1 \ldots 2]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\color{blue}{1, 3}, 2, 4, 5] \longrightarrow [\color{blue}{3, 1}, 2, 4, 5]$$$  And in the end the segment $$$a[1 \ldots 3]$$$ is selected and is shifted to the left by $$$1$$$: $$$[\color{blue}{3, 1, 2}, 4, 5] \longrightarrow [\color{blue}{1, 2, 3}, 4, 5]$$$

let left liste i =
  let liste = " " ^ liste in
  let rec aux j space =
    if liste.[j] = ' ' then
      if space = i then j
      else aux (j+1) (space+1)
    else
      aux (j+1) space in
  aux 0 0;;

let right liste i =
  let liste = liste ^ " " in
  let rec aux j space =
    if liste.[j] = ' ' then
      if space = i then j-1
      else aux (j+1) (space+1)
    else
      aux (j+1) space in
  aux 0 0;;

let ith liste i j n =
  let liste = liste ^ " " in
  let rec aux start j space =
    if liste.[j] = ' ' then
      if space = i then
        (int_of_string(String.sub liste (start+1) (j-start-1)), j+1)
      else aux j (j+1) (space+1)
    else
      aux start (j+1) space in
  aux (j-1) j n;;

let swipe liste l =
  let len = String.length liste in
  let r = right liste (l-2) in
  (String.sub liste (r+2) (len-r-2)) ^ " " ^ (String.sub liste 0 (r+1));;

let cut liste l r d p l2 =
  let len = String.length liste in
  let li = left liste l and ri = right liste r in
  let subliste = String.sub liste li (ri-li+1) in
  let subliste = swipe subliste (r-l+1) in
  if p then (print_int (l+1); print_string " "; print_int (r+1); print_string " "; print_int d; print_newline ());
  (String.sub liste 0 li) ^ subliste ^ (String.sub liste (ri+1) (len-ri-1));;

let posmin liste s l =
  let rec aux mini index i j =
     if i = l then index else
     let (elt, j) = ith liste i j i in
     if elt < mini then aux elt i (i+1) j else aux mini index (i+1) j in
  aux max_int (-1) s (left liste s);;

let solve liste p l =
  let rec aux liste i c =
    if i < l then
    let pos = posmin liste i l in
    if pos <> i then
      let liste = cut liste i pos (pos-i) p l in
      aux liste (i+1) (c+1)
    else aux liste (i+1) c
    else c in
  aux liste 0 0;;

let t = read_int ();;

let rec main i =
  if i < t then
    begin
      let l = read_int () in
      let liste = read_line () in
      let answer = solve liste false l in
      print_int answer;
      print_newline ();
      solve liste true l;
      main (i+1)
    end;;

main 0;;


Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:  a1 = p, where p is some integer;  ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is some integer. Right now Gena has a piece of paper with sequence b, consisting of n integers. Help Gena, find there the longest subsequence of integers that is an almost arithmetical progression.Sequence s1,  s2,  ...,  sk is a subsequence of sequence b1,  b2,  ...,  bn, if there is such increasing sequence of indexes i1, i2, ..., ik (1  ≤  i1  <  i2  < ...   <  ik  ≤  n), that bij  =  sj. In other words, sequence s can be obtained from b by crossing out some elements.

The first line contains integer n (1 ≤ n ≤ 4000). The next line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106).

Print a single integer — the length of the required longest subsequence.

NoteIn the first test the sequence actually is the suitable subsequence. In the second test the following subsequence fits: 10, 20, 10.

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

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

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

  let h = Hashtbl.create 100 in
  let c = ref 0 in
    for i=0 to n-1 do
      if not (Hashtbl.mem h b.(i)) then (
	Hashtbl.add h b.(i) !c;
	c := !c + 1
      )
    done;

    for i=0 to n-1 do
      b.(i) <- Hashtbl.find h b.(i);
(*      Printf.printf "b.(%d) = %d\n" i b.(i) *)
    done;

    let m = !c in

    let dp = Array.make_matrix n m 1 in

      for i=1 to n-1 do
	let k = b.(i) in
	  for j=0 to i-1 do
	    let l = b.(j) in
	    let c = dp.(j).(k) in
	      dp.(i).(l) <- max (c+1) dp.(i).(l)
	  done
      done;

      let mm = maxf 0 (n-1) (fun i -> maxf 0 (m-1) (fun k ->
(*						      Printf.printf "dp.(%d).(%d) = %d\n" k i dp.(i).(k); *)
						      dp.(i).(k))) in

	Printf.printf "%d\n" mm


As meticulous Gerald sets the table and caring Alexander sends the postcards, Sergey makes snowmen. Each showman should consist of three snowballs: a big one, a medium one and a small one. Sergey's twins help him: they've already made n snowballs with radii equal to r1, r2, ..., rn. To make a snowman, one needs any three snowballs whose radii are pairwise different. For example, the balls with radii 1, 2 and 3 can be used to make a snowman but 2, 2, 3 or 2, 2, 2 cannot. Help Sergey and his twins to determine what maximum number of snowmen they can make from those snowballs.

The first line contains integer n (1 ≤ n ≤ 105) — the number of snowballs. The next line contains n integers — the balls' radii r1, r2, ..., rn (1 ≤ ri ≤ 109). The balls' radii can coincide.

Print on the first line a single number k — the maximum number of the snowmen. Next k lines should contain the snowmen's descriptions. The description of each snowman should consist of three space-separated numbers — the big ball's radius, the medium ball's radius and the small ball's radius. It is allowed to print the snowmen in any order. If there are several solutions, print any of them.

type 'a heap = {mutable heap : (int * 'a) array;
		mutable heap_len : int;
	       }

let heap_new size el = {heap = Array.make size (0, el);
			heap_len = 0;
		       }

let heap_reset heap =
  heap.heap_len <- 0

let heap_insert heap p el =
  if Array.length heap.heap = heap.heap_len then (
    let new_size = heap.heap_len * 2 in
    let new_heap = Array.make new_size heap.heap.(0) in
      Array.blit heap.heap 0 new_heap 0 heap.heap_len;
      heap.heap <- new_heap;
  );
  let h = heap.heap in
  let pos = ref heap.heap_len in
    while !pos > 0 && fst h.((!pos - 1) / 2) > p do
      let parent = (!pos - 1) / 2 in
	h.(!pos) <- h.(parent);
	pos := parent
    done;
    h.(!pos) <- (p, el);
    heap.heap_len <- heap.heap_len + 1

let heap_get_min heap =
  if heap.heap_len > 0 then
    snd heap.heap.(0)
  else
    raise Not_found

let heap_extract_min heap =
  if heap.heap_len > 0 then
    let h = heap.heap in
    let res = h.(0) in
    let len = heap.heap_len - 1 in
      h.(0) <- h.(len);
      heap.heap_len <- len;
      if len > 0 then (
	let p = fst h.(0) in
	let i = ref 0 in
	let b = ref true in
	  while !b do
	    let l = !i * 2 + 1 in
	    let r = !i * 2 + 2 in
	    let smallest =
	      if l < len && p > fst h.(l)
	      then l
	      else !i
	    in
	    let smallest =
	      if r < len && fst h.(smallest) > fst h.(r)
	      then r
	      else smallest
	    in
	      if smallest <> !i then (
		let tmp = h.(!i) in
		  h.(!i) <- h.(smallest);
		  h.(smallest) <- tmp;
		  i := smallest;
	      ) else
		b := false
	  done
      );
      res
  else
    raise Not_found

let heap_is_empty heap =
  heap.heap_len = 0

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let ht = Hashtbl.create n in
  let _ =
    for i = 0 to n - 1 do
      let x = Scanf.bscanf sb "%d " (fun s -> s) in
	try
	  Hashtbl.replace ht x (Hashtbl.find ht x + 1)
	with
	  | Not_found ->
	      Hashtbl.replace ht x 1
    done;
  in
  let heap = heap_new n (-1) in
    Hashtbl.iter
      (fun r c ->
	 heap_insert heap (-c) r
      ) ht;
  let res = ref [] in
    (try
       while true do
	 let (c1, r1) = heap_extract_min heap in
	 let (c2, r2) = heap_extract_min heap in
	 let (c3, r3) = heap_extract_min heap in
	   let [r1'; r2'; r3'] = List.sort compare [r1; r2; r3] in
	     res := (r3', r2', r1') :: !res;
	     let c1 = c1 + 1 in
	     let c2 = c2 + 1 in
	     let c3 = c3 + 1 in
	       if c1 <> 0 then heap_insert heap c1 r1;
	       if c2 <> 0 then heap_insert heap c2 r2;
	       if c3 <> 0 then heap_insert heap c3 r3;
       done
     with
       | Not_found -> ()
    );
    Printf.printf "%d\n" (List.length !res);
    List.iter
      (fun (a, b, c) ->
	 Printf.printf "%d %d %d\n" a b c
      ) !res

(*
let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let r = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      r.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare r
  in
  let sr = Array.make 3 0 in
  let sc = Array.make 3 0 in
  let p = ref 0 in
  let rec clean i =
    if i < !p then (
      if sc.(i) = 0 then (
	for j = i to !p - 2 do
	  sc.(j) <- sc.(j + 1);
	  sr.(j) <- sr.(j + 1);
	done;
	decr p;
	clean i
      ) else clean (i + 1)
    )
  in
  let res = ref [] in
    for i = 0 to n - 1 do
      if !p > 0 && sr.(!p - 1) = r.(i) then (
	sc.(!p - 1) <- sc.(!p - 1) + 1;
      ) else (
	sc.(!p) <- 1;
	sr.(!p) <- r.(i);
	incr p;
      );
      while !p = 3 do
	res := (sr.(2), sr.(1), sr.(0)) :: !res;
	for i = 0 to 2 do
	  sc.(i) <- sc.(i) - 1
	done;
	clean 0
      done
    done;
    Printf.printf "%d\n" (List.length !res);
    List.iter
      (fun (a, b, c) ->
	 Printf.printf "%d %d %d\n" a b c
      ) !res
*)

type 'a heap = {mutable heap : (int * 'a) array;
		mutable heap_len : int;
	       }

let heap_new size el = {heap = Array.make size (0, el);
			heap_len = 0;
		       }

let heap_reset heap =
  heap.heap_len <- 0

let heap_insert heap p el =
  if Array.length heap.heap = heap.heap_len then (
    let new_size = heap.heap_len * 2 in
    let new_heap = Array.make new_size heap.heap.(0) in
      Array.blit heap.heap 0 new_heap 0 heap.heap_len;
      heap.heap <- new_heap;
  );
  let h = heap.heap in
  let pos = ref heap.heap_len in
    while !pos > 0 && fst h.((!pos - 1) / 2) > p do
      let parent = (!pos - 1) / 2 in
	h.(!pos) <- h.(parent);
	pos := parent
    done;
    h.(!pos) <- (p, el);
    heap.heap_len <- heap.heap_len + 1

let heap_get_min heap =
  if heap.heap_len > 0 then
    snd heap.heap.(0)
  else
    raise Not_found

let heap_extract_min heap =
  if heap.heap_len > 0 then
    let h = heap.heap in
    let res = h.(0) in
    let len = heap.heap_len - 1 in
      h.(0) <- h.(len);
      heap.heap_len <- len;
      if len > 0 then (
	let p = fst h.(0) in
	let i = ref 0 in
	let b = ref true in
	  while !b do
	    let l = !i * 2 + 1 in
	    let r = !i * 2 + 2 in
	    let smallest =
	      if l < len && p > fst h.(l)
	      then l
	      else !i
	    in
	    let smallest =
	      if r < len && fst h.(smallest) > fst h.(r)
	      then r
	      else smallest
	    in
	      if smallest <> !i then (
		let tmp = h.(!i) in
		  h.(!i) <- h.(smallest);
		  h.(smallest) <- tmp;
		  i := smallest;
	      ) else
		b := false
	  done
      );
      res
  else
    raise Not_found

let heap_is_empty heap =
  heap.heap_len = 0

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let ht = Hashtbl.create n in
  let _ =
    for i = 0 to n - 1 do
      let x = Scanf.bscanf sb "%d " (fun s -> s) in
	try
	  Hashtbl.replace ht x (Hashtbl.find ht x + 1)
	with
	  | Not_found ->
	      Hashtbl.replace ht x 1
    done;
  in
  let heap = heap_new n (-1) in
    Hashtbl.iter
      (fun r c ->
	 heap_insert heap (-c) r
      ) ht;
  let res = ref [] in
    (try
       while true do
	 let (c1, r1) = heap_extract_min heap in
	 let (c2, r2) = heap_extract_min heap in
	 let (c3, r3) = heap_extract_min heap in
	   let [r1; r2; r3] = List.sort compare [r1; r2; r3] in
	     res := (r3, r2, r1) :: !res;
	     let c1 = c1 + 1 in
	     let c2 = c2 + 1 in
	     let c3 = c3 + 1 in
	       if c1 <> 0 then heap_insert heap c1 r1;
	       if c2 <> 0 then heap_insert heap c2 r2;
	       if c3 <> 0 then heap_insert heap c3 r3;
       done
     with
       | Not_found -> ()
    );
    Printf.printf "%d\n" (List.length !res);
    List.iter
      (fun (a, b, c) ->
	 Printf.printf "%d %d %d\n" a b c
      ) !res


Alice has a grid with $$$2$$$ rows and $$$n$$$ columns. She fully covers the grid using $$$n$$$ dominoes of size $$$1 \times 2$$$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5000$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the width of the grid. The second line of each test case contains a string $$$s$$$ consisting of $$$n$$$ characters, each of which is either L, R, U, or D, representing the left, right, top, or bottom half of a domino, respectively (see notes for better understanding). This string represents one of the rows of the grid.  Additional constraint on the input: each input corresponds to at least one valid tiling.

For each test case, output one string — the other row of the grid, using the same format as the input string. If there are multiple answers, print any.

NoteIn the first test case, Alice shows Bob the top row, the whole grid may look like:   In the second test case, Alice shows Bob the bottom row, the whole grid may look like:   In the third test case, Alice shows Bob the bottom row, the whole grid may look like:   In the fourth test case, Alice shows Bob the top row, the whole grid may look like:

(* OCaml template *)

(* Utility functions *)
let sum = List.fold_left (+) 0;;

let aux = function
	| 'U' -> 'D'
	| 'D' -> 'U'
	|  c  ->  c

(* Main *)
let t = read_int ();;

for t' = 1 to t do
	(* Solve test case here *)
	let n = read_int () in
		let s = read_line () in
			print_endline @@ String.map aux s
done

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int() in
    let s = read_string() in
    for i=0 to n-1 do
      let y = match s.[i] with
	| 'L' -> 'L'
	| 'R' -> 'R'
	| 'U' -> 'D'
	| 'D' -> 'U'
	| _ -> failwith "bad input"
      in
      printf "%c" y;
    done;
    print_newline()
  done


There are several days left before the fiftieth birthday of a famous Berland's writer Berlbury. In this connection the local library decided to make an exposition of the works of this famous science-fiction writer. It was decided as well that it is necessary to include into the exposition only those books that were published during a particular time period. It is obvious that if the books differ much in size, the visitors will not like it. That was why the organizers came to the opinion, that the difference between the highest and the lowest books in the exposition should be not more than k millimeters.The library has n volumes of books by Berlbury, arranged in chronological order of their appearance. The height of each book in millimeters is know, it is hi. As Berlbury is highly respected in the city, the organizers want to include into the exposition as many books as possible, and to find out what periods of his creative work they will manage to cover. You are asked to help the organizers cope with this hard task.

The first line of the input data contains two integer numbers separated by a space n (1 ≤ n ≤ 105) and k (0 ≤ k ≤ 106) — the amount of books by Berlbury in the library, and the maximum allowed height difference between the lowest and the highest books. The second line contains n integer numbers separated by a space. Each number hi (1 ≤ hi ≤ 106) is the height of the i-th book in millimeters.

In the first line of the output data print two numbers a and b (separate them by a space), where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k milllimeters. In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work.

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

let () =
  let n = read_int 0 in
  let th = read_int 0 in
  let a = Array.init n read_int in
  let h1 = ref 0 and t1 = ref 0 and h2 = ref 0 and t2 = ref 0
  and q1 = Array.make n 0 and q2 = Array.make n 0
  and j = ref (-1)
  and ans = ref 0 and ansl = ref [] in
  for i = 0 to n-1 do
    while !h1 < !t1 && a.(q1.(!t1-1)) > a.(i) do
      t1 := !t1-1;
    done;
    q1.(!t1) <- i;
    t1 := !t1+1;
    while !h2 < !t2 && a.(q2.(!t2-1)) < a.(i) do
      t2 := !t2-1;
    done;
    q2.(!t2) <- i;
    t2 := !t2+1;
    while a.(q2.(!h2))-a.(q1.(!h1)) > th do
      if q1.(!h1) < q2.(!h2) then (
        j := q1.(!h1);
        h1 := !h1+1
      ) else (
        j := q2.(!h2);
        h2 := !h2+1
      )
    done;
    if i- !j > !ans then (
      ans := i- !j;
      ansl := []
    );
    if i- !j = !ans then
      ansl := (!j+1)::!ansl
  done;
  Printf.printf "%d %d\n" !ans (List.length !ansl);
  List.iter (fun x -> Printf.printf "%d %d\n" (x+1) (x+ !ans)) (List.rev !ansl)

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

let () =
  let n = read_int 0 in
  let th = read_int 0 in
  let a = Array.init n read_int in
  let h1 = ref 0 and t1 = ref 0 and h2 = ref 0 and t2 = ref 0
  and q1 = Array.make n 0 and q2 = Array.make n 0
  and ans = ref 0 and ansl = ref [] in
  for i = 0 to n-1 do
    while !h1 < !t1 && a.(q1.(!t1-1)) > a.(i) do
      t1 := !t1-1;
    done;
    q1.(!t1) <- i;
    t1 := !t1+1;
    while !h2 < !t2 && a.(q2.(!t2-1)) < a.(i) do
      t2 := !t2-1;
    done;
    q2.(!t2) <- i;
    t2 := !t2+1;
    while a.(q2.(!h2))-a.(q1.(!h1)) > th do
      if q1.(!h1) < q2.(!h2) then
        h1 := !h1+1
      else
        h2 := !h2+1
    done;
    let j = min q1.(!h1) q2.(!h2) in
    if i-j > !ans then (
      ans := i-j;
      ansl := []
    );
    if i-j = !ans then
      ansl := j::!ansl
  done;
  Printf.printf "%d %d\n" (!ans+1) (List.length !ansl);
  List.iter (fun x -> Printf.printf "%d %d\n" (x+1) (x+1+ !ans)) (List.rev !ansl)


You are given an array $$$a_1, a_2, \dots , a_n$$$, which is sorted in non-decreasing order ($$$a_i \le a_{i + 1})$$$. Find three indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$1 \le i < j < k \le n$$$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$ (for example it is possible to construct a non-degenerate triangle with sides $$$3$$$, $$$4$$$ and $$$5$$$ but impossible with sides $$$3$$$, $$$4$$$ and $$$7$$$). If it is impossible to find such triple, report it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 5 \cdot 10^4$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_{i - 1} \le a_i$$$) — the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it in one line. If there is a triple of indices $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$) such that it is impossible to construct a non-degenerate triangle having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1.

NoteIn the first test case it is impossible with sides $$$6$$$, $$$11$$$ and $$$18$$$. Note, that this is not the only correct answer.In the second test case you always can construct a non-degenerate triangle.

let main =
  let test_cases = Scanf.scanf " %d" (fun x -> x) in

  for i = 0 to test_cases - 1 do
    let len = Scanf.scanf " %d" (fun x -> x) in
    assert (len >= 3);

    let arr = Array.init len (fun _ -> 0L) in
    Array.iteri (fun idx _ -> arr.(idx) <- Scanf.scanf " %Ld" (fun x -> x)) arr;

    if Int64.add arr.(0) arr.(1) <= arr.(len - 1) then
      print_endline (Printf.sprintf "%d %d %d" 1 2 len)
    else print_endline "-1"
  done

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

let main =
  let test_cases = read_int () in

  for i = 0 to test_cases - 1 do
    let len = read_int () in
    assert (len >= 3);

    let arr = Array.init len (fun _ -> 0) in
    Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;

    if arr.(0) + arr.(1) <= arr.(len - 1) then
      print_endline (Printf.sprintf "%d %d %d" 1 2 len)
    else print_endline "-1"
  done

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

let main =
  let test_cases = read_int () in

  for i = 0 to test_cases - 1 do
    let len = read_int () in
    assert (len >= 3);

    let arr = Array.init len (fun _ -> 0) in
    Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;

    let rec h i =
      match (i <= 1, arr.(0) + arr.(1) <= arr.(i)) with
      | true, _ -> "-1"
      | false, true -> Printf.sprintf "%d %d %d" 0 1 i
      | false, false -> h (i - 1)
    in
    len - 1 |> h |> print_endline
  done

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

let main =
  let test_cases = read_int () in

  for i = 0 to test_cases - 1 do
    let len = read_int () in

    let arr = Array.init len (fun _ -> 0) in
    Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;

    if arr.(0) + arr.(1) <= arr.(len - 1) then
      print_endline (Printf.sprintf "%d %d %d" 1 2 len)
    else print_endline "-1"
  done

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

let main =
  let test_cases = read_int () in

  for i = 0 to test_cases - 1 do
    let len = read_int () in
    assert (len >= 3);

    let arr = Array.init len (fun _ -> 0) in
    Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;

    let rec h i =
      match (i <= 1, arr.(0) + arr.(1) <= arr.(i)) with
      | true, _ -> "-1"
      | false, true -> Printf.sprintf "%d %d %d" 1 2 (i + 1)
      | false, false -> h (i - 1)
    in
    len - 1 |> h |> print_endline
  done

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

let test_cases = read_int ()

;;
for i = 0 to test_cases - 1 do
  let len = read_int () in
  assert (len >= 3);

  let arr = Array.init len (fun _ -> 0) in
  Array.iteri (fun idx _ -> arr.(idx) <- read_int ()) arr;

  if arr.(0) + arr.(1) <= arr.(len - 1) then
    print_endline (Printf.sprintf "%d %d %d" 1 2 len)
  else print_endline "-1"
done


Casimir has a string $$$s$$$ which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions:  he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent);  or he can erase exactly one letter 'B' and exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent). Therefore, each turn the length of the string is decreased exactly by $$$2$$$. All turns are independent so for each turn, Casimir can choose any of two possible actions.For example, with $$$s$$$ $$$=$$$ "ABCABC" he can obtain a string $$$s$$$ $$$=$$$ "ACBC" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.For a given string $$$s$$$ determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case is described by one string $$$s$$$, for which you need to determine if it can be fully erased by some sequence of turns. The string $$$s$$$ consists of capital letters 'A', 'B', 'C' and has a length from $$$1$$$ to $$$50$$$ letters, inclusive.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should be YES if there is a way to fully erase the corresponding string and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answers).

6
ABACAB
ABBA
AC
ABC
CABCBB
BCBCBCBCBCBCBCBC

let count s =
  let l = String.length s in
  let rec iterate i a b c =
    if i >= l then (a, b, c) else
    match s.[i] with
       'A' -> iterate (i+1) (a+1) b c
      |'B' -> iterate (i+1) a (b+1) c
      |'C' -> iterate (i+1) a b (c+1)
      | _  -> invalid_arg "count: invalid character"
    in iterate 0 0 0 0;;

let solve s =
  let (a, b, c) = count s in
  if a + c = b then
    begin
      print_string "YES"; print_newline ()
    end
  else
    begin
      print_string "NO"; print_newline ()
    end;;

let t = read_int ();;

let rec main i =
  if i < t then
  let s = read_line () in
  begin
    solve s; main (i+1)
  end;;

main 0;;

let count s =
  let l = String.length s and (a, b, c) = (0,0,0) in
  let rec iterate i =
    if i >= l then (a, b, c) else
    match s.[i] with
       'A' -> let a = a+1 in iterate (i+1)
      |'B' -> let b = b+1 in iterate (i+1)
      |'C' -> let c = c+1 in iterate (i+1)
      | _  -> invalid_arg "count: invalid character"
    in iterate 0;;

let solve s =
  let (a, b, c) = count s in
  if a + c = b then
    begin
      print_string "YES"; print_newline ()
    end
  else
    begin
      print_string "NO"; print_newline ()
    end;;

let t = read_int ();;

let rec main i =
  if i < t then
  let s = read_line () in
  begin
    solve s; main (i+1)
  end;;

main 0;;


Are you going to Scarborough Fair?Parsley, sage, rosemary and thyme.Remember me to one who lives there.He once was the true love of mine.Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.Although the girl wants to help, Willem insists on doing it by himself.Grick gave Willem a string of length n.Willem needs to do m operations, each operation has four parameters l, r, c1, c2, which means that all symbols c1 in range [l, r] (from l-th to r-th, including l and r) are changed into c2. String is 1-indexed.Grick wants to know the final string after all the m operations.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). The second line contains a string s of length n, consisting of lowercase English letters. Each of the next m lines contains four parameters l, r, c1, c2 (1 ≤ l ≤ r ≤ n, c1, c2 are lowercase English letters), separated by space.

Output string s after performing m operations described above.

NoteFor the second example:After the first operation, the string is wxxak.After the second operation, the string is waaak.After the third operation, the string is gaaak.

open Scanf
open Printf

let string_replace s l r o t =
  let f i c =
    if i >= l && i <= r && c = o then
      t
    else
      c
  in
  String.mapi f s
;;

let () =
  let (n, m) = bscanf Scanning.stdin " %d %d" (fun x y -> (x, y)) in
  let s = bscanf Scanning.stdin " %s" (fun x -> x) in
  let rec solve i result =
    if i = m
    then result
    else
      let (l, r, o, t) =
        bscanf Scanning.stdin " %d %d %c %c" (fun a b c d -> (a, b, c, d)) in
      let l = l-1 in
      let r = r-1 in
      let result = string_replace result l r o t in
      solve (i+1) result
  in
  printf "%s\n" (solve 0 s);;

open Scanf
open Printf

let string_replace s l r o t =
  let f i c =
    if i >= l && i <= r && c = o then
      t
    else
      c
  in
  String.mapi f s
;;

let () =
  let (n, m) = bscanf Scanning.stdin " %d %d" (fun x y -> (x, y)) in
  let s = bscanf Scanning.stdin " %s" (fun x -> x) in
  let rec solve i result =
    if i = m
    then result
    else
      let (l, r, o, t) =
        bscanf Scanning.stdin " %d %d %c %c" (fun a b c d -> (a, b, c, d)) in
      let ll = l-1 in
      let rr = r-1 in
      let tmp = string_replace result ll rr o t in
      solve (i+1) tmp
  in
  printf "%s\n" (solve 0 s);;

open Printf
open Scanf

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

let () =
  let (n,m) = read_pair () in
  let s = read_string() in
  let rec loop i ac = if i=m then ac else (
      let (l,r) = read_pair() in
      let r = r-1 in
      let l = l-1 in
      let c1 = (read_string()).[0] in
      let c2 = (read_string()).[0] in
      let ac = String.init n (fun i -> if i < l || i > r then ac.[i]
	else if ac.[i] = c1 then c2 else ac.[i])
      in
      loop (i+1) ac
  )
  in

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

open Scanf
open Printf

let string_replace s l r o t =
  let f i c =
    if i >= l && i <= r && c = o then
      t
    else
      s.[i] in
  String.mapi f s
;;

let () =
  let (n, m) = bscanf Scanning.stdin " %d %d" (fun x y -> (x, y)) in
  let s = bscanf Scanning.stdin " %s" (fun x -> x) in
  let rec solve i result =
    if i = m
    then result
    else
      let (l, r, o, t) =
        bscanf Scanning.stdin " %d %d %c %c" (fun a b c d -> (a, b, c, d)) in
      let ll = l-1 in
      let rr = r-1 in
      let tmp = string_replace s ll rr o t in
      solve (i+1) tmp
  in
  printf "%s\n" (solve 0 s);;


There are $$$n$$$ pieces of cake on a line. The $$$i$$$-th piece of cake has weight $$$a_i$$$ ($$$1 \leq i \leq n$$$).The tastiness of the cake is the maximum total weight of two adjacent pieces of cake (i. e., $$$\max(a_1+a_2,\, a_2+a_3,\, \ldots,\, a_{n-1} + a_{n})$$$).You want to maximize the tastiness of the cake. You are allowed to do the following operation at most once (doing more operations would ruin the cake):   Choose a contiguous subsegment $$$a[l, r]$$$ of pieces of cake ($$$1 \leq l \leq r \leq n$$$), and reverse it. The subsegment $$$a[l, r]$$$ of the array $$$a$$$ is the sequence $$$a_l, a_{l+1}, \dots, a_r$$$.If you reverse it, the array will become $$$a_1, a_2, \dots, a_{l-2}, a_{l-1}, \underline{a_r}, \underline{a_{r-1}}, \underline{\dots}, \underline{a_{l+1}}, \underline{a_l}, a_{r+1}, a_{r+2}, \dots, a_{n-1}, a_n$$$.For example, if the weights are initially $$$[5, 2, 1, 4, 7, 3]$$$, you can reverse the subsegment $$$a[2, 5]$$$, getting $$$[5, \underline{7}, \underline{4}, \underline{1}, \underline{2}, 3]$$$. The tastiness of the cake is now $$$5 + 7 = 12$$$ (while before the operation the tastiness was $$$4+7=11$$$).Find the maximum tastiness of the cake after doing the operation at most once.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — the number of pieces of cake. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — $$$a_i$$$ is the weight of the $$$i$$$-th piece of cake.

For each test case, print a single integer: the maximum tastiness of the cake after doing the operation at most once.

NoteIn the first test case, after reversing the subsegment $$$a[2, 5]$$$, you get a cake with weights $$$[5, \underline{7}, \underline{4}, \underline{1}, \underline{2}, 3]$$$. The tastiness of the cake is now $$$\max(5+7, 7+4, 4+1, 1+2, 2+3) = 12$$$. This is the maximum possible tastiness of the cake one can obtain by performing the operation at most once.In the second test case, it's optimal not to do any operation. The tastiness is $$$78+78 = 156$$$.In the third test case, after reversing the subsegment $$$a[1, 2]$$$, you get a cake with weights $$$[\underline{54}, \underline{69}, 91]$$$. The tastiness of the cake is now $$$\max(54+69, 69+91) = 160$$$. There is no way to make the tastiness of the cake greater than $$$160$$$ by performing at most one operation.

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

let search2mmax t = let n = Array.length t in
  let min1 = ref (-1) in
  let min2 = ref (-2) in
  for i = 0 to n-1 do
    if (!min1 = -1 || (!min1 < !min2 && !min2 <> -2 && t.(i)> !min1 )) then
      min1 := t.(i)
    else (if (!min2 = -2 || (!min1 >= !min2 && t.(i)> !min2 )) then
            min2:= t.(i)
         );

  done; (Int64.add (Int64.of_int (!min1)) (Int64.of_int (!min2)) )
;;

let n = int_of_string(input_line stdin) in
for i = 0 to n -1 do
  let len = int_of_string(input_line stdin) in
  let str = input_line stdin in
  let toto = parse len str in
  print_endline (Int64.to_string (search2mmax toto)) ;
done;;

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

let search2mmax t = let n = Array.length t in
  let min1 = ref (-1) in
  let min2 = ref (-2) in
  for i = 0 to n-1 do
    if (!min1 = -1 || (!min1 < !min2 && !min2 <> -2 && t.(i)> !min1 )) then
      min1 := t.(i)
    else (if (!min2 = -2 || (!min1 >= !min2 && t.(i)> !min2 )) then
            min2:= t.(i)
         );

  done; Int64.to_int (Int64.add (Int64.of_int (!min1)) (Int64.of_int (!min2)) )
;;

let n = int_of_string(input_line stdin) in
for i = 0 to n -1 do
  let len = int_of_string(input_line stdin) in
  let str = input_line stdin in
  let toto = parse len str in
  print_endline (string_of_int (search2mmax toto)) ;
done;;

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

let search2mmax t = let n = Array.length t in
  let min1 = ref (-1) in
  let min2 = ref (-2) in
  for i = 0 to n-1 do
    if (!min1 = -1 || (!min1 < !min2 && !min2 <> -2 && t.(i)> !min1 )) then
      min1 := t.(i)
    else (if (!min2 = -2 || (!min1 >= !min2 && t.(i)> !min2 )) then
            min2:= t.(i)
         );

  done; !min1 + !min2
;;

let n = int_of_string(input_line stdin) in
for i = 0 to n -1 do
  let len = int_of_string(input_line stdin) in
  let str = input_line stdin in
  let toto = parse len str in
  print_endline (string_of_int (search2mmax toto)) ;
done;;

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

let search2min t = let n = Array.length t in
  let min1 = ref (-1) in
  let min2 = ref (-2) in
  for i = 0 to n-1 do
    if (!min1 = -1 || (!min1 > !min2 && !min2 <> -2 && t.(i)< !min1 )) then
      min1 := t.(i)
    else (if (!min2 = -2 || (!min1 <= !min2 && t.(i)< !min2 )) then
            min2:= t.(i)
         );

  done; !min1 + !min2
;;

let n = int_of_string(input_line stdin) in
for i = 0 to n -1 do
  let len = int_of_string(input_line stdin) in
  let str = input_line stdin in
  let toto = parse len str in
  print_endline (string_of_int (search2min toto)) ;
done;;


A recently found Ancient Prophesy is believed to contain the exact Apocalypse date. The prophesy is a string that only consists of digits and characters "-".We'll say that some date is mentioned in the Prophesy if there is a substring in the Prophesy that is the date's record in the format "dd-mm-yyyy". We'll say that the number of the date's occurrences is the number of such substrings in the Prophesy. For example, the Prophesy "0012-10-2012-10-2012" mentions date 12-10-2012 twice (first time as "0012-10-2012-10-2012", second time as "0012-10-2012-10-2012").The date of the Apocalypse is such correct date that the number of times it is mentioned in the Prophesy is strictly larger than that of any other correct date.A date is correct if the year lies in the range from 2013 to 2015, the month is from 1 to 12, and the number of the day is strictly more than a zero and doesn't exceed the number of days in the current month. Note that a date is written in the format "dd-mm-yyyy", that means that leading zeroes may be added to the numbers of the months or days if needed. In other words, date "1-1-2013" isn't recorded in the format "dd-mm-yyyy", and date "01-01-2013" is recorded in it.Notice, that any year between 2013 and 2015 is not a leap year.

The first line contains the Prophesy: a non-empty string that only consists of digits and characters "-". The length of the Prophesy doesn't exceed 105 characters.

In a single line print the date of the Apocalypse. It is guaranteed that such date exists and is unique.

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

let prophesy = read_string () ;;

let isdigit c = (c >= '0' && c <= '9') ;;

let months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|] ;;

let parse_date date =
    Scanf.sscanf date "%d-%d-%d" (fun d m y -> (d, m, y))

let valid_date date =
    let rec loop i =
        if i >= 10 then true
        else if (i = 2 || i = 5) && date.[i] = '-' then loop (i + 1)
        else if i != 2 && i != 5 && isdigit date.[i] then loop (i + 1)
        else false
    in if (loop 0) = false then false
    else let (d, m, y) = parse_date date
    in y >= 2013 && y <= 2015 && m > 0 && m <= 12 && d > 0 && d <= months.(m) ;;

let freq =
    let matrix = Array.make 32 (Array.make_matrix 13 2016 0) in
    for i = 0 to 31 do
        matrix.(i) <- Array.make_matrix 13 2016 0
    done ;
    matrix ;;

let apocalypse =
    let rec loop i date count =
        if i > (String.length prophesy) - 10 then date
        else
            let cur_date = String.sub prophesy i 10
            in if valid_date cur_date then let (d, m, y) = parse_date cur_date
            in
            (
                freq.(d).(m).(y) <- freq.(d).(m).(y) + 1 ;
                if freq.(d).(m).(y) > count then
                    loop (i + 1) cur_date freq.(d).(m).(y)
                else
                    loop (i + 1) date count
            )
            else loop (i + 1) date count
    in loop 0 "" 0 ;;

Printf.printf "%s\n" apocalypse ;;

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

let days = [|31;28;31;30;31;30;31;31;30;31;30;31|]

let is_digit c = c >= '0' && c <= '9'

let valid_date s =
  (List.for_all (fun p -> is_digit s.[p]) [0;1;3;4;6;7;8;9]) &&
    (List.for_all (fun p -> s.[p] = '-') [2;5]) &&
    (
      let d = int_of_string (String.sub s 0 2) in
      let m = int_of_string (String.sub s 3 2) in
      let y = int_of_string (String.sub s 6 4) in
	m>=1 && m<=12 && d>=1 && d<=days.(m-1) && y>=2013 && y<=2015
    )

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

  let h = Hashtbl.create 10 in

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

    for i=0 to n-10 do
      let t = String.sub s i 10 in
	if valid_date t then increment t
    done;

    let m = Hashtbl.fold (fun _ c ac -> max c ac) h 0 in

    let t = Hashtbl.fold (fun s c ac -> if c = m then s else ac) h "" in

      Printf.printf "%s\n" t

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

let prophesy = read_string () ;;

let isdigit c = (c >= '0' && c <= '9') ;;

let months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|] ;;

let parse_date date =
    Scanf.sscanf date "%d-%d-%d" (fun d m y -> (d, m, y))

let valid_date date =
    let rec loop i =
        if i >= 10 then true
        else if (i = 2 || i = 5) && date.[i] = '-' then loop (i + 1)
        else if i != 2 && i != 5 && isdigit date.[i] then loop (i + 1)
        else false
    in if (loop 0) = false then false
    else let (d, m, y) = parse_date date
    in y >= 2013 && y <= 2015 && m > 0 && m <= 12 && d > 0 && d <= months.(m) ;;

let freq = Array.make 32 (Array.make_matrix 13 2016 0) ;;

let apocalypse =
    let rec loop i date count =
        if i > (String.length prophesy) - 10 then date
        else
            let cur_date = String.sub prophesy i 10
            in if valid_date cur_date then let (d, m, y) = parse_date cur_date
            in
            (
                freq.(d).(m).(y) <- freq.(d).(m).(y) + 1 ;
                if freq.(d).(m).(y) >= count then
                    loop (i + 1) cur_date freq.(d).(m).(y)
                else
                    loop (i + 1) date count
            )
            else loop (i + 1) date count
    in loop 0 "" 0 ;;

Printf.printf "%s\n" apocalypse ;;

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

let prophesy = read_string () ;;

let isdigit c = (c >= '0' && c <= '9') ;;

let months = [|0; 31; 28; 31; 30; 31; 30; 31; 31; 30; 31; 30; 31|] ;;

let parse_date date =
    Scanf.sscanf date "%d-%d-%d" (fun d m y -> (d, m, y))

let valid_date date =
    let rec loop i =
        if i >= 10 then true
        else if (i = 2 || i = 5) && date.[i] = '-' then loop (i + 1)
        else if i != 2 && i != 5 && isdigit date.[i] then loop (i + 1)
        else false
    in if (loop 0) = false then false
    else let (d, m, y) = parse_date date
    in y >= 2013 && y <= 2015 && m > 0 && m <= 12 && d > 0 && d <= months.(m) ;;

let freq = Array.make 32 (Array.make_matrix 13 2016 0) ;;

let apocalypse =
    let rec loop i date count =
        if i > (String.length prophesy) - 10 then date
        else
            let cur_date = String.sub prophesy i 10
            in if valid_date cur_date then let (d, m, y) = parse_date cur_date
            in
            (
                freq.(d).(m).(y) <- freq.(d).(m).(y) + 1 ;
                if freq.(d).(m).(y) > count then
                    loop (i + 1) cur_date freq.(d).(m).(y)
                else
                    loop (i + 1) date count
            )
            else loop (i + 1) date count
    in loop 0 "" 0 ;;

Printf.printf "%s\n" apocalypse ;;

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

let days = [|31;28;31;30;31;30;31;31;30;31;31;31|]

let is_digit c = c >= '0' && c <= '9'

let valid_date s =
  (List.for_all (fun p -> is_digit s.[p]) [0;1;3;4;6;7;8;9]) &&
    (List.for_all (fun p -> s.[p] = '-') [2;5]) &&
    (
      let d = int_of_string (String.sub s 0 2) in
      let m = int_of_string (String.sub s 3 2) in
      let y = int_of_string (String.sub s 6 4) in
	m>=1 && m<=12 && d>=1 && d<=days.(m-1) && y>=2013 && y<=2015
    )

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

  let h = Hashtbl.create 10 in

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

    for i=0 to n-10 do
      let t = String.sub s i 10 in
	if valid_date t then increment t
    done;

    let m = Hashtbl.fold (fun _ c ac -> max c ac) h 0 in

    let t = Hashtbl.fold (fun s c ac -> if c = m then s else ac) h "" in

      Printf.printf "%s\n" t


Little Petya likes arrays that consist of non-negative integers a lot. Recently his mom has presented him one such array consisting of n elements. Petya immediately decided to find there a segment of consecutive elements, such that the xor of all numbers from this segment was maximal possible. Help him with that.The xor operation is the bitwise exclusive "OR", that is denoted as "xor" in Pascal and "^" in C/C++/Java.

The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains the space-separated integers from the array. All numbers are non-negative integers strictly less than 230.

Print a single integer — the required maximal xor of a segment of consecutive elements.

NoteIn the first sample one of the optimal segments is the segment that consists of the first and the second array elements, if we consider the array elements indexed starting from one.The second sample contains only one optimal segment, which contains exactly one array element (element with index three).

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

let () =
  let n = read_int() in
  let a = Array.init n (fun i -> read_int()) in
  let v = Array.make_matrix n n 0 in
    for i=0 to n-1 do
      v.(i).(i) <- a.(i);
    done;
    for i=0 to n-1 do
      for j=i+1 to n-1 do
	v.(i).(j) <- v.(i).(j-1) lxor a.(j)
      done
    done;

    let m = ref 0 in
      for i=0 to n-1 do
	for j=i to n-1 do
	  m := max v.(i).(j) !m
	done
      done;

      Printf.printf "%d\n" !m