This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

The first line of the input file contains a non-empty string, consisting of «(» and «)» characters. Its length does not exceed 106.

Print the length of the longest substring that is a regular bracket sequence, and the number of such substrings. If there are no such substrings, write the only line containing "0 1".

(* Utils
   --------------------------------------------------------------------------- *)

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

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

(* Solution
   --------------------------------------------------------------------------- *)

let rec rev acc = function
  | '(' :: xs -> rev (')' :: acc) xs
  | ')' :: xs -> rev ('(' :: acc) xs
  | x   :: xs -> rev (x   :: acc) xs
  | [] -> acc

let merge (l1, t1) (l2, t2)  =
  match (compare l1 l2) with
    | 1 -> (l1, t1)
    | 0 when l1 = 0 -> (0, 1)
    | 0 -> (l1, t1 + t2)
    | _ -> (l2, t2)

let rec count b ct res = function
  | [] -> if b = 0 then merge res (ct, 1) else res
  | '(' :: xs ->
      count (b + 1) (ct + 1) res xs
  | _   :: xs ->
    if b > 0 then
      count (b - 1) (ct + 1) res xs
    else
      count 0 0 (merge res (ct, 1)) xs

let solve s =
  let s1 = ')' :: explode s in
  let s2 = rev [] s1 in
  merge (count 0 0 (0, 1) s1) (count 0 0 (0, 1) s2)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" len count

(* Utils
   --------------------------------------------------------------------------- *)

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

(* Solution
   --------------------------------------------------------------------------- *)

let solve s =
  let stk = Stack.create () in

  let b = ref (-1) in
  let max = ref 0 in
  let max_ct = ref 1 in

  for i = 0 to String.length s - 1 do
    try
      match s.[i] with
        | '(' -> Stack.push i stk
        | ')' ->
          let top = Stack.pop stk in
          let len = i - (if Stack.is_empty stk then !b else Stack.top stk) in
          match compare !max len with
            | 1 -> ()
            | 0 -> incr max_ct
            | _ -> max := len; max_ct := 1

    with Stack.Empty -> b := i
  done;

  (!max, !max_ct)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" len count

let foldli f acc s =
  let n = String.length s in
  let rec go i acc =
    if i >= n then
      acc
    else
      go (i+1) (f i acc s.[i])
  in go 0 acc

let () =
  let a = read_line () in
  let opt,cnt,_,_ = foldli (fun i (opt,cnt,b,s) c ->
    if c = '(' then
      (opt,cnt,b,i::s)
    else if s = [] then
      (opt,cnt,i,[])
    else
      let s' = List.tl s in
      let opt' = i - (if s' = [] then b else List.hd s') in
      if opt' > opt then
        (opt',1,b,s')
      else if opt' = opt then
        (opt,cnt+1,b,s')
      else
        (opt,cnt,b,s')
  ) (0,1,-1,[]) a in
  Printf.printf "%d %d\n" opt cnt

(* Utils
   --------------------------------------------------------------------------- *)

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

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

(* Solution
   --------------------------------------------------------------------------- *)

let rec rev acc = function
  | '(' :: xs -> rev (')' :: acc) xs
  | ')' :: xs -> rev ('(' :: acc) xs
  | x   :: xs -> rev (x   :: acc) xs
  | [] -> acc

let merge (l1, t1) (l2, t2)  =
  match (compare l1 l2) with
    | 1 -> (l1, t1)
    | 0 when l1 = 0 -> (0, 1)
    | 0 -> (l1, t1 + t2)
    | _ -> (l2, t2)

let rec count b ct = function
  | [] -> if b = 0 then (ct, 1) else (0, 1)
  | '(' :: xs -> count (b + 1) (ct + 1) xs
  | _   :: xs ->
    if b > 0 then
      count (b - 1) (ct + 1) xs
    else
      merge (count 0 0 xs) (ct, 1)

let solve s =
  let s1 = ')' :: explode s in
  let s2 = rev [] s1 in
  merge (count 0 0 s1) (count 0 0 s2)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" len count

(* Utils
   --------------------------------------------------------------------------- *)

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

(* Solution
   --------------------------------------------------------------------------- *)

let srev s1 =
  let s2 = String.copy s1 in
  let len = String.length s1 - 1 in
  for i = 0 to len do
    s2.[i] <- match s1.[len - i] with
      | '(' -> ')'
      | ')' -> '('
  done;
  s2

let merge (l1, t1) (l2, t2)  =
  match (compare l1 l2) with
    |  1 -> (l1, t1)
    |  0 when l1 = 0 -> (0, 1)
    |  0 -> (l1, t1 + t2)
    | -1 -> (l2, t2)

let count s =
  let rec iter b ct i =
    try
      match s.[i] with
        | '(' -> iter (b + 1) (ct + 1) (i + 1)
        | ')' ->
          if b > 0 then
            iter (b - 1) (ct + 1) (i + 1)
          else
            merge (iter 0 0 (i + 1)) (ct, 1)

    with Invalid_argument _ ->
      if b = 0 then (ct, 1) else (0, 1)

  in iter 0 0 0

let solve s =
  let s1 = ")" ^ s in
  let s2 = srev s1 in
  merge (count s1) (count s2)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" len count

(* Utils
   --------------------------------------------------------------------------- *)

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

(* Solution
   --------------------------------------------------------------------------- *)

let solve s =
  let stk = Stack.create () in

  let b = ref 0 in
  let max = ref 0 in
  let max_ct = ref 1 in

  for i = 0 to String.length s - 1 do
    try
      match s.[i] with
        | '(' -> Stack.push i stk
        | ')' ->
          let top = Stack.pop stk in
          let len = if Stack.is_empty stk then i - !b else i - top in
          match compare !max len with
            | 1 -> ()
            | 0 -> incr max_ct
            | _ -> max := len; max_ct := 1

    with Stack.Empty -> b := i
  done;

  (!max, !max_ct)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" (len+1) count

(* Utils
   --------------------------------------------------------------------------- *)

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

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

(* Solution
   --------------------------------------------------------------------------- *)

let rec rev acc = function
  | '(' :: xs -> rev (')' :: acc) xs
  | ')' :: xs -> rev ('(' :: acc) xs
  | [] -> acc

let merge (l1, t1) (l2, t2)  =
  match (compare l1 l2) with
    |  1 -> (l1, t1)
    |  0 when l1 = 0 -> (0, 1)
    |  0 -> (l1, t1 + t2)
    | -1 -> (l2, t2)

let rec count b ct = function
  | [] -> if b = 0 then (ct, 1) else (0, 1)
  | '(' :: xs -> count (b + 1) (ct + 1) xs
  | ')' :: xs ->
    if b > 0 then
      count (b - 1) (ct + 1) xs
    else
      merge (count 0 0 xs) (ct, 1)

let solve s =
  let s1 = ')' :: explode s in
  let s2 = rev [] s1 in
  merge (count 0 0 s1) (count 0 0 s2)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" len count

(* Utils
   --------------------------------------------------------------------------- *)

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

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

(* Solution
   --------------------------------------------------------------------------- *)

let rec rev acc = function
  | '(' :: xs -> rev (')' :: acc) xs
  | ')' :: xs -> rev ('(' :: acc) xs
  | [] -> acc

let merge (l1, t1) (l2, t2)  =
  match (compare l1 l2) with
    |  1 -> (l1, t1)
    |  0 when l1 = 0 -> (0, 1)
    |  0 -> (l1, t1 + t2)
    | -1 -> (l2, t2)

let rec count b ct = function
  | [] -> if b = 0 then (ct, 1) else (0, 1)
  | '(' :: xs -> count (b + 1) (ct + 1) xs
  | ')' :: xs ->
    if b > 0 then
      count (b - 1) (ct + 1) xs
    else
      merge (count 0 0 xs) (ct, 1)

let solve s =
  let s1 = explode s in
  let s2 = rev [] s1 in
  merge (count 0 0 s1) (count 0 0 s2)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" len count

(* Utils
   --------------------------------------------------------------------------- *)

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

(* Solution
   --------------------------------------------------------------------------- *)

let solve s =
  let stk = Stack.create () in

  let max = ref 0 in
  let max_ct = ref 1 in

  for i = 0 to String.length s - 1 do
    try
      match s.[i] with
        | '(' -> Stack.push i stk
        | ')' ->
          let len = i - Stack.pop stk + 1 in
          match compare !max len with
            | 1 -> ()
            | 0 -> incr max_ct
            | _ -> max := len; max_ct := 1

    with Stack.Empty -> ()
  done;

  (!max, !max_ct)

let _ =
  let (len, count) = solve (read_string ()) in
  Printf.printf "%d %d" len count


N ladies attend the ball in the King's palace. Every lady can be described with three values: beauty, intellect and richness. King's Master of Ceremonies knows that ladies are very special creatures. If some lady understands that there is other lady at the ball which is more beautiful, smarter and more rich, she can jump out of the window. He knows values of all ladies and wants to find out how many probable self-murderers will be on the ball. Lets denote beauty of the i-th lady by Bi, her intellect by Ii and her richness by Ri. Then i-th lady is a probable self-murderer if there is some j-th lady that Bi < Bj, Ii < Ij, Ri < Rj. Find the number of probable self-murderers.

The first line contains one integer N (1 ≤ N ≤ 500000). The second line contains N integer numbers Bi, separated by single spaces. The third and the fourth lines contain sequences Ii and Ri in the same format. It is guaranteed that 0 ≤ Bi, Ii, Ri ≤ 109.

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

let (@@@) x y = if x <> 0 then x else y

let getx (v,_,_) = v
let gety (_,v,_) = v
let getz (_,_,v) = v

let lbound a n x =
  let rec go l h =
    if l >= h then
      l
    else
      let m = (l+h) lsr 1 in
      if a.(m) < x then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.make n (0,0,0) in
  for i = 0 to n-1 do let (_,y,z) = a.(i) in let x = read_int 0 in a.(i) <- (x,y,z) done;
  for i = 0 to n-1 do let (x,_,z) = a.(i) in let y = read_int 0 in a.(i) <- (x,y,z) done;
  for i = 0 to n-1 do let (x,y,_) = a.(i) in let z = read_int 0 in a.(i) <- (x,y,z) done;
  Array.sort (fun (x,y,z) (xx,yy,zz) -> compare xx x @@@ compare y yy @@@ compare z zz) a;

  let ys = Array.make n 0 in
  for i = 0 to n-1 do
    ys.(i) <- gety a.(i)
  done;
  Array.sort compare ys;

  let fenwick = Array.make n (-1) in
  let ans = ref 0 in
  for i = 0 to n-1 do
    let yi = gety a.(i) |> lbound ys n in
    let z = getz a.(i) in
    let rec getmax i ma =
      if i = 0 then
        ma
      else
        let ii = i land (i-1) in
        getmax ii (max ma fenwick.(i-1))
    in
    let rec add i =
      if i < n then (
        let ii = i lor (i+1) in
        fenwick.(i) <- max fenwick.(i) z;
        add ii
      )
    in
    let ma = getmax (n-1-yi) (-1) in
    if ma > z then
      incr ans
    else
      add (n-1-yi)
  done;
  Printf.printf "%d\n" !ans

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

let (@@@) x y = if x <> 0 then x else y

let gety (_,v,_) = v
let getz (_,_,v) = v

let lbound a n x =
  let rec go l h =
    if l >= h then
      l
    else
      let m = (l+h) lsr 1 in
      if a.(m) < x then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.init n (fun _ ->
    let x = read_int 0 in
    let y = read_int 0 in
    let z = read_int 0 in
    x,y,z) in
  Array.sort (fun (x,y,z) (xx,yy,zz) -> compare xx x @@@ compare y yy @@@ compare z zz) a;

  let ys = Array.make n 0 in
  for i = 0 to n-1 do
    ys.(i) <- gety a.(i)
  done;
  Array.sort compare ys;

  let fenwick = Array.make n (-1) in
  let ans = ref 0 in
  for i = 0 to n-1 do
    let yi = gety a.(i) |> lbound ys n in
    let z = getz a.(i) in
    let rec getmax i ma =
      if i = 0 then
        ma
      else
        let ii = i land (i-1) in
        getmax ii (max ma fenwick.(i-1))
    in
    let rec add i =
      if i < n then (
        let ii = i lor (i+1) in
        fenwick.(i) <- max fenwick.(i) z;
        add ii
      )
    in
    let ma = getmax (n-1-yi) (-1) in
    if ma > z then
      incr ans
    else
      add (n-1-yi)
  done;
  Printf.printf "%d\n" !ans


Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length.Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant occupying a single point on that line.Emuskald has discovered that each species thrives at a different temperature, so he wants to arrange m - 1 borders that would divide the greenhouse into m sections numbered from 1 to m from left to right with each section housing a single species. He is free to place the borders, but in the end all of the i-th species plants must reside in i-th section from the left.Of course, it is not always possible to place the borders in such way, so Emuskald needs to replant some of his plants. He can remove each plant from its position and place it anywhere in the greenhouse (at any real coordinate) with no plant already in it. Since replanting is a lot of stress for the plants, help Emuskald find the minimum number of plants he has to replant to be able to place the borders.

The first line of input contains two space-separated integers n and m (1 ≤ n, m ≤ 5000, n ≥ m), the number of plants and the number of different species. Each of the following n lines contain two space-separated numbers: one integer number si (1 ≤ si ≤ m), and one real number xi (0 ≤ xi ≤ 109), the species and position of the i-th plant. Each xi will contain no more than 6 digits after the decimal point. It is guaranteed that all xi are different; there is at least one plant of each species; the plants are given in order "from left to the right", that is in the ascending order of their xi coordinates (xi < xi + 1, 1 ≤ i < n).

Output a single integer — the minimum number of plants to be replanted.

NoteIn the first test case, Emuskald can replant the first plant to the right of the last plant, so the answer is 1.In the second test case, the species are already in the correct order, so no replanting is needed.

open Scanf
open Num
open Printf
open String

type plant = P of int * float;;

let (n,m) = Scanf.scanf "%d %d " (fun x y -> (x,y));;
let read_P () = Scanf.scanf "%d %f " (fun x y -> P (x, y) );;
let read_P2 () = Scanf.scanf "%d %f " (fun x y -> x );;

let plants = Array.init n (fun i -> read_P2 () );;

(* DEBUG
let printx = function
  | P(x,y) -> printf "%d %f\n" x y
in Array.iter (fun x -> print_int x; print_endline "") plants;;
*)
(* longest increasing subsequence*)
let d = Array.make n 1;;

let max_length = ref 1;;
for i = 1 to n -1 do
  for j = i - 1 downto 0 do
    if ( (plants.(i) >= plants.(j) ) && (d.(j)+1 > d.(i)) ) then (d.(i) <- d.(j) + 1)
  done;
  if(d.(i) > !max_length) then max_length := d.(i)

done

let () = print_int (n - !max_length); print_endline "";;

open Scanf
open Num
open Printf
open String

let s = Scanf.bscanf Scanf.Scanning.stdin "%s " ( fun x -> x) |> String.lowercase

let explode s =
  let r = ref [] in
  for i = 0 to (length s - 1) do
    let c = String.get s i in
    r := !r@[c]
  done; !r
;;

let is_vowel = function
  | 'a' -> true
  | 'o' -> true
  | 'y' -> true
  | 'e' -> true
  | 'u' -> true
  | 'i' -> true
  | _ -> false

let l = ( explode s
  |> List.filter (fun x -> (not (is_vowel x)) )
  );;

List.iter (fun x -> print_string ("."^(String.make 1 x)) ) l; print_endline "";;

open Scanf
open Num
open Printf
open String

type plant = P of int * float;;

let (n,m) = Scanf.scanf "%d %d " (fun x y -> (x,y));;
let read_P () = Scanf.scanf "%d %f " (fun x y -> P (x, y) );;
let read_P2 () = Scanf.scanf "%d %f " (fun x y -> x );;

let plants = Array.init n (fun i -> read_P2 () );;

(* DEBUG
let printx = function
  | P(x,y) -> printf "%d %f\n" x y
in Array.iter (fun x -> printx x) plants;;
*)

(* longest increasing subsequence*)
let d = Array.create n 1;;

for i = 1 to n -1 do
  for j = i - 1 downto 0 do
    if ( (plants.(i) >= plants.(j) ) && (d.(j)+1 > d.(i)) ) then (d.(i) <- d.(j) + 1)
  done
done

let () = print_int (n-d.(n-1)); print_endline "";;


Boboniu gives you  $$$r$$$ red balls,  $$$g$$$ green balls,  $$$b$$$ blue balls,  $$$w$$$ white balls. He allows you to do the following operation as many times as you want:   Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.

The first line contains one integer $$$T$$$ ($$$1\le T\le 100$$$) denoting the number of test cases. For each of the next $$$T$$$ cases, the first line contains four integers $$$r$$$, $$$g$$$, $$$b$$$ and $$$w$$$ ($$$0\le r,g,b,w\le 10^9$$$).

For each test case, print "Yes" if it's possible to arrange all the balls into a palindrome after doing several (possibly zero) number of described operations. Otherwise, print "No".

NoteIn the first test case, you're not able to do any operation and you can never arrange three balls of distinct colors into a palindrome.In the second test case, after doing one operation, changing $$$(8,1,9,3)$$$ to $$$(7,0,8,6)$$$, one of those possible palindromes may be "rrrwwwbbbbrbbbbwwwrrr".A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. For example, "rggbwbggr", "b", "gg" are palindromes while "rgbb", "gbbgr" are not. Notice that an empty word, phrase, or sequence is palindrome.

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_4 _ = bscanf Scanning.stdin " %d %d %d %d " (fun a b c d -> (a,b,c,d))

let () =
  let cases = read_int() in
  for case = 1 to cases do
    let (r,g,b,w) = read_4() in
    let c = (r mod 2) + (g mod 2) + (b mod 2) + (w mod 2) in
    let can_toggle = r>0 && g>0 && b>0 in
    let answer =
      if can_toggle then c <> 2
      else c=0 || c=1
    in

    if answer then printf "Yes\n" else printf "No\n"
  done


A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n).A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1.You have integer n. Find some lucky permutation p of size n.

The first line contains integer n (1 ≤ n ≤ 105) — the required permutation size.

Print "-1" (without the quotes) if the lucky permutation p of size n doesn't exist. Otherwise, print n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) after a space — the required permutation. If there are multiple answers, you can print any of them.

(* Codeforces 287C - HappyPermutations *)

open Filename;;

(* you can use either gr or rdln but not both *)
let use_input_txt = false;;
let fn = (Filename.dirname Filename.current_dir_name);;
let filename = Filename.concat "." "input.txt";;
let cin = if use_input_txt then Scanf.Scanning.open_in filename
	else Scanf.Scanning.stdin;;

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

let n = gr();;  (* size of permutation *)

let p = Array.make n 1;;

let pp i n =
	let n2 = n /2 in
	if (i == n2 +1) && (n mod 4 == 1) then i
	else if i <= n2	then
		(if (i mod 2) == 1
			then i + 1
			else n - i + 2)
	else
		(if ((n-i) mod 2) == 1
			then n - i
			else i - 1);;

let countp n =
	for i = 1 to n do
		p.(i -1) <- pp i n
	done;;

let main() =
	if ((n mod 4) == 2) or ((n mod 4) == 3)
	then print_string "-1"
	else
		begin
			countp n;
			printarri p
		end;;

main();;


Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sending it to the magazine 2Char, he needs to adapt the text to the format of the journal. To do so, he removes some words from the chosen article, in such a way that the remaining text can be written using no more than two distinct letters.Since the payment depends from the number of non-space characters in the article, Andrew wants to keep the words with the maximum total length.

The first line of the input contains number n (1 ≤ n ≤ 100) — the number of words in the article chosen by Andrew. Following are n lines, each of them contains one word. All the words consist only of small English letters and their total length doesn't exceed 1000. The words are not guaranteed to be distinct, in this case you are allowed to use a word in the article as many times as it appears in the input.

Print a single integer — the maximum possible total length of words in Andrew's article.

NoteIn the first sample the optimal way to choose words is {'abb', 'aaa', 'bbb'}.In the second sample the word 'cdecdecdecdecdecde' consists of three distinct letters, and thus cannot be used in the article. The optimal answer is {'a', 'a', 'aaaa'}.

open Char;;
let n = read_int () and kol = ref 0 and answer = ref 0;;
let a = Array.create n "";;
let check c x =
begin
	kol := 0;
	for i = 0 to (String.length x) - 1 do
		if String.get x i = c then kol := !kol + 1
	done;
	!kol;
end;;
for i = 0 to n - 1 do let ss = read_line() in Array.set a i ss done;;
for i = 1 to 26 do
	for j = 1 to 26 do
		if i <> j then
		begin
			let ans = ref 0 in
			begin
				for k = 0 to n - 1 do
					if (check (chr (i + 96)) a.(k)) + (check (chr (j + 96)) a.(k)) = String.length a.(k) then ans := !ans + String.length a.(k);
				done;
				answer := max !answer !ans;
			end
		end
	done
done;;
print_int !answer;;

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 maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let n2l n = char_of_int ((int_of_char 'a') + n)
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 word = Array.init n (fun _ -> read_string()) in

  let word_contains_only w c d =
    let n = String.length w in
    forall 0 (n-1) (fun i -> w.[i] = c || w.[i] = d)
  in

  let answer = maxf 0 25 (fun i ->
    maxf 0 25 (fun j ->
      let c = n2l i in
      let d = n2l j in
      sum 0 (n-1) (fun k ->
	if word_contains_only word.(k) c d then String.length word.(k) else 0
      ) 0
    )
  ) in

  printf "%d\n" answer


The board has got a painted tree graph, consisting of n nodes. Let us remind you that a non-directed graph is called a tree if it is connected and doesn't contain any cycles.Each node of the graph is painted black or white in such a manner that there aren't two nodes of the same color, connected by an edge. Each edge contains its value written on it as a non-negative integer.A bad boy Vasya came up to the board and wrote number sv near each node v — the sum of values of all edges that are incident to this node. Then Vasya removed the edges and their values from the board.Your task is to restore the original tree by the node colors and numbers sv.

The first line of the input contains a single integer n (2 ≤ n ≤ 105) — the number of nodes in the tree. Next n lines contain pairs of space-separated integers ci, si (0 ≤ ci ≤ 1, 0 ≤ si ≤ 109), where ci stands for the color of the i-th vertex (0 is for white, 1 is for black), and si represents the sum of values of the edges that are incident to the i-th vertex of the tree that is painted on the board.

Print the description of n - 1 edges of the tree graph. Each description is a group of three integers vi, ui, wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 0 ≤ wi ≤ 109), where vi and ui — are the numbers of the nodes that are connected by the i-th edge, and wi is its value. Note that the following condition must fulfill cvi ≠ cui. It is guaranteed that for any input data there exists at least one graph that meets these data. If there are multiple solutions, print any of them. You are allowed to print the edges in any order. As you print the numbers, separate them with spaces.

(* Codeforces 260D BlackWhiteTree ??? *)

open String;;
open Array;;

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

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

let rec readprs idx n acc = match n with
	| 0 -> List.rev acc
	| _ -> let c = gr() in
			let v = gr() in
			readprs (idx +1) (n -1) ((c, v, idx) :: acc);;

let rec split1 li la lb = match li with
	| [] -> (la, lb)
	| h :: t ->
			let (c, _, _) = h in
			match c with
			| 0 -> split1 t (h :: la) lb
			| 1 -> split1 t la (h :: lb);;

let sortfun a b =
	let (ca, va, ia) = a in
	let (cb, vb, ib) = b in
	(va - vb);;

let rec combine_witha lasta lb acc = match lb with
| [] -> acc
| hb :: tb ->
					let (_, va, ia) = lasta in
					let (_, vb, ib) = hb in
					combine_witha lasta tb ((ia, ib, vb) :: acc);;

let rec combine_withb la lastb acc = match la with
| [] -> acc
| ha :: ta ->
					let (_, va, ia) = ha in
					let (_, vb, ib) = lastb in
					combine_withb ta lastb ((ia, ib, va) :: acc);;

let rec combine la lb acc = match la with
	| [] -> acc
	| ha :: [] -> combine_witha ha lb acc
	| ha :: ta -> match lb with
			| [] -> acc
			| hb :: [] -> combine_withb la hb acc
			| hb :: tb ->
					let (_, va, ia) = ha in
					let (_, vb, ib) = hb in
					if va <= vb then
						combine ta ((1, (vb - va), ib) :: tb) ((ia, ib, va) :: acc)
					else
						combine ((0, (va - vb), ia) :: ta) tb ((ia, ib, vb) :: acc);;

let rec pricomb co =
	let (ia, ib, w) = co in
	begin
		print_int ia; print_string " ";
		print_int ib; print_string " ";
		print_int w;
		print_newline()
	end;;

let n = gr();;

let main () =
	let prs = readprs 1 n [] in
	let (ula, ulb) = split1 prs [] [] in
	let la = List.sort sortfun ula in
	let lb = List.sort sortfun ulb in
	let comb = combine la lb [] in
	List.iter pricomb comb;;

main();;

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

let n = read_int () ;;

let nodes =
    let rec loop i f =
        if i > n then f []
        else let ci = read_int () and si = read_int ()
        in loop (i + 1) (fun l -> f ((i, ci, si) :: l))
    in loop 1 (fun x -> x) ;;

let white = List.filter (fun (i, c, s) -> c = 0) nodes ;;
let black = List.filter (fun (i, c, s) -> c = 1) nodes ;;

let tree =
    let rec build_tree u cu su w b tree =
        if w = [] && b = [] then tree
        else let (node, color, sum, white, black, edge) =
            let (v, cv, sv), nw, nb, opposite_nodes =
                if cu = 0 then let t = List.tl b in (List.hd b), w, t, t
                else let t = List.tl w in (List.hd w), t, b, t
            in if su > sv || su = sv && opposite_nodes <> []
                then (u, cu, su - sv, nw, nb, (u, v, sv))
            else (v, cv, sv - su, nw, nb, (u, v, su))
        in build_tree node color sum white black (edge :: tree)
    in let (u, c, s) = List.hd white
    in build_tree u c s (List.tl white) black [] ;;

let rec print_tree = function
    | [] -> ()
    | (u, v, w) :: t -> Printf.printf "%d %d %d\n" u v w ; print_tree t
in print_tree tree ;;

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

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

let () =
  let n = read_int() in

  let color = [|ref Pset.empty; ref Pset.empty|] in

  let () = for i=1 to n do
    let c = read_int() in
    let s = read_int() in
      color.(c) := Pset.add (s,i) (!(color.(c)));
  done in

  let step (set0, size0, set1, size1) =
    let i = if size0 = 1 then 0 else if size1 = 1 then 1 else
      ( let (m0,_) = Pset.min_elt set0 in
	let (m1,_) = Pset.min_elt set1 in
	  if m0 > m1 then 0 else 1
      )
    in
      (* i is the one which stays, 1-i is removed *)
    let (set0, size0, set1, size1) = if i=0 then (set0, size0, set1, size1) else (set1, size1, set0, size0) in
    let (s0,i0) = Pset.min_elt set0 in
    let set0 = Pset.remove (s0,i0) set0 in
    let (s1,i1) = Pset.min_elt set1 in
    let set1 = Pset.remove (s1,i1) set1 in

      Printf.printf "%d %d %d\n" i0 i1 s1;

      let set0 = Pset.add (s0-s1, i0) set0 in
	(set0, size0, set1, size1-1)
  in

  let rec loop sets i = if i=n-1 then () else loop (step sets) (i+1) in

    loop (!(color.(0)), Pset.cardinal !(color.(0)), !(color.(1)), Pset.cardinal !(color.(1))) 0

(* Codeforces 260D BlackWhiteTree works *)

open String;;
open Array;;

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

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

let rec readprs idx n acc = match n with
	| 0 -> List.rev acc
	| _ -> let c = gr() in
			let v = gr() in
			readprs (idx +1) (n -1) ((c, v, idx) :: acc);;

let rec split1 li la lb = match li with
	| [] -> (la, lb)
	| h :: t ->
			let (c, _, _) = h in
			match c with
			| 0 -> split1 t (h :: la) lb
			| 1 -> split1 t la (h :: lb);;

let sortfun a b =
	let (ca, va, ia) = a in
	let (cb, vb, ib) = b in
	(va - vb);;

let rec combine la lb acc = match la with
	| [] -> acc
	| ha :: ta -> match lb with
			| [] -> acc
			| hb :: tb ->
					let (_, va, ia) = ha in
					let (_, vb, ib) = hb in
					if va <= vb then
						combine ta ((1, (vb - va), ib) :: tb) ((ia, ib, va) :: acc)
					else
						combine ((0, (va - vb), ia) :: ta) tb ((ia, ib, vb) :: acc);;

let rec pricomb co =
	let (ia, ib, w) = co in
	begin
		print_int ia; print_string " ";
		print_int ib; print_string " ";
		print_int w;
		print_newline()
	end;;

let n = gr();;

let main () =
	let prs = readprs 1 n [] in
	let (ula, ulb) = split1 prs [] [] in
	let la = List.sort sortfun ula in
	let lb = List.sort sortfun ulb in
	let comb = combine la lb [] in
	List.iter pricomb comb;;

main();;


Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki people. The j-th person standing in the queue to the i-th cashier has mi, j items in the basket. Vasya knows that:  the cashier needs 5 seconds to scan one item;  after the cashier scans each item of some customer, he needs 15 seconds to take the customer's money and give him the change. Of course, Vasya wants to select a queue so that he can leave the supermarket as soon as possible. Help him write a program that displays the minimum number of seconds after which Vasya can get to one of the cashiers.

The first line contains integer n (1 ≤ n ≤ 100) — the number of cashes in the shop. The second line contains n space-separated integers: k1, k2, ..., kn (1 ≤ ki ≤ 100), where ki is the number of people in the queue to the i-th cashier. The i-th of the next n lines contains ki space-separated integers: mi, 1, mi, 2, ..., mi, ki (1 ≤ mi, j ≤ 100) — the number of products the j-th person in the queue for the i-th cash has.

Print a single integer — the minimum number of seconds Vasya needs to get to the cashier.

NoteIn the second test sample, if Vasya goes to the first queue, he gets to the cashier in 100·5 + 15 = 515 seconds. But if he chooses the second queue, he will need 1·5 + 2·5 + 2·5 + 3·5 + 4·15 = 100 seconds. He will need 1·5 + 9·5 + 1·5 + 3·15 = 100 seconds for the third one and 7·5 + 8·5 + 2·15 = 105 seconds for the fourth one. Thus, Vasya gets to the cashier quicker if he chooses the second or the third queue.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make (n+1) 0;;
let nb=Array.make (n+1) 0;;

for i=1 to n do
   let k=read_int() in
   nb.(i)<-k;
   tab.(i)<-15*k;
done;;

for i=1 to n do
   for j=1 to nb.(i) do
      tab.(i)<-tab.(i)+5*read_int()
   done
done;;

let m=ref tab.(1);;
for i=1 to n do
   if tab.(i)< !m then m:= tab.(i)
done;;

print_int !m;;


Let's call a string $$$s$$$ perfectly balanced if for all possible triplets $$$(t,u,v)$$$ such that $$$t$$$ is a non-empty substring of $$$s$$$ and $$$u$$$ and $$$v$$$ are characters present in $$$s$$$, the difference between the frequencies of $$$u$$$ and $$$v$$$ in $$$t$$$ is not more than $$$1$$$.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string $$$s$$$ consisting of lowercase English letters only. Your task is to determine whether $$$s$$$ is perfectly balanced or not.A string $$$b$$$ is called a substring of another string $$$a$$$ if $$$b$$$ can be obtained by deleting some characters (possibly $$$0$$$) from the start and some characters (possibly $$$0$$$) from the end of $$$a$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 2\cdot 10^4$$$) denoting the number of testcases. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$), consisting of lowercase English letters. It is guaranteed that the sum of $$$|s|$$$ over all testcases does not exceed $$$2\cdot 10^5$$$.

For each test case, print "YES" if $$$s$$$ is a perfectly balanced string, and "NO" otherwise. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

module CharOrd = struct
  type t = char

  let compare x y = if x < y then -1 else if x > y then 1 else 0
end

module CharSet = Set.Make (CharOrd)

let solve () =
  let str = read_line () in
  let n = String.length str in
  let c = ref CharSet.empty in
  let rec find_k i =
    if i >= n then n
    else if CharSet.exists (fun x -> x == String.get str i) !c then i
    else (
      c := CharSet.add (String.get str i) !c;
      find_k (i + 1))
  in
  let k = find_k 0 in
  let rec is_ok i =
    if i >= n then true
    else if String.get str i = String.get str (i - k) then is_ok (i + 1)
    else false
  in
  if is_ok k then "YES" else "NO"

let () =
  let t = read_int () in
  for i = 0 to t - 1 do
    print_endline (solve ())
  done

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let a = input_line stdin in
  let tab = Array.make 26 (-1) in
  let rep = ref true in
  for i = 0 to String.length a - 1 do
    let lett = a.[i] in
    let num = Char.code lett - 97 in
    if tab.(num) = -2 then begin rep := false end ;
    if !rep && (tab.(num) <> -1) then begin
      let last = tab.(num) in
      for j = 0 to 25 do
        if tab.(j) <> -1 && tab.(j) <> -2 && num<>j && tab.(j) < last then rep := false ;
        if tab.(j) = -1 then tab.(j) <- (-2)
      done;
    end ; tab.(num) <- i ;

  done;
  if !rep then print_endline "YES" else print_endline "NO"
done;;

module CharOrd = struct
  type t = char

  let compare x y = if x < y then -1 else if x > y then 1 else 0
end

module CharSet = Set.Make (CharOrd)

let solve () =
  let str = read_line () in
  let n = String.length str in
  let c = ref CharSet.empty in
  let rec find_k i =
    if i >= n then n - 1
    else if CharSet.exists (fun x -> x == String.get str i) !c then i
    else (
      c := CharSet.add (String.get str i) !c;
      find_k (i + 1))
  in
  let k = find_k 0 in
  let rec is_ok i =
    if i >= n then true
    else if String.get str i = String.get str (i - k) then is_ok (i + 1)
    else false
  in
  if is_ok k then "YES" else "NO"

let () =
  let t = read_int () in
  for i = 0 to t - 1 do
    print_endline (solve ())
  done

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let a = input_line stdin in
let tab = Array.make 26 (-1) in
  let rep = ref true in
  for i = 0 to String.length a - 1 do
    let lett = a.[i] in
    let num = Char.code lett - 97 in
    if !rep && (tab.(num) <> -1) then begin
      let last = tab.(num) in
      for j = 0 to 25 do
        if tab.(j) <> -1 && tab.(j) < last then rep := false
      done;

    end ; tab.(num) <- i ;

  done;
  if !rep then print_endline "YES" else print_endline "NO"
done;;


There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.

The first line contains three integers n, x0 и y0 (1 ≤ n ≤ 1000,  - 104 ≤ x0, y0 ≤ 104) — the number of stormtroopers on the battle field and the coordinates of your gun. Next n lines contain two integers each xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of the stormtroopers on the battlefield. It is guaranteed that no stormtrooper stands at the same point with the gun. Multiple stormtroopers can stand at the same point.

Print a single integer — the minimum number of shots Han Solo needs to destroy all the stormtroopers.

NoteExplanation to the first and second samples from the statement, respectively:

open Printf
open Scanf

let rec gcd a b = if a=0 then b else gcd (b mod a) a

let ( -- ) (a,b) (c,d) = (a-c,b-d)

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 gun = read_pair () in
  let point = Array.init n (fun _ -> (read_pair()) -- gun) 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-1 do
    let (x,y) = point.(i) in
    let g = gcd (abs x) (abs y) in
    let (x,y) = (x/g, y/g) in
    let (x,y) = min (x,y) (-x,-y) in
    increment (x,y);
  done;

  printf "%d\n" (Hashtbl.length h)

(* test if points a, b, c are colinear *)
let colinear (ax, ay) (bx, by) (cx, cy) =
  (ax - cx) * (by - cy) = (ay - cy) * (bx - cx)

let () = Scanf.scanf "%d %d %d\n" (fun n x0 y0 ->
  let colinear = colinear (x0, y0) in
  let points = Array.init n (fun _ ->
    Scanf.scanf "%d %d\n" (fun x y -> (x, y)))
  in
  let rays = ref [points.(0)] in
  Array.iter (fun p ->
    (* check each ray to see if it hits this point *)
    let rec aux = function
      | [] -> false
      | q :: ps -> if colinear p q then true else aux ps
    in
    if not (aux !rays) then
      rays := p :: !rays
  ) points;
  Printf.printf "%d\n" (List.length !rays)
)


You are given a sequence of integers of length $$$n$$$ and integer number $$$k$$$. You should print any integer number $$$x$$$ in the range of $$$[1; 10^9]$$$ (i.e. $$$1 \le x \le 10^9$$$) such that exactly $$$k$$$ elements of given sequence are less than or equal to $$$x$$$.Note that the sequence can contain equal elements.If there is no such $$$x$$$, print "-1" (without quotes).

The first line of the input contains integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le k \le n$$$). The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the sequence itself.

Print any integer number $$$x$$$ from range $$$[1; 10^9]$$$ such that exactly $$$k$$$ elements of given sequence is less or equal to $$$x$$$. If there is no such $$$x$$$, print "-1" (without quotes).

NoteIn the first example $$$5$$$ is also a valid answer because the elements with indices $$$[1, 3, 4, 6]$$$ is less than or equal to $$$5$$$ and obviously less than or equal to $$$6$$$.In the second example you cannot choose any number that only $$$2$$$ elements of the given sequence will be less than or equal to this number because $$$3$$$ elements of the given sequence will be also less than or equal to this number.

let split_string ?(pattern=" ") = Str.split @@ Str.regexp pattern
let (n, k) = Scanf.sscanf (read_line ()) "%d %d" @@ fun n k -> (n, k)
let a = read_line () |> split_string |> List.map int_of_string |> List.sort compare |> Array.of_list

let () =
  if k = 0 then Printf.printf "%d\n" (if a.(0) > 1 then a.(0) - 1 else -1)
  else if n = k then Printf.printf "%d\n" a.(k - 1)
  else if a.(k - 1) <> a.(k) then Printf.printf "%d\n" a.(k - 1)
  else print_endline "-1"


Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:   Tetrahedron. Tetrahedron has 4 triangular faces.  Cube. Cube has 6 square faces.  Octahedron. Octahedron has 8 triangular faces.  Dodecahedron. Dodecahedron has 12 pentagonal faces.  Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below:  Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number!

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of polyhedrons in Anton's collection. Each of the following n lines of the input contains a string si — the name of the i-th polyhedron in Anton's collection. The string can look like this:   "Tetrahedron" (without quotes), if the i-th polyhedron in Anton's collection is a tetrahedron.  "Cube" (without quotes), if the i-th polyhedron in Anton's collection is a cube.  "Octahedron" (without quotes), if the i-th polyhedron in Anton's collection is an octahedron.  "Dodecahedron" (without quotes), if the i-th polyhedron in Anton's collection is a dodecahedron.  "Icosahedron" (without quotes), if the i-th polyhedron in Anton's collection is an icosahedron.

Output one number — the total number of faces in all the polyhedrons in Anton's collection.

4
Icosahedron
Cube
Tetrahedron
Dodecahedron

NoteIn the first sample Anton has one icosahedron, one cube, one tetrahedron and one dodecahedron. Icosahedron has 20 faces, cube has 6 faces, tetrahedron has 4 faces and dodecahedron has 12 faces. In total, they have 20 + 6 + 4 + 12 = 42 faces.

let make_list () =
    let n = Pervasives.read_int () in
    let rec loop i list =
        if i < n
        then
            let shape = Pervasives.read_line () in
            loop (i + 1) (shape :: list)
        else
            list
    in loop 0 []

let counter count shape =
    match shape with
    | "Tetrahedron" -> count + 4
    | "Cube" -> count + 6
    | "Octahedron" -> count + 8
    | "Dodecahedron" -> count + 12
    | "Icosahedron" -> count + 20

let () =
    let shapes = make_list () in
    let count = List.fold_left counter 0 shapes in
    Pervasives.print_int count

let counter shape count =
    match shape with
    | "Tetrahedron" -> count + 4
    | "Cube" -> count + 6
    | "Octahedron" -> count + 8
    | "Dodecahedron" -> count + 12
    | "Icosahedron" -> count + 20

let () =
    let n = Pervasives.read_int () in
    let rec loop i count =
        if i < n
        then
            let shape = Pervasives.read_line () in
            loop (i + 1) (counter shape count)
        else
            Pervasives.print_int count
    in loop 0 0

let main () =
  let gr () = Scanf.scanf "%d" (fun i -> i) in
  let gs () = Scanf.scanf "\n%s" (fun i -> i) in
  let n = gr () in
  let rec solve cnt ans =
      match cnt with
      | 0 -> ans
      | cnt ->
          let line = gs() in
          let sides = match line with
          | "Tetrahedron" -> 4
          | "Cube" -> 6
          | "Octahedron" -> 8
          | "Dodecahedron" -> 12
          | "Icosahedron" -> 20
          | somestr -> Printf.printf "!!!%s\n" (somestr); 0
          in
          solve (cnt - 1) (ans + sides)
  in
  Printf.printf "%d\n" (solve n 0);;
let _ = main();;

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

let rec names n =
    if n == 0
    then []
    else Scanf.scanf " %s" (fun x -> x::(names (n - 1)))
in

let sides names =
    let rec helper names acc =
        match names with
        | [] -> acc
        | hd::tl ->
            match hd with
            | "Tetrahedron" -> helper tl (acc + 4)
            | "Cube" -> helper tl (acc + 6)
            | "Octahedron" -> helper tl (acc + 8)
            | "Dodecahedron" -> helper tl (acc + 12)
            | "Icosahedron" -> helper tl (acc + 20)
            | _ -> 0
    in helper names 0
in

Printf.printf "%d\n" (sides (names 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 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 answer = sum 0 (n-1) (fun _ ->
    match read_string() with
      | "Tetrahedron" -> 4
      | "Cube" -> 6
      | "Octahedron" -> 8
      | "Dodecahedron" -> 12
      | "Icosahedron" -> 20
      | _ -> failwith "bad input"
  ) in

  printf "%d\n" answer


Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is the number that is equal to the bitwise excluding OR of the maximum element of the sequence and the second maximum element of the sequence.You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., sr as s[l..r] (1 ≤ l < r ≤ n). Your task is to find the maximum number among all lucky numbers of sequences s[l..r].Note that as all numbers in sequence s are distinct, all the given definitions make sence.

The first line contains integer n (1 < n ≤ 105). The second line contains n distinct integers s1, s2, ..., sn (1 ≤ si ≤ 109).

Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r].

NoteFor the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].For the second sample you must choose s[2..5] = {8, 3, 5, 7}.

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

module Imap = Map.Make (struct type t = int let compare = compare end)

let () =
  let n = read_int() in
  let s = Array.init n (fun i-> (read_int(), i)) in

  let () = Array.sort compare s in

  let bestxor = ref 0 in

  let trypair x y = bestxor := max !bestxor (x lxor y) in

  let rec loop i m = if i<0 then () else
    let (s,j) = s.(i) in
    let (l,_,r) = Imap.split j m in
      if not (Imap.is_empty l) then (
	let (_, h) = Imap.max_binding l in
	  trypair h s
      );
      if not (Imap.is_empty r) then (
	let (_, h) = Imap.min_binding r in
	  trypair h s
      );
      loop (i-1) (Imap.add j s m)
  in

    loop (n-1) Imap.empty;
    Printf.printf "%d\n" !bestxor


Nura wants to buy k gadgets. She has only s burles for that. She can buy each gadget for dollars or for pounds. So each gadget is selling only for some type of currency. The type of currency and the cost in that currency are not changing.Nura can buy gadgets for n days. For each day you know the exchange rates of dollar and pound, so you know the cost of conversion burles to dollars or to pounds.Each day (from 1 to n) Nura can buy some gadgets by current exchange rate. Each day she can buy any gadgets she wants, but each gadget can be bought no more than once during n days.Help Nura to find the minimum day index when she will have k gadgets. Nura always pays with burles, which are converted according to the exchange rate of the purchase day. Nura can't buy dollars or pounds, she always stores only burles. Gadgets are numbered with integers from 1 to m in order of their appearing in input.

First line contains four integers n, m, k, s (1 ≤ n ≤ 2·105, 1 ≤ k ≤ m ≤ 2·105, 1 ≤ s ≤ 109) — number of days, total number and required number of gadgets, number of burles Nura has. Second line contains n integers ai (1 ≤ ai ≤ 106) — the cost of one dollar in burles on i-th day. Third line contains n integers bi (1 ≤ bi ≤ 106) — the cost of one pound in burles on i-th day. Each of the next m lines contains two integers ti, ci (1 ≤ ti ≤ 2, 1 ≤ ci ≤ 106) — type of the gadget and it's cost. For the gadgets of the first type cost is specified in dollars. For the gadgets of the second type cost is specified in pounds.

If Nura can't buy k gadgets print the only line with the number -1. Otherwise the first line should contain integer d — the minimum day index, when Nura will have k gadgets. On each of the next k lines print two integers qi, di — the number of gadget and the day gadget should be bought. All values qi should be different, but the values di can coincide (so Nura can buy several gadgets at one day). The days are numbered from 1 to n. In case there are multiple possible solutions, 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 k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let a0 = Array.make n 0 in
  let a1 = Array.make n 0 in
  let am0 = Array.make n 0 in
  let am1 = Array.make n 0 in
  let c0 = Array.make m (0, 0) in
  let c1 = Array.make m (0, 0) in
  let cnt0 = ref 0 in
  let cnt1 = ref 0 in
  let t0 = ref 0L in
  let t1 = ref 0L in
    for i = 0 to n - 1 do
      a0.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am0.(i) <-
	if i = 0
	then a0.(i)
	else min am0.(i - 1) a0.(i);
    done;
    for i = 0 to n - 1 do
      a1.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am1.(i) <-
	if i = 0
	then a1.(i)
	else min am1.(i - 1) a1.(i);
    done;
    for i = 0 to m - 1 do
      let t = Scanf.bscanf sb "%d " (fun s -> s) in
	if t = 1 then (
	  c0.(!cnt0) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  incr cnt0;
	) else (
	  c1.(!cnt1) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  incr cnt1;
	)
    done;
    let cnt0 = !cnt0 in
    let cnt1 = !cnt1 in
    let c0 = Array.sub c0 0 cnt0 in
    let c1 = Array.sub c1 0 cnt1 in
    let res = ref (n + 1) in
    let best0 = ref 0 in
      Array.sort compare c0;
      Array.sort compare c1;
      for i = 0 to min k cnt1 - 1 do
	t1 := !t1 +| Int64.of_int (fst c1.(i));
      done;
      for i = 0 to cnt0 do
	if k - i <= cnt1 then (
(*Printf.printf "asd %d %Ld %Ld\n" i !t0 !t1;*)
	  let l = ref (-1)
	  and r = ref n in
	    while !l < !r - 1 do
	      let m = (!l + !r) / 2 in
	      let t =
		Int64.of_int am0.(m) *| !t0 +|
		    Int64.of_int am1.(m) *| !t1
	      in
		if t <= s
		then r := m
		else l := m
	    done;
(*if n = 34 then Printf.printf "asd %d %Ld %Ld %d\n" i !t0 !t1 (!r + 1);*)
	    if !res > !r + 1 then (
	      res := !r + 1;
	      best0 := i;
	    )
	);
	if i < cnt0 then (
	  t0 := !t0 +| Int64.of_int (fst c0.(i));
	);
	if k - 1 - i < cnt1 && k - 1 - i >= 0 then (
	  t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));
	);
      done;
      if !res > n
      then Printf.printf "%d\n" (-1)
      else (
	Printf.printf "%d\n" !res;
	let d0 = ref 0 in
	let d1 = ref 0 in
	let s' = ref 0L in
	  for i = 0 to !res - 1 do
	    if a0.(i) < a0.(!d0)
	    then d0 := i;
	    if a1.(i) < a1.(!d1)
	    then d1 := i;
	  done;
	  incr d0;
	  incr d1;
	  for i = 0 to !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c0.(i) + 1) !d0;
	    s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);
	  done;
	  for i = 0 to k - !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c1.(i) + 1) !d1;
	    s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);
	  done;
	  (*Printf.printf "qwe %Ld\n" !s';*)
	  assert (!s' <= s);
      )

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

let () =
  let n = read_int() in
  let m = read_int() in
  let k = read_int() in
  let s = long (read_int()) in

  let dcost = Array.init n (fun _ -> long (read_int())) in
  let pcost = Array.init n (fun _ -> long (read_int())) in

  let rec read_loop i plist dlist = if i=m then (plist,dlist) else
      let t = read_int () in
      let cost = long (read_int ()) in
      if t = 1
      then read_loop (i+1) plist ((cost,i)::dlist)
      else read_loop (i+1) ((cost,i)::plist) dlist
  in

  let (plist,dlist) = read_loop 0 [] [] in
  let parray = Array.of_list (List.sort compare plist) in
  let darray = Array.of_list (List.sort compare dlist) in

  (*
  let rec firstk i li ac = if i = k then List.rev ac else
      match li with
	| [] -> List.rev ac
	| h::t -> firstk (i+1) t (h::ac)
  in

  let plist = firstk 0 plist [] in
  let dlist = firstk 0 dlist [] in
  let dlist = List.rev dlist in
  *)

  let nd = min k (Array.length darray) in
  let np = Array.length parray in
  let p_start = k - nd in
  let dsum = sum 0 (nd-1) (fun i -> fst darray.(i)) 0L in
  let psum = sum 0 (p_start-1) (fun i -> fst parray.(i)) 0L in

  let is_possible d =
  (* return true if it's possible to get k gadgets in the first d days *)
  (* days are numbered 0, 1, 2, ... n-1.  so we're looking at days 0,1,..d-1 *)
    let (best_dollar, dday) = minf 0 (d-1) (fun j -> (dcost.(j), j)) in
    let (best_pound, pday) = minf 0 (d-1) (fun j -> (pcost.(j), j)) in

    let rec scan i dsum psum =
      if best_dollar ** dsum ++ best_pound ** psum <= s then i
      else if i >= nd || i + p_start >= np then -1 else
	scan (i+1) (dsum -- (fst darray.(nd-1-i))) (psum ++ (fst parray.(p_start+i)))
    in

    let goodi = scan 0 dsum psum in
    (goodi >= 0, (dday, pday, goodi))
  in

  let rec bsearch lo hi =
  (* lo is impossible, hi is possible *)
    if lo = hi-1 then hi else
      let m = (lo+hi)/2 in
      if fst (is_possible m) then bsearch lo m else bsearch m hi
  in

  if not (fst (is_possible n)) then printf "-1\n" else (
    let answer = bsearch 0 n in
    printf "%d\n" answer;

    let (_, (dday, pday, goodi)) = is_possible answer in

    for j=0 to nd-goodi-1 do
      printf "%d %d\n" (1+ snd darray.(j)) (1+dday)
    done;

    for j=0 to p_start+goodi-1 do
      printf "%d %d\n" (1+ snd parray.(j)) (1+pday)
    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 k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let a0 = Array.make n 0 in
  let a1 = Array.make n 0 in
  let am0 = Array.make n 0 in
  let am1 = Array.make n 0 in
  let c0 = Array.make m (0, 0) in
  let c1 = Array.make m (0, 0) in
  let cnt0 = ref 0 in
  let cnt1 = ref 0 in
  let t0 = ref 0L in
  let t1 = ref 0L in
    for i = 0 to n - 1 do
      a0.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am0.(i) <-
	if i = 0
	then a0.(i)
	else min am0.(i - 1) a0.(i);
    done;
    for i = 0 to n - 1 do
      a1.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am1.(i) <-
	if i = 0
	then a1.(i)
	else min am1.(i - 1) a1.(i);
    done;
    for i = 0 to m - 1 do
      let t = Scanf.bscanf sb "%d " (fun s -> s) in
	if t = 1 then (
	  c0.(!cnt0) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  incr cnt0;
	) else (
	  c1.(!cnt1) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));
	  incr cnt1;
	)
    done;
    let cnt0 = !cnt0 in
    let cnt1 = !cnt1 in
    let c0 = Array.sub c0 0 cnt0 in
    let c1 = Array.sub c1 0 cnt1 in
    let res = ref (n + 1) in
    let best0 = ref 0 in
      Array.sort compare c0;
      Array.sort compare c1;
      for i = 0 to cnt0 do
	if k - i <= cnt1 then (
(*Printf.printf "asd %d %Ld %Ld\n" i !t0 !t1;*)
	  let l = ref (-1)
	  and r = ref n in
	    while !l < !r - 1 do
	      let m = (!l + !r) / 2 in
	      let t =
		Int64.of_int am0.(m) *| !t0 +|
		    Int64.of_int am1.(m) *| !t1
	      in
		if t <= s
		then r := m
		else l := m
	    done;
if n = 34 then Printf.printf "asd %d %Ld %Ld %d\n" i !t0 !t1 (!r + 1);
	    if !res > !r + 1 then (
	      res := !r + 1;
	      best0 := i;
	    )
	);
	if i < cnt0 then (
	  t0 := !t0 +| Int64.of_int (fst c0.(i));
	);
	if k - 1 - i < cnt1 && k - 1 - i >= 0 then (
	  t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));
	);
      done;
      if !res > n
      then Printf.printf "%d\n" (-1)
      else (
	Printf.printf "%d\n" !res;
	let d0 = ref 0 in
	let d1 = ref 0 in
	let s' = ref 0L in
	  for i = 0 to !res - 1 do
	    if a0.(i) < a0.(!d0)
	    then d0 := i;
	    if a1.(i) < a1.(!d1)
	    then d1 := i;
	  done;
	  incr d0;
	  incr d1;
	  for i = 0 to !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c0.(i) + 1) !d0;
	    s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);
	  done;
	  for i = 0 to k - !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c1.(i) + 1) !d1;
	    s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);
	  done;
	  (*Printf.printf "qwe %Ld\n" !s';*)
	  assert (!s' <= s);
      )

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 k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%d " (fun s -> s) in
  let a0 = Array.make n 0 in
  let a1 = Array.make n 0 in
  let am0 = Array.make n 0 in
  let am1 = Array.make n 0 in
  let c0 = Array.make m (0, 0) in
  let c1 = Array.make m (0, 0) in
  let cnt0 = ref 0 in
  let cnt1 = ref 0 in
  let t0 = ref 0L in
  let t1 = ref 0L in
    for i = 0 to n - 1 do
      a0.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am0.(i) <-
	if i = 0
	then a0.(i)
	else min am0.(i - 1) a0.(i);
    done;
    for i = 0 to n - 1 do
      a1.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am1.(i) <-
	if i = 0
	then a1.(i)
	else min am1.(i - 1) a1.(i);
    done;
    for i = 0 to m - 1 do
      let t = Scanf.bscanf sb "%d " (fun s -> s) in
	if t = 1 then (
	  c0.(!cnt0) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  incr cnt0;
	) else (
	  c1.(!cnt1) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));
	  incr cnt1;
	)
    done;
    let cnt0 = !cnt0 in
    let cnt1 = !cnt1 in
    let c0 = Array.sub c0 0 cnt0 in
    let c1 = Array.sub c1 0 cnt1 in
    let res = ref (n + 1) in
    let best0 = ref 0 in
      Array.sort compare c0;
      Array.sort compare c1;
      for i = 0 to cnt0 do
	if k - i <= cnt1 then (
(*Printf.printf "asd %d %Ld %Ld\n" i !t0 !t1;*)
	  let l = ref (-1)
	  and r = ref n in
	    while !l < !r - 1 do
	      let m = (!l + !r) / 2 in
	      let t =
		Int64.of_int am0.(m) *| !t0 +|
		    Int64.of_int am1.(m) *| !t1
	      in
		if t <= Int64.of_int s
		then r := m
		else l := m
	    done;
	    if !res > !r + 1 then (
	      res := !r + 1;
	      best0 := i;
	    )
	);
	if i < cnt0 then (
	  t0 := !t0 +| Int64.of_int (fst c0.(i));
	);
	if k - 1 - i < cnt1 && k - 1 - i >= 0 then (
	  t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));
	);
      done;
      if !res > n
      then Printf.printf "%d\n" (-1)
      else (
	Printf.printf "%d\n" !res;
	let d0 = ref 0 in
	let d1 = ref 0 in
	let s' = ref 0L in
	  for i = 0 to !res - 1 do
	    if a0.(i) < a0.(!d0)
	    then d0 := i;
	    if a1.(i) < a1.(!d1)
	    then d1 := i;
	  done;
	  incr d0;
	  incr d1;
	  for i = 0 to !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c0.(i) + 1) !d0;
	    s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);
	  done;
	  for i = 0 to k - !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c1.(i) + 1) !d1;
	    s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);
	  done;
	  assert (!s' <= Int64.of_int s);
      )

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 k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let a0 = Array.make n 0 in
  let a1 = Array.make n 0 in
  let am0 = Array.make n 0 in
  let am1 = Array.make n 0 in
  let c0 = Array.make m (0, 0) in
  let c1 = Array.make m (0, 0) in
  let cnt0 = ref 0 in
  let cnt1 = ref 0 in
  let t0 = ref 0L in
  let t1 = ref 0L in
    for i = 0 to n - 1 do
      a0.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am0.(i) <-
	if i = 0
	then a0.(i)
	else min am0.(i - 1) a0.(i);
    done;
    for i = 0 to n - 1 do
      a1.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am1.(i) <-
	if i = 0
	then a1.(i)
	else min am1.(i - 1) a1.(i);
    done;
    for i = 0 to m - 1 do
      let t = Scanf.bscanf sb "%d " (fun s -> s) in
	if t = 1 then (
	  c0.(!cnt0) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  incr cnt0;
	) else (
	  c1.(!cnt1) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  if !cnt1 < k
	  then t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));
	  incr cnt1;
	)
    done;
    let cnt0 = !cnt0 in
    let cnt1 = !cnt1 in
    let c0 = Array.sub c0 0 cnt0 in
    let c1 = Array.sub c1 0 cnt1 in
    let res = ref (n + 1) in
    let best0 = ref 0 in
      Array.sort compare c0;
      Array.sort compare c1;
      for i = 0 to cnt0 do
	if k - i <= cnt1 then (
(*Printf.printf "asd %d %Ld %Ld\n" i !t0 !t1;*)
	  let l = ref (-1)
	  and r = ref n in
	    while !l < !r - 1 do
	      let m = (!l + !r) / 2 in
	      let t =
		Int64.of_int am0.(m) *| !t0 +|
		    Int64.of_int am1.(m) *| !t1
	      in
		if t <= s
		then r := m
		else l := m
	    done;
(*if n = 34 then Printf.printf "asd %d %Ld %Ld %d\n" i !t0 !t1 (!r + 1);*)
	    if !res > !r + 1 then (
	      res := !r + 1;
	      best0 := i;
	    )
	);
	if i < cnt0 then (
	  t0 := !t0 +| Int64.of_int (fst c0.(i));
	);
	if k - 1 - i < cnt1 && k - 1 - i >= 0 then (
	  t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));
	);
      done;
      if !res > n
      then Printf.printf "%d\n" (-1)
      else (
	Printf.printf "%d\n" !res;
	let d0 = ref 0 in
	let d1 = ref 0 in
	let s' = ref 0L in
	  for i = 0 to !res - 1 do
	    if a0.(i) < a0.(!d0)
	    then d0 := i;
	    if a1.(i) < a1.(!d1)
	    then d1 := i;
	  done;
	  incr d0;
	  incr d1;
	  for i = 0 to !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c0.(i) + 1) !d0;
	    s' := !s' +| Int64.of_int (fst c0.(i)) *| Int64.of_int a0.(!d0 - 1);
	  done;
	  for i = 0 to k - !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c1.(i) + 1) !d1;
	    s' := !s' +| Int64.of_int (fst c1.(i)) *| Int64.of_int a1.(!d1 - 1);
	  done;
	  (*Printf.printf "qwe %Ld\n" !s';*)
	  assert (!s' <= s);
      )

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 k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%d " (fun s -> s) in
  let a0 = Array.make n 0 in
  let a1 = Array.make n 0 in
  let am0 = Array.make n 0 in
  let am1 = Array.make n 0 in
  let c0 = Array.make m (0, 0) in
  let c1 = Array.make m (0, 0) in
  let cnt0 = ref 0 in
  let cnt1 = ref 0 in
  let t0 = ref 0L in
  let t1 = ref 0L in
    for i = 0 to n - 1 do
      a0.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am0.(i) <-
	if i = 0
	then a0.(i)
	else min am0.(i - 1) a0.(i);
    done;
    for i = 0 to n - 1 do
      a1.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      am1.(i) <-
	if i = 0
	then a1.(i)
	else min am1.(i - 1) a1.(i);
    done;
    for i = 0 to m - 1 do
      let t = Scanf.bscanf sb "%d " (fun s -> s) in
	if t = 1 then (
	  c0.(!cnt0) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  incr cnt0;
	) else (
	  c1.(!cnt1) <- (Scanf.bscanf sb "%d " (fun s -> s), i);
	  t1 := !t1 +| Int64.of_int (fst c1.(!cnt1));
	  incr cnt1;
	)
    done;
    let cnt0 = !cnt0 in
    let cnt1 = !cnt1 in
    let c0 = Array.sub c0 0 cnt0 in
    let c1 = Array.sub c1 0 cnt1 in
    let res = ref (n + 1) in
    let best0 = ref 0 in
      Array.sort compare c0;
      Array.sort compare c1;
      for i = 0 to cnt0 do
	if k - i <= cnt1 then (
	  let l = ref (-1)
	  and r = ref n in
	    while !l < !r - 1 do
	      let m = (!l + !r) / 2 in
	      let t =
		Int64.of_int am0.(m) *| !t0 +|
		    Int64.of_int am1.(m) *| !t1
	      in
		if t <= Int64.of_int s
		then r := m
		else l := m
	    done;
	    if !res > !r + 1 then (
	      res := !r + 1;
	      best0 := i;
	    )
	);
	if i < cnt0 then (
	  t0 := !t0 +| Int64.of_int (fst c0.(i));
	);
	if k - 1 - i < cnt1 && k - 1 - i >= 0 then (
	  t1 := !t1 -| Int64.of_int (fst c1.(k - 1 - i));
	);
      done;
      if !res > n
      then Printf.printf "%d\n" (-1)
      else (
	Printf.printf "%d\n" !res;
	let d0 = ref 0 in
	let d1 = ref 0 in
	  for i = 0 to !res - 1 do
	    if a0.(i) < a0.(!d0)
	    then d0 := i;
	    if a1.(i) < a1.(!d0)
	    then d1 := i;
	  done;
	  incr d0;
	  incr d1;
	  for i = 0 to !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c0.(i) + 1) !d0;
	  done;
	  for i = 0 to k - !best0 - 1 do
	    Printf.printf "%d %d\n" (snd c1.(i) + 1) !d1;
	  done;
      )


Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it.Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same?

The first line of the input contains a single integer n (1 ≤ n ≤ 100) — the number of participants Anton has outscored in this contest . The next n lines describe participants results: the i-th of them consists of a participant handle namei and two integers beforei and afteri ( - 4000 ≤ beforei, afteri ≤ 4000) — participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters «_» and «-» characters. It is guaranteed that all handles are distinct.

Print «YES» (quotes for clarity), if Anton has performed good in the contest and «NO» (quotes for clarity) otherwise.

3
Burunduk1 2526 2537
BudAlNik 2084 2214
subscriber 2833 2749

3
Applejack 2400 2400
Fluttershy 2390 2431
Pinkie_Pie -2500 -2450

NoteIn the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest.In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let res = ref false in
    for i = 1 to n do
      let _s = Scanf.bscanf sb "%s " (fun s -> s) in
      let b = Scanf.bscanf sb "%d " (fun s -> s) in
      let a = Scanf.bscanf sb "%d " (fun s -> s) in
	if b >= 2400 && a > b
	then res := true
    done;
    if !res
    then Printf.printf "YES\n"
    else Printf.printf "NO\n"


Bob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. To steal one item Bob needs exactly 1 second. What is the minimum amount of money that Bob will have to pay to the checkout assistant? Remember, please, that it is Bob, who determines the order of items for the checkout assistant.

The first input line contains number n (1 ≤ n ≤ 2000). In each of the following n lines each item is described by a pair of numbers ti, ci (0 ≤ ti ≤ 2000, 1 ≤ ci ≤ 109). If ti is 0, Bob won't be able to steal anything, while the checkout assistant is occupied with item i.

Output one number — answer to the problem: what is the minimum amount of money that Bob will have to pay.

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

open Int64

let () =
  let n = read_int 0 in
  let s = Array.make (n+1) (shift_right max_int 1) in
  s.(0) <- 0L;
  for i = 1 to n do
    let t = read_int 0 in
    let c = read_int64 0 in
    for j = n-1 downto 0 do
      let x = min (j+t+1) n in
      s.(x) <- min s.(x) (add s.(j) c)
    done
  done;
  Printf.printf "%Ld\n" s.(n)

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

let () =
  let n = read_int 0 in
  let s = Array.make (n+1) (max_int/2) in
  s.(0) <- 0;
  for i = 1 to n do
    let t = read_int 0 in
    let c = read_int 0 in
    for j = n-1 downto 0 do
      let x = min (j+t+1) n in
      s.(x) <- min s.(x) (s.(j)+c)
    done
  done;
  Printf.printf "%d\n" s.(n)


Arkady bought an air ticket from a city A to a city C. Unfortunately, there are no direct flights, but there are a lot of flights from A to a city B, and from B to C.There are $$$n$$$ flights from A to B, they depart at time moments $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ and arrive at B $$$t_a$$$ moments later.There are $$$m$$$ flights from B to C, they depart at time moments $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ and arrive at C $$$t_b$$$ moments later.The connection time is negligible, so one can use the $$$i$$$-th flight from A to B and the $$$j$$$-th flight from B to C if and only if $$$b_j \ge a_i + t_a$$$.You can cancel at most $$$k$$$ flights. If you cancel a flight, Arkady can not use it.Arkady wants to be in C as early as possible, while you want him to be in C as late as possible. Find the earliest time Arkady can arrive at C, if you optimally cancel $$$k$$$ flights. If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$.

The first line contains five integers $$$n$$$, $$$m$$$, $$$t_a$$$, $$$t_b$$$ and $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$, $$$1 \le k \le n + m$$$, $$$1 \le t_a, t_b \le 10^9$$$) — the number of flights from A to B, the number of flights from B to C, the flight time from A to B, the flight time from B to C and the number of flights you can cancel, respectively. The second line contains $$$n$$$ distinct integers in increasing order $$$a_1$$$, $$$a_2$$$, $$$a_3$$$, ..., $$$a_n$$$ ($$$1 \le a_1 < a_2 < \ldots < a_n \le 10^9$$$) — the times the flights from A to B depart. The third line contains $$$m$$$ distinct integers in increasing order $$$b_1$$$, $$$b_2$$$, $$$b_3$$$, ..., $$$b_m$$$ ($$$1 \le b_1 < b_2 < \ldots < b_m \le 10^9$$$) — the times the flights from B to C depart.

If you can cancel $$$k$$$ or less flights in such a way that it is not possible to reach C at all, print $$$-1$$$. Otherwise print the earliest time Arkady can arrive at C if you cancel $$$k$$$ flights in such a way that maximizes this time.

NoteConsider the first example. The flights from A to B depart at time moments $$$1$$$, $$$3$$$, $$$5$$$, and $$$7$$$ and arrive at B at time moments $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$, respectively. The flights from B to C depart at time moments $$$1$$$, $$$2$$$, $$$3$$$, $$$9$$$, and $$$10$$$ and arrive at C at time moments $$$2$$$, $$$3$$$, $$$4$$$, $$$10$$$, $$$11$$$, respectively. You can cancel at most two flights. The optimal solution is to cancel the first flight from A to B and the fourth flight from B to C. This way Arkady has to take the second flight from A to B, arrive at B at time moment $$$4$$$, and take the last flight from B to C arriving at C at time moment $$$11$$$.In the second example you can simply cancel all flights from A to B and you're done.In the third example you can cancel only one flight, and the optimal solution is to cancel the first flight from A to B. Note that there is still just enough time to catch the last flight from B to C.

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

let () =
  let n, m, ta, tb, k = Scanf.scanf "%d %d %Ld %Ld %d\n" (fun x y z q e -> x, y, z, q, e) in
  let a =
    Array.init n
      (fun _ -> Scanf.scanf "%Ld " (fun x -> x))
    |> Array.map ((++) ta)
  in
  let b =
    Array.init m
      (fun _ -> Scanf.scanf "%Ld " (fun x -> x))
  in
  let ia = ref 0 in
  let prev = ref 0 in
  let toto =
    Array.mapi
      (fun ib b ->
         while ((!ia < n) && a.(!ia) <= b) do incr ia done;
         let x = min (!prev+1) (!ia) in
         prev := x;
         x
      ) b
  in
  if toto.(m-1) <= k then Printf.printf "-1"
  else begin
    let idx = ref 0 in
    while toto.(!idx) <= k do incr idx done;
    Printf.printf "%Ld" (b.(!idx) ++ tb)
  end
;;


Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).The weight of the spanning tree is the sum of weights of all edges included in spanning tree.

First line contains two integers n and m (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105) — the number of vertices and edges in graph. Each of the next m lines contains three integers ui, vi, wi (1 ≤ ui, vi ≤ n, ui ≠ vi, 1 ≤ wi ≤ 109) — the endpoints of the i-th edge and its weight.

Print m lines. i-th line should contain the minimal possible weight of the spanning tree that contains i-th edge. The edges are numbered from 1 to m in order of their appearing in input.

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

type element = {mutable p : int;
		mutable rank : int;
		mutable w : int64}

type t = element array

let makeset set x =
  set.(x) <- {p = x; rank = 0; w = 0L}

(*
let rec find set x =
  if x <> set.(x).p then set.(x).p <- find set set.(x).p;
  set.(x).p
*)
let rec find set x =
  if x <> set.(x).p
  then find set set.(x).p
  else x

let link set x y w =
  if set.(x).rank > set.(y).rank then (
    set.(y).p <- x;
    set.(y).w <- w;
    x
  ) else (
    if set.(x).rank = set.(y).rank then set.(y).rank <- set.(y).rank + 1;
    set.(x).p <- y;
    set.(x).w <- w;
    y
  )

let newsets size =
  let set = Array.make size {p = -1; rank = 0; w = 0L} in
    for i = 0 to size-1 do
      makeset set i
    done;
    set

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 es = Array.make m (0L, 0, 0) in
    for i = 0 to m - 1 do
      let u = Scanf.bscanf sb "%d " (fun s -> s) in
      let v = Scanf.bscanf sb "%d " (fun s -> s) in
      let w = Scanf.bscanf sb "%Ld " (fun s -> s) in
	es.(i) <- (w, u - 1, v - 1)
    done;
    let es' = Array.copy es in
    let () = Array.sort compare es in
    let ds = newsets n in
    let c = Array.make n (-1) in
    let t = ref 0L in
      for i = 0 to m - 1 do
	let (w, u, v) = es.(i) in
	let ru = find ds u in
	let rv = find ds v in
	  if ru <> rv then (
	    ignore (link ds ru rv w);
	    t := !t +| w
	  )
      done;
      for i = 0 to m - 1 do
	let lca =
	  let (_w, u, v) = es'.(i) in
	  let u = ref u in
	  let v = ref v in
	    while ds.(!u).p <> !u do
	      c.(!u) <- i;
	      u := ds.(!u).p
	    done;
	    c.(!u) <- i;
	    while c.(!v) <> i do
	      v := ds.(!v).p
	    done;
	    !v
	in
	let (w, u, v) = es'.(i) in
	let ww = ref 0L in
	let u = ref u in
	let v = ref v in
	  while !u <> lca do
	    ww := max !ww ds.(!u).w;
	    u := ds.(!u).p
	  done;
	  while !v <> lca do
	    ww := max !ww ds.(!v).w;
	    v := ds.(!v).p
	  done;
	  let t = !t -| !ww +| w in
	    Printf.printf "%Ld\n" t
      done;

(* started 1:10 *)

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

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

let () =

  let n = read_int() in
  let m = read_int() in

  let edges_unsorted = fold 1 m (fun i ac ->
    let u = read_int() -1 in
    let v = read_int() -1 in
    let w = long (read_int()) in
    (w,u,v)::ac) []
  in

  let edges_unsorted = List.rev edges_unsorted in

  let edges = List.sort compare edges_unsorted in

  let uf = Array.make n (-1) in
  let weight = Array.make n 0L in

  let rec find i = if uf.(i) < 0 then i else find uf.(i) in

  let union i j w =
  (* assume i and j are both canonical elements *)
    let (wi,wj) = (-uf.(i), -uf.(j)) in
    if wi < wj then (
      uf.(j) <- uf.(i) + uf.(j);
      uf.(i) <- j;
      weight.(i) <- w;
    ) else (
      uf.(i) <- uf.(i) + uf.(j);
      uf.(j) <- i;
      weight.(j) <- w;
    )
  in

  List.iter (fun (w,u,v) ->
    let (i,j) = (find u, find v) in
    if i <> j then union i j w
  ) edges;

  let path = Array.make n (-1) in

  let total_cost = sum 0 (n-1) (fun v -> weight.(v)) 0L in

  let lca u v i =
    let rec mark u = if u >= 0 then (path.(u) <- i; mark uf.(u)) in
    mark u;
    let rec fmark v = if path.(v) = i then v else fmark uf.(v) in
    fmark v
  in

  let rec max_cost_to v l ac = if v = l then ac else
      max_cost_to uf.(v) l (max ac weight.(v))
  in

  List.iteri (fun i (w,u,v) ->
    let l = lca u v i in
    let wt = max (max_cost_to u l 0L) (max_cost_to v l 0L) in
    printf "%Ld\n" (total_cost ++ w -- wt)
  ) edges_unsorted;


You are given $$$n$$$ pairs of integers $$$(a_1, b_1), (a_2, b_2), \ldots, (a_n, b_n)$$$. All of the integers in the pairs are distinct and are in the range from $$$1$$$ to $$$2 \cdot n$$$ inclusive.Let's call a sequence of integers $$$x_1, x_2, \ldots, x_{2k}$$$ good if either   $$$x_1 < x_2 > x_3 < \ldots < x_{2k-2} > x_{2k-1} < x_{2k}$$$, or  $$$x_1 > x_2 < x_3 > \ldots > x_{2k-2} < x_{2k-1} > x_{2k}$$$. You need to choose a subset of distinct indices $$$i_1, i_2, \ldots, i_t$$$ and their order in a way that if you write down all numbers from the pairs in a single sequence (the sequence would be $$$a_{i_1}, b_{i_1}, a_{i_2}, b_{i_2}, \ldots, a_{i_t}, b_{i_t}$$$), this sequence is good.What is the largest subset of indices you can choose? You also need to construct the corresponding index sequence $$$i_1, i_2, \ldots, i_t$$$.

The first line contains single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$) — the number of pairs. Each of the next $$$n$$$ lines contain two numbers — $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 2 \cdot n$$$) — the elements of the pairs. It is guaranteed that all integers in the pairs are distinct, that is, every integer from $$$1$$$ to $$$2 \cdot n$$$ is mentioned exactly once.

In the first line print a single integer $$$t$$$ — the number of pairs in the answer. Then print $$$t$$$ distinct integers $$$i_1, i_2, \ldots, i_t$$$ — the indexes of pairs in the corresponding order.

NoteThe final sequence in the first example is $$$1 < 7 > 3 < 5 > 2 < 10$$$.The final sequence in the second example is $$$6 > 1 < 3 > 2 < 5 > 4$$$.

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let l =
    (* List.init n (fun i -> i+1) *)
    let l = ref [] in
    for i = 1 to n do
      l := i :: !l
    done;
    List.rev !l
  in
  let lu, ld =
    List.fold_left
      (fun (lu, ld) idx ->
         let a, b = Scanf.scanf "%d %d\n" (fun x y -> x, y) in
         if a < b then (a, b, idx) :: lu, ld else lu, (a, b, idx)::ld
      ) ([], []) l
  in
  if List.length lu < List.length ld
  then (* ld*)
    begin
      Printf.printf "%d\n" (List.length ld);
      List.sort (fun (a1, b1, _) (a2, b2, _) -> compare a1 a2) ld
      |> List.iter (fun (_, _, idx) -> Printf.printf "%d " idx)
    end
  else begin
    Printf.printf "%d\n" (List.length lu);
    List.sort (fun (a1, b1, _) (a2, b2, _) -> compare a2 a1) lu
    |> List.iter (fun (_, _, idx) -> Printf.printf "%d " idx)
  end
;;


The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries:  The query to swap two table rows;  The query to swap two table columns;  The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.

The first line contains three space-separated integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 500000) — the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each — the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≤ p ≤ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers.   If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≤ x, y ≤ m, x ≠ y);  If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≤ x, y ≤ n, x ≠ y);  If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≤ x ≤ n, 1 ≤ y ≤ m).  The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns — from left to right from 1 to m.

For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.

NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.

open Scanf
open Str

let (|>) x f = f x
let identity x = x
let regexp_spc = regexp " "

let swap ar x y =
  let tmp = ar.(x) in
  ar.(x) <- ar.(y);
  ar.(y) <- tmp

let _ =
  let n :: m :: k :: _ = () |> read_line |> (split regexp_spc) |> List.map int_of_string in
  let mp = Array.make n (Array.make 0 0) in
  for i = 0 to n-1 do
    mp.(i) <-
      () |> read_line |> (split regexp_spc) |> List.map int_of_string |> Array.of_list
  done;

  let rs = Array.init n identity in
  let cs = Array.init m identity in
  for i = 1 to k do
    let op = read_line () in
    let m, x, y = sscanf op "%c %d %d" (fun m x y -> m, x-1, y-1) in
    match m with
      | 'c' -> swap cs x y
      | 'r' -> swap rs x y
      | 'g' -> mp.(rs.(x)).(cs.(y)) |> string_of_int |> print_endline
  done


Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as aij.In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 104) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element aij (1 ≤ aij ≤ 104).

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).

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

let n = read_int ();;
let m = read_int ();;
let d = read_int ();;

let data = Array.init (n*m) (fun i -> read_int ());;

Array.sort compare data;;

let isok = ref true;;

let solve a b = if (b-a) mod d = 0 then true else false in
  for i = 1 to (n*m-1) do
        isok := !isok && (solve data.(i) data.(i-1))
  done;;

let work ii data = let cnt = ref 0 in
     for i = 0 to (ii-1) do cnt := !cnt + (data.(ii) - data.(i))/d done;
     for i = (ii+1) to (n*m-1) do cnt := !cnt + (data.(i) - data.(ii))/d done;
     !cnt;;

if n*m = 1 then Printf.printf "0\n"
else if !isok = false then Printf.printf "-1\n"
else
   if (n*m) mod 2 = 0 then
         let a = work ((n*m)/2-1) data in let b = work ((n*m)/2) data in Printf.printf "%d\n" (min a b)
   else
         let a = work ((n*m+1)/2-1) data in Printf.printf "%d\n" a;;


Bizon the Champion isn't just attentive, he also is very hardworking.Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.

The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a single integer — the minimum number of strokes needed to paint the whole fence.

NoteIn the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.In the third sample there is only one plank that can be painted using a single vertical stroke.

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 rec licz l r =
  (*dbg l; dbg r; pnl();*)
  let minek = ref max_int in
  for i = l to r do
    minek := min !minek a.(i);
  done;

  let pocz = ref (-1) and wyn = ref !minek in
  for i = l to r do
    if a.(i) - !minek <> 0 then begin
      a.(i) <- a.(i) - !minek;
      if !pocz = -1 then pocz := i;
      if i = r || a.(i + 1) - !minek = 0 then begin
        wyn := !wyn + (licz !pocz i);
        pocz := -1;
      end;
    end;
  done;
  min (r - l + 1) !wyn;;

print_int (licz 0 (n - 1));;


Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:  Each boy plays for exactly one team (x + y = n).  The sizes of teams differ in no more than one (|x - y| ≤ 1).  The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.

The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.

On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.

NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.

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

let () =
  let n = read_int() in

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

    let n1 = (n+1)/2 in
    let n2 = n-n1 in

      Printf.printf "%d\n" n1;
      for i=0 to n1-1 do
	Printf.printf "%d " (snd a.(2*i))
      done;
      print_newline();

      Printf.printf "%d\n" n2;
      for i=0 to n2-1 do
	Printf.printf "%d " (snd a.(2*i+1))
      done;
      print_newline();


Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

open Scanf;;
open Printf;;
open Str;;

let split_by_space = split (regexp " +")

let rec head n ls =
  if n < 0 then invalid_arg "head : passed negative integer"
  else
    match (n, ls) with
      (0, _) -> []
    | (n, []) -> failwith "head : list is too short"
    | (n, x::xs) -> x :: (head (n - 1) xs)

let rec tail n ls =
  if n < 0 then invalid_arg "tail : passed negative integer"
  else
    match (n, ls) with
      (0, ls) -> ls
    | (n, []) -> failwith "tail : list is too short"
    | (n, x::xs) -> tail (n - 1) xs

module UF = struct
  type t = int array

  let make n = Array.make n (-1)

  let rec root x uf =
    if uf.(x) < 0 then x
    else (uf.(x) <- root uf.(x) uf; uf.(x))

  let union_set x y uf =
    let x = root x uf and
        y = root y uf in
    begin
      if x != y then
        let x, y = if uf.(y) < uf.(x) then y, x else x, y in
        begin
          uf.(x) <- uf.(x) + uf.(y);
          uf.(y) <- x
        end
    end;
    x != y

  let find_set x y uf = root x uf = root y uf

  let size x uf = - uf.(x)
end

let input () =
  let f () =
    let n = scanf "%d " (fun x -> x) in
    let a_arr = Array.make n 0 in
    for i = 0 to (n - 1) do
      a_arr.(i) <- scanf "%d " (fun x -> x)
    done;
    (n, a_arr) in
  let (n, a_arr) = f () and
      (m, b_arr) = f () in
  (n, a_arr, m, b_arr)

let get_fst_count lst =
  let rec match_count tar = function
      [] -> 0
    | x :: xs when x = tar -> 1 + match_count tar xs
    | _ -> 0 in
  match lst with
    x :: xs -> 1 + match_count x xs
  | [] -> invalid_arg ""

let solve (n, a_arr, m, b_arr) =
  let rat_lst =
    ArrayLabels.fold_left ~init:[] ~f:(fun acc x ->
      ArrayLabels.fold_left ~init:acc ~f:(fun acc y ->
        if y mod x = 0 then (y / x) :: acc else acc) b_arr) a_arr in
  let sorted_rat_lst = List.sort (fun x y -> y - x) rat_lst in
  get_fst_count sorted_rat_lst

let () =
  let inp = input () in
  printf "%d\n" (solve inp)


DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

The first line contains a single string s (1 ≤ |s| ≤ 103). The second line contains a single integer k (0 ≤ k ≤ 103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.

Print a single integer — the largest possible value of the resulting string DZY could get.

NoteIn the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

module H = Hashtbl ;;

let ctbl = H.create 10 ;;

let (@@) f x = f x ;;

let solve str n m =
  let sum = ref 0L in
  let (+/) = Int64.add in
  let ( */ ) = Int64.mul in
  for i = 0 to String.length str - 1 do
    sum := !sum +/ (Int64.of_int i +/ 1L) */ H.find ctbl str.[i]
  done;
  Printf.eprintf "%Ld\n" !sum;
  for i = String.length str + 1 to String.length str + n do
    sum := !sum +/ Int64.of_int i */ m
  done;
  Printf.printf "%Ld\n" !sum
;;

let () =
  Scanf.scanf "%s " (fun str ->
  Scanf.scanf "%d " (fun n ->
  let m = ref (-1L) in
  for i = 0 to 25 do
    Scanf.scanf "%d " (fun n ->
      H.add ctbl (Char.chr (Char.code 'a' + i)) (Int64.of_int n);
      m := max !m @@ Int64.of_int n;)
  done;
  Printf.eprintf "%Ld\n" !m;
  solve str n !m));
;;

module H = Hashtbl ;;

let ctbl = H.create 10 ;;

let (@@) f x = f x ;;

let solve str n m =
  let sum = ref 0 in
  for i = 0 to String.length str - 1 do
    sum := !sum + (i + 1) * H.find ctbl str.[i]
  done;
  Printf.eprintf "%d\n" !sum;
  for i = String.length str to String.length str + n - 1 do
    sum := !sum + (i + 1) * m
  done;
  Printf.printf "%d\n" !sum
;;

let () =
  Scanf.scanf "%s " (fun str ->
  Scanf.scanf "%d " (fun n ->
  let m = ref (-1) in
  for i = 0 to 25 do
    Scanf.scanf "%d " (fun n ->
      H.add ctbl (Char.chr (Char.code 'a' + i))  n;
      m := max !m n;)
  done;
  Printf.eprintf "%d\n" !m;
  solve str n !m));
;;