People worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.— Pedro DomingosYou work for a well-known department store that uses leading technologies and employs mechanistic work — that is, robots!The department you work in sells $$$n \cdot k$$$ items. The first item costs $$$1$$$ dollar, the second item costs $$$2$$$ dollars, and so on: $$$i$$$-th item costs $$$i$$$ dollars. The items are situated on shelves. The items form a rectangular grid: there are $$$n$$$ shelves in total, and each shelf contains exactly $$$k$$$ items. We will denote by $$$a_{i,j}$$$ the price of $$$j$$$-th item (counting from the left) on the $$$i$$$-th shelf, $$$1 \le i \le n, 1 \le j \le k$$$.Occasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items $$$a_{i,l}, a_{i,l+1}, \ldots, a_{i,r}$$$ for some shelf $$$i$$$ and indices $$$l \le r$$$? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.You care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array $$$a$$$ that:  Every number from $$$1$$$ to $$$n \cdot k$$$ (inclusively) occurs exactly once.  For each $$$i, l, r$$$, the mean price of items from $$$l$$$ to $$$r$$$ on $$$i$$$-th shelf is an integer. Find out if such an arrangement is possible, and if it is, give any example of such arrangement.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 500$$$) — the number of shelves and length of each shelf, respectively. It is guaranteed that the sum $$$n$$$ over all test cases does not exceed $$$500$$$ and the sum $$$k$$$ over all test cases does not exceed $$$500$$$.

Print the answer for each test case. If such an arrangement exists, print "YES" on a single line. After that, print any example on $$$n$$$ lines of $$$k$$$ numbers each, one line per shelf. Each number from $$$1$$$ to $$$n \cdot k$$$ must occur exactly once in the output. If no good arrangement exists, print a single word "NO" on its own line.

Scanf.scanf "%d" (fun t ->
    for i = 1 to t do
        Scanf.scanf " %d %d" (fun n k ->
            if k = 1 || n mod 2 = 0 then (
                print_endline "YES";
                for i = 1 to n do
                    for j = 0 to k - 1 do Printf.printf "%d " (i + j * n) done;
                    print_newline ()
                done
            ) else (
                print_endline "NO"
            )
        )
    done
)

Scanf.scanf "%d" (fun t ->
    let check k n =
        let rec loop i =
            if i = 0 then true else
            if n mod i = 0 then loop (i - 1) else false
        in
        loop k
    in
    for i = 1 to t do
        Scanf.scanf " %d %d" (fun n k ->
            if check k n then (
                print_endline "YES";
                for i = 1 to n do
                    for j = 0 to k - 1 do Printf.printf "%d " (i + j * n) done;
                    print_newline ()
                done
            ) else (
                print_endline "NO"
            )
        )
    done
)


Recall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples:  for the array $$$[0, 0, 1, 0, 2]$$$ MEX equals to $$$3$$$ because numbers $$$0, 1$$$ and $$$2$$$ are presented in the array and $$$3$$$ is the minimum non-negative integer not presented in the array;  for the array $$$[1, 2, 3, 4]$$$ MEX equals to $$$0$$$ because $$$0$$$ is the minimum non-negative integer not presented in the array;  for the array $$$[0, 1, 4, 3]$$$ MEX equals to $$$2$$$ because $$$2$$$ is the minimum non-negative integer not presented in the array. You are given an empty array $$$a=[]$$$ (in other words, a zero-length array). You are also given a positive integer $$$x$$$.You are also given $$$q$$$ queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ and means that you have to append one element $$$y_j$$$ to the array. The array length increases by $$$1$$$ after a query.In one move, you can choose any index $$$i$$$ and set $$$a_i := a_i + x$$$ or $$$a_i := a_i - x$$$ (i.e. increase or decrease any element of the array by $$$x$$$). The only restriction is that $$$a_i$$$ cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of $$$q$$$ queries (i.e. the $$$j$$$-th answer corresponds to the array of length $$$j$$$).Operations are discarded before each query. I.e. the array $$$a$$$ after the $$$j$$$-th query equals to $$$[y_1, y_2, \dots, y_j]$$$.

The first line of the input contains two integers $$$q, x$$$ ($$$1 \le q, x \le 4 \cdot 10^5$$$) — the number of queries and the value of $$$x$$$. The next $$$q$$$ lines describe queries. The $$$j$$$-th query consists of one integer $$$y_j$$$ ($$$0 \le y_j \le 10^9$$$) and means that you have to append one element $$$y_j$$$ to the array.

Print the answer to the initial problem after each query — for the query $$$j$$$ print the maximum value of MEX after first $$$j$$$ queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.

NoteIn the first example:  After the first query, the array is $$$a=[0]$$$: you don't need to perform any operations, maximum possible MEX is $$$1$$$.  After the second query, the array is $$$a=[0, 1]$$$: you don't need to perform any operations, maximum possible MEX is $$$2$$$.  After the third query, the array is $$$a=[0, 1, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$.  After the fourth query, the array is $$$a=[0, 1, 2, 2]$$$: you don't need to perform any operations, maximum possible MEX is $$$3$$$ (you can't make it greater with operations).  After the fifth query, the array is $$$a=[0, 1, 2, 2, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3]$$$. Now MEX is maximum possible and equals to $$$4$$$.  After the sixth query, the array is $$$a=[0, 1, 2, 2, 0, 0]$$$: you can perform $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$. The array changes to be $$$a=[0, 1, 2, 2, 3, 0]$$$. Now MEX is maximum possible and equals to $$$4$$$.  After the seventh query, the array is $$$a=[0, 1, 2, 2, 0, 0, 10]$$$. You can perform the following operations:   $$$a[3] := a[3] + 3 = 2 + 3 = 5$$$,  $$$a[4] := a[4] + 3 = 0 + 3 = 3$$$,  $$$a[5] := a[5] + 3 = 0 + 3 = 3$$$,  $$$a[5] := a[5] + 3 = 3 + 3 = 6$$$,  $$$a[6] := a[6] - 3 = 10 - 3 = 7$$$,  $$$a[6] := a[6] - 3 = 7 - 3 = 4$$$.  The resulting array will be $$$a=[0, 1, 2, 5, 3, 6, 4]$$$. Now MEX is maximum possible and equals to $$$7$$$.

open! Printf;;

module String = struct
	include String
	let split c str =
		let str = String.concat "" [str; String.make 1 c] in
		let cur = ref [] in
		let res = ref [] in
		String.iter (fun a ->
			match a = c with
			| false -> cur := (String.make 1 a) :: !cur
			| true ->
				let char_list = List.rev (!cur) in
				res := (String.concat "" char_list) :: !res;
				cur := []) str ;
			List.rev !res
	;;
end;;

let read_int_list () =
	read_line () |> String.split ' ' |> List.map int_of_string
;;

let read_2_ints () =
	match read_int_list () with
	| [a; b] -> a, b
	| _ -> assert false
;;

let n, x = read_2_ints () in
let arr = Array.make n 0 in
let res = ref 0 in
for _=1 to n do
	let i = read_int () mod x in
	let get = Array.get arr in
	Array.set arr i ((get i) + 1);
	while ((get (!res mod x)) > 0) do
		let ind = !res mod x in
		Array.set arr ind ((get ind) - 1);
		incr res
	done;
	printf "%d\n" !res
done;;


Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.

The first line contains integer n (3 ≤ n ≤ 100) — amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness.

Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order.

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

let find_rare_parity array =
    let rec loop i odds evens =
        if i < 3
        then
            if array.(i) mod 2 > 0
            then
                loop (i + 1) (odds + 1) evens
            else
                loop (i + 1) odds (evens + 1)
        else
            if odds > evens
            then
                0
            else
                1
    in loop 0 0 0

let get_index parity array l =
    let rec loop i =
        if i < l
        then
            if array.(i) mod 2 = parity
            then
                i + 1
            else
                loop (i + 1)
        else
            failwith "Corrupted input"
    in loop 0

let solve () =
    let l = read () in
    let numbers = Array.init l (fun x -> read ()) in
    get_index (find_rare_parity numbers) numbers l

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

let () = print (solve ())

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

let find_rare_parity array =
    let rec loop i odds evens =
        if i < 3
        then
            if array.(i) mod 2 > 0
            then
                loop (i + 1) (odds + 1) evens
            else
                loop (i + 1) odds (evens + 1)
        else
            if odds > evens
            then
                `even
            else
                `odd
    in loop 0 0 0

let get_index parity array l =
    let rec loop i =
        if i < l
        then
            if parity = `odd
            then
                if array.(i) mod 2 > 0
                then
                    i + 1
                else
                    loop (i + 1)
            else
                if array.(i) mod 2 = 0
                then
                    i + 1
                else
                    loop (i + 1)
        else
            failwith "Corrupted input"
    in loop 0

let solve () =
    let l = read () in
    let numbers = Array.init l (fun x -> read ()) in
    get_index (find_rare_parity numbers) numbers l

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

let () = print (solve ())

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

let find_rare_parity array =
    let rec loop i odds evens =
        if i < 3
        then
            if array.(i) mod 2 > 0
            then
                loop (i + 1) (odds + 1) evens
            else
                loop (i + 1) odds (evens + 1)
        else
            if odds > evens
            then
                `even
            else
                `odd
    in loop 0 0 0

let get_odd_index array l =
    let rec loop i =
        if i < l
        then
            if array.(i) mod 2 > 0
            then
                i + 1
            else
                loop (i + 1)
        else
            failwith "No odd numbers"
    in loop 0

let get_even_index array l =
    let rec loop i =
        if i < l
        then
            if array.(i) mod 2 = 0
            then
                i + 1
            else
                loop (i + 1)
        else
            failwith "No even numbers"
    in loop 0

let solve () =
    let l = read () in
    let numbers = Array.init l (fun x -> read ()) in
    if find_rare_parity numbers = `odd
    then
        get_odd_index numbers l
    else
        get_even_index numbers l

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

let () = print (solve ())

let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let a_lst = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in

  let o_l = List.mapi (fun i x -> if x mod 2 <> 0 then i+1 else -1) a_lst
            |> List.filter (fun x -> x <> -1)
  in
  let e_l = List.mapi (fun i x -> if x mod 2 = 0 then i+1 else -1) a_lst
            |> List.filter (fun x -> x <> -1)
  in

  if List.length o_l = 1 then
    Printf.printf "%d\n" @@ List.hd o_l
  else
    Printf.printf "%d\n" @@ List.hd e_l

let rec split s i acc =
begin
  if i > String.length s
  then List.rev acc
  else
      let first =
      if String.contains_from s i ' '
         then  String.index_from s i ' '
         else String.length s
    in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc)
end in
let rec find n xs =
   match xs with
  |  (1::0::0::_) | (0::1::1::_) -> n+0
  |  (0::1::0::_) | (1::0::1::_) -> n+1
  |  (0::0::1::_) | (1::1::0::_) -> n+2
  | bs -> find (n+1) (List.tl bs)
in
let _ = int_of_string (read_line ()) in
let xs = split (read_line ()) 0 [] in
print_int (xs |> List.map (fun x -> x mod 2 ) |> find 1 )

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

let () =
  let n = read_int () in
  let rec loop cnt_ev cnt_od lst_ev lst_od = function
    | 0 -> if cnt_ev = 1 then lst_ev else lst_od
    | c -> (
      let num = read_int () in
      if num mod 2 = 0 then
        loop (cnt_ev+1) cnt_od c lst_od (c - 1)
      else
        loop cnt_ev (cnt_od+1) lst_ev c (c - 1)
    ) in
  Printf.printf "%d\n" (n - (loop 0 0 0 0 n) + 1)

let index_of_list elm lst =
  let rec loop lst index =
    match lst with
      | [] -> -1
      | h :: t ->
	if h = elm then index
	else loop t (index+1)
  in
  loop lst 0

let solve lst =
  let evens = List.filter (fun x -> x mod 2 = 0) lst in
  if List.length evens = 1 then (index_of_list (List.hd evens) lst)+1
  else
    let odds = List.filter (fun x -> x mod 2 = 1) lst in
    (index_of_list (List.hd odds) lst)+1

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

let _ =
  let lst = Scanf.scanf " %d" some_int in
  Printf.printf "%d\n" (solve (List.rev lst))

let id x = x in
let (@.) f g = fun x -> f @@ g x in
let scan_int () = Scanf.scanf " %d" id in
let rec read_n_ints n = let i = scan_int () in
        if n = 1 then [i]
        else [i] @ (read_n_ints @@ n-1) in

let rec find_first_index p l = match l with
        | [] -> 0
        | hd :: tl when p hd -> 0
        | _ :: tl -> 1 + (find_first_index p tl) in

let n = scan_int () in
let l = read_n_ints n in
let is_even x = x mod 2 = 0 in
let n_even = l |> List.filter is_even |> List.length in
let index = if n_even = 1 then find_first_index is_even l
            else find_first_index (not @. is_even) l in
Printf.printf "%d\n" @@ 1 + index

let index_of_list elm lst =
  let rec loop lst index =
    match lst with
      | [] -> -1
      | h :: t ->
	if h = elm then index
	else loop t (index+1)
  in
  loop lst 0

let solve lst =
  let evens = List.filter (fun x -> x mod 2 = 0) lst in
  if List.length evens = 1 then (index_of_list (List.hd evens) lst)+1
  else
    let odds = List.filter (fun x -> x mod 2 = 1) lst in
    (index_of_list (List.hd odds) lst)+1

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

let _ =
  let lst = Scanf.scanf " %d" some_int in
  Printf.printf "%d\n" (solve lst)


You are given 2 arrays $$$a$$$ and $$$b$$$, both of size $$$n$$$. You can swap two elements in $$$b$$$ at most once (or leave it as it is), and you are required to minimize the value $$$$$$\sum_{i}|a_{i}-b_{i}|.$$$$$$Find the minimum possible value of this sum.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le {10^9}$$$).  The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le {10^9}$$$).

Output the minimum value of $$$\sum_{i}|a_{i}-b_{i}|$$$.

NoteIn the first example, we can swap the first and fifth element in array $$$b$$$, so that it becomes $$$[ 5, 2, 3, 4, 1 ]$$$.Therefore, the minimum possible value of this sum would be $$$|5-5| + |4-2| + |3-3| + |2-4| + |1-1| = 4$$$.In the second example, we can swap the first and second elements. So, our answer would be $$$2$$$.

let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> Int64.of_int x);;
let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> x);;
let read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;
let comp (a, b) (c, d) = if (Int64.compare a c) = 0 then Int64.compare b d else Int64.compare a c;;

let min x y = if Int64.compare x y < 0 then x else y

let max x y = if Int64.compare x y > 0 then x else y

let empty_read x = read_int64 ();;

let n = read_int ();;
let a = Array.init n empty_read;;
let b = Array.init n empty_read;;
let c = (Array.init n (fun i ->
    if Int64.compare a.(i) b.(i) <= 0
    then (a.(i), b.(i), 0)
    else (b.(i), a.(i), 1)));;

let _ = Array.stable_sort (fun (x, y, z) (u, v, w) ->
    if Int64.compare x u != 0
    then Int64.compare x u
    else
        if Int64.compare y v != 0
        then Int64.compare y v
        else compare z w) c;;

let mx = Array.make 2 Int64.zero;;

let ans = Array.fold_left Int64.add Int64.zero (
    Array.map (fun (a, b, c) -> Int64.sub b a) c);;

let diff = ref Int64.zero;;

for i = 0 to n - 1 do
    match c.(i) with (a, b, x) ->
        diff := max !diff (Int64.sub (min b mx.(1 - x)) a);
        mx.(x) <- max mx.(x) b
done;;

Printf.printf "%s\n" (Int64.to_string (Int64.sub ans (Int64.mul 2L !diff)))

let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> Int64.of_int x);;
let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> x);;
let read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;
let comp (a, b) (c, d) = if (Int64.compare a c) = 0 then Int64.compare b d else Int64.compare a c;;
let min x y = if Int64.compare x y < 0 then x else y
let max x y = if Int64.compare x y > 0 then x else y
let empty_read x = read_int64 ();;

let n = read_int ();;
let a = Array.init n empty_read;;
let b = Array.init n empty_read;;
let c = (Array.init n (fun i ->
    if Int64.compare a.(i) b.(i) <= 0
    then (a.(i), b.(i), 0)
    else (b.(i), a.(i), 1)));;
let _ = Array.sort (fun (x, y, z) (u, v, w) ->
    if Int64.compare x u != 0
    then Int64.compare x u
    else
        if Int64.compare y v != 0
        then Int64.compare y v
        else compare z w) c;;
let mx = Array.make 2 Int64.zero;;
let ans = Array.fold_left Int64.add Int64.zero (
    Array.map (fun (a, b, c) -> Int64.sub b a) c);;

let diff = ref Int64.zero;;
for i = 0 to n - 1 do
    match c.(i) with (a, b, x) ->
        diff := max !diff (Int64.sub (min b mx.(1 - x)) a);
        mx.(x) <- max mx.(x) b
done;;

Printf.printf "%s\n" (Int64.to_string (Int64.sub ans (Int64.mul 2L !diff)));;


In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with n - k + 1 strings s1, s2, ..., sn - k + 1, each either "YES" or "NO".   The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise).  The string s2 describes a group of soldiers 2 through k + 1.  And so on, till the string sn - k + 1 that describes a group of soldiers n - k + 1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names — it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution.

The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 50) — the number of soldiers and the size of a group respectively. The second line contains n - k + 1 strings s1, s2, ..., sn - k + 1. The string si is "YES" if the group of soldiers i through i + k - 1 is effective, and "NO" otherwise.

Find any solution satisfying all given conditions. In one line print n space-separated strings, denoting possible names of soldiers in the order. The first letter of each name should be uppercase, while the other letters should be lowercase. Each name should contain English letters only and has length from 1 to 10. If there are multiple valid solutions, print any of them.

Adam Bob Bob Cpqepqwer Limak Adam Bob Adam

R Q Ccccccccc Ccocc Ccc So Strong Samples Ccc

NoteIn the first sample, there are 8 soldiers. For every 3 consecutive ones we know whether they would be an effective group. Let's analyze the provided sample output:  First three soldiers (i.e. Adam, Bob, Bob) wouldn't be an effective group because there are two Bobs. Indeed, the string s1 is "NO".  Soldiers 2 through 4 (Bob, Bob, Cpqepqwer) wouldn't be effective either, and the string s2 is "NO".  Soldiers 3 through 5 (Bob, Cpqepqwer, Limak) would be effective, and the string s3 is "YES".  ...,  Soldiers 6 through 8 (Adam, Bob, Adam) wouldn't be effective, and the string s6 is "NO".

open Printf
open Scanf

let l2n c = (int_of_char c) - (int_of_char 'a')
let n2l n = char_of_int ((int_of_char 'a') + n)
let toupper = Char.uppercase

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let k = read_int () in
  let eff = Array.init (n-k+1) (fun _ -> read_string() = "YES") in

  let name = ref 0 in

  let get_new_name () =
    let dig0 = !name mod 26 in
    let dig1 = !name / 26 in
    let s0 = String.make 1 (toupper (n2l dig0)) in
    let s1 = String.make 1 (n2l dig1) in
    name := 1 + !name;
    s0 ^ s1
  in

  let name_array = Array.make n "" in

  for i=0 to k-2 do
    name_array.(i) <- get_new_name ()
  done;

  for i=k-1 to n-1 do
    if eff.(i-(k-1)) then (
      name_array.(i) <- get_new_name ()
    ) else (
      name_array.(i) <- name_array.(i-(k-1))
    )
  done;

  for i=0 to n-1 do
    printf "%s " name_array.(i)
  done;
  print_newline()


Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.

The first line contains a single number n (2 ≤ n ≤ 1000) — the number of the tram's stops.  Then n lines follow, each contains two integers ai and bi (0 ≤ ai, bi ≤ 1000) — the number of passengers that exits the tram at the i-th stop, and the number of passengers that enter the tram at the i-th stop. The stops are given from the first to the last stop in the order of tram's movement.   The number of people who exit at a given stop does not exceed the total number of people in the tram immediately before it arrives at the stop. More formally, . This particularly means that a1 = 0.  At the last stop, all the passengers exit the tram and it becomes empty. More formally, .  No passenger will enter the train at the last stop. That is, bn = 0.

Print a single integer denoting the minimum possible capacity of the tram (0 is allowed).

NoteFor the first example, a capacity of 6 is sufficient:   At the first stop, the number of passengers inside the tram before arriving is 0. Then, 3 passengers enter the tram, and the number of passengers inside the tram becomes 3.  At the second stop, 2 passengers exit the tram (1 passenger remains inside). Then, 5 passengers enter the tram. There are 6 passengers inside the tram now.  At the third stop, 4 passengers exit the tram (2 passengers remain inside). Then, 2 passengers enter the tram. There are 4 passengers inside the tram now.  Finally, all the remaining passengers inside the tram exit the tram at the last stop. There are no passenger inside the tram now, which is in line with the constraints. Since the number of passengers inside the tram never exceeds 6, a capacity of 6 is sufficient. Furthermore it is not possible for the tram to have a capacity less than 6. Hence, 6 is the correct answer.

let _ =
    let main () =
        let n = Scanf.sscanf (read_line ()) "%d" (fun n -> n) in
        let rec loop i cur m =
            if i = 0 then Printf.printf "%d\n" m else
                let (a, b) = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> a, b) in
                let cur = cur - a + b in
                let m = max cur m in
                loop (i - 1) cur m
        in
        loop n 0 0
    in
    main ()

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

let rec at_trainstop ppl_inside current_max n =
    if n > 0
    then
        let new_ppl = Scanf.scanf "%d %d " (fun a b -> (-a + b)) in
        at_trainstop (ppl_inside + new_ppl) (Pervasives.max current_max (ppl_inside + new_ppl)) (n - 1)
    else
        current_max

let solve input = at_trainstop 0 0 input

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

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

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

let if_max max ppl_inside =
    if ppl_inside > max
    then
        ppl_inside
    else
        max

let rec at_trainstop ppl_inside max n =
    if n > 0
    then
        let new_ppl = Scanf.scanf "%d %d " (fun a b -> (-a + b)) in
        at_trainstop (ppl_inside + new_ppl) (if_max max (ppl_inside + new_ppl)) (n - 1)
    else
        max

let solve input = at_trainstop 0 0 input

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

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

let rec tram n l m o i =
	if n = 0 then m
	else Scanf.scanf "%d %d\n" (fun oo ii ->
		tram (n-1) (l-o+i) (max (l-o+i) m) oo ii
	)
;;

let () =
	let n = read_int () in
	print_int (tram n 0 0 0 0)
;;

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

let max a b = if (a > b) then a else b

let () =
	let n = read_int() in
	let a = Array.make (n + 1) 0 in
	let b = Array.make (n + 1) 0 in
	let sum = ref 0 in
	let mx = ref 0 in
		for i = 1 to n do
			a.(i) <- read_int();
			b.(i) <- read_int();
			sum := !sum - a.(i) + b.(i);
			mx := max !mx !sum;
		done;
		printf "%d\n" (!mx)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and r=ref 0 and s=ref 0;;
for i=1 to n do
   let x=read_int() and y=read_int() in
   r:= !r+y-x;
   s:=max !s !r
done;;
Printf.printf "%d" !s;;

open Scanf
open Printf

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

let nn = n + 10

let a = Array.make nn (-1);;
let b = Array.make nn (-1);;
let c = Array.make nn (-1);; (*The number of people on tram after each stop*)

for i = 1 to n do
  let (ai,bi) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " ( fun x y -> (x,y) ) in
  a.(i) <- ai; b.(i) <- bi
done
;;

let () = c.(0) <- 0;;

for i = 1 to n do
  c.(i) <- (c.(i-1) + b.(i-1) - a.(i-1))
done
;;

let z = Array.fold_left (fun x y -> if x > y then x else y ) (-1) c
in print_int z; print_endline ""

let solve n stops =
  let rec loop stops passenger max_capacity = match stops with
      [] -> max_capacity
    | first :: rest ->
      loop rest (passenger+(snd first)-(fst first)) (max passenger max_capacity)
  in
  loop stops 0 0;;

let rec get_stops n stops=
  if n <= 0
  then stops
  else get_stops (n-1) (Scanf.scanf "%d %d\n" (fun x y -> (x, y)) :: stops)

let get_stops n = List.rev (get_stops n [])

let _ =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let stops = get_stops n in
  Printf.printf "%d\n" (solve n stops)

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

let solve n =
  let rec find_max n max sum = match n with
    | 0 -> max
    | n -> let a = read_int ()
           and b = read_int () in
           let new_sum = sum - a + b in
             if max > new_sum
             then find_max (n - 1) max new_sum
             else find_max (n - 1) new_sum new_sum
  in find_max n 0 0

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

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

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

exception Error of string

let inf = 1000000000;;
let eps = 1e-11;;

let _ =
  let n = sf "%d\n" (fun x -> x) in
  let a = ref 0 in
  let b = ref 0 in
  let res = ref 0 in
  for i = 1 to n do
    let (x, y) = sf "%d %d\n" (fun x y -> x, y) in
    a := !a + x;
    b := !b + y;
    res := max !res (!b - !a)
  done;
  pf "%d\n" !res
;;

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

let max a b =
  if a < b then b
  else a

let () =
  let n = ref (read_int ()) in
  let ans = ref 0 in
  let count_now = ref 0 in
  for i = 1 to !n do
    count_now := !count_now + read_int () - read_int ();
    ans := max !ans !count_now;
  done;
  Printf.printf "%d" !ans;

let read_list () =
  let n = read_int()
  and l = ref [] in
    for i = 1 to n do
      let pair = Scanf.scanf " %d %d" (fun a b -> (a, b)) in
      l := pair :: !l;
    done;
    !l

let solve l =
  fst (List.fold_left
    (fun (mx, ac) (hm, hp) ->  let na = (ac + hp - hm) in (max mx na, na))
    (0, 0)
    (List.rev l))

let print_res =
  print_int

let main =
  let l = read_list () in
    print_res (solve l)

let rec tram n m o i =
	if n = 0 then m
	else let oo, ii = Scanf.scanf "%d %d\n" (fun o i -> (o, i))
		in tram (n-1) (max (m-o+i) m) oo ii
;;

let () =
	let n = read_int () in
	print_int (tram n 0 0 0)
;;

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

let max a b = if (a > b) then a else b

let () =
	let n = read_int() in
	let a = Array.make (n + 1) 0 in
	let b = Array.make (n + 1) 0 in
	let sum = ref 0 in
	let mx = ref 0 in
		for i = 1 to n do
			a.(i) <- read_int();
			b.(i) <- read_int();
			sum := !sum + a.(i) - b.(i);
			mx := max !mx !sum;
		done;
		printf "%d\n" (!mx)

open Scanf
open Printf

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

let nn = n + 10

let a = Array.make nn (-1);;
let b = Array.make nn (-1);;
let c = Array.make nn (-1);; (*The number of people on tram after each stop*)

for i = 1 to n do
  let (ai,bi) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " ( fun x y -> (x,y) ) in
  a.(i) <- ai; b.(i) <- bi
done
;;

let () = c.(0) <- 0;;

for i = 1 to n-1 do
  c.(i) <- (c.(i-1) + b.(i-1) - a.(i-1))
done
;;

let z = Array.fold_left (fun x y -> if x > y then x else y ) (-1) c
in print_int z; print_endline ""

let read_list () =
  let n = read_int()
  and l = ref [] in
    for i = 1 to n do
      let pair = Scanf.scanf " %d %d" (fun a b -> (a, b)) in
      l := pair :: !l;
    done;
    !l

let solve l =
  List.fold_left
    (fun ac (hp, hm) ->  max ac (ac - hp + hm))
    0
    l

let print_res =
  print_int

let main =
  let l = read_list () in
    print_res (solve l)


One day, Yuhao came across a problem about checking if some bracket sequences are correct bracket sequences.A bracket sequence is any non-empty sequence of opening and closing parentheses. A bracket sequence is called a correct bracket sequence if it's possible to obtain a correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, the sequences "(())()", "()" and "(()(()))" are correct, while the bracket sequences ")(", "(()" and "(()))(" are not correct.Yuhao found this problem too simple for him so he decided to make the problem harder. You are given many (not necessarily correct) bracket sequences. The task is to connect some of them into ordered pairs so that each bracket sequence occurs in at most one pair and the concatenation of the bracket sequences in each pair is a correct bracket sequence. The goal is to create as many pairs as possible.This problem unfortunately turned out to be too difficult for Yuhao. Can you help him and solve it?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of bracket sequences. Each of the following $$$n$$$ lines contains one bracket sequence — a non-empty string which consists only of characters "(" and ")". The sum of lengths of all bracket sequences in the input is at most $$$5 \cdot 10^5$$$. Note that a bracket sequence may appear in the input multiple times. In this case, you can use each copy of the sequence separately. Also note that the order in which strings appear in the input doesn't matter.

Print a single integer — the maximum number of pairs which can be made, adhering to the conditions in the statement.

NoteIn the first example, it's optimal to construct two pairs: "((     )())" and "(     )".

Scanf.(Array.(
  let n = scanf " %d" @@ fun v -> v in
  let l,r,zero = make 500010 0, make 500010 0, ref 0 in
  init n (fun _ ->
    let s = scanf " %s" @@ fun v -> v in
    let s = init (String.length s) (fun i -> s.[i]) in
    let post,pre = fold_left (fun (sum,pre) -> function
    | '(' -> (sum+1,pre)
    | ')' -> if sum=0 then (0,pre+1) else (sum-1,pre)
    | _ -> failwith ""
    ) (0,0) s in
    if post>0 && pre>0 then ()
    else if post>0 then (
      r.(post) <- r.(post) + 1
    ) else if pre>0 then (
      l.(pre) <- l.(pre) + 1
    ) else (
      zero := !zero + 1
    )
  ) |> ignore;
  fold_left (fun (sum,i) v ->
    let u = r.(i) in (sum + min u v,i+1)
  ) (!zero/2,0) l
  |> fst |> print_int
))

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  let (+=) r v = r := !r + v
  let (-=) r v = r := !r - v
  let ( *= ) r v = r := !r * v
  let (/=) r v = r := !r / v
  let (%=) r v = r := !r % v
  let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)
  let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module Int64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let slen s = String.length s
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
  let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
  let fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

let calc s =
  let cnt,pre,post = ref 0L,ref 0L,ref 0L in
  String.iteri (fun i c ->
    if c = '(' then cnt += 1L
    else (
      cnt -= 1L;
      if !cnt < 0L then (
        pre := max (!pre) (-1L*(!cnt));
      )
    )
  ) s;
  cnt := !pre;
  String.iteri (fun i c ->
    if c = '(' then cnt += 1L
    else (
      cnt -= 1L;
    )
  ) s;
  post := !cnt;
  if !cnt>0L && !pre>0L then (
    `None
  ) else if !pre>0L then (
    `Pre !pre
  ) else if !post>0L then (
    `Post !cnt
  ) else (
    `Zero
  )
let () =
  let n = gi 0 in
  let pos,neg,zero = make 600010 0L,make 600010 0L,ref 0L in
  repi 1 (i32 n) (fun i ->
    let s = scanf " %s" @@ id in
    let v = calc s in
    match v with
    | `None -> ()
    | `Pre v ->
      neg.(i32 v) <- neg.(i32 v) + 1L
    | `Post v ->
      pos.(i32 v) <- pos.(i32 v) + 1L
    | `Zero -> zero += 1L
  );
  let r = ref 0L in
  iteri (fun i v ->
    let w = neg.(i) in
    r += min v w
  ) pos;
  r += !zero/2L;
  printf "%Ld\n" !r

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  let (+=) r v = r := !r + v
  let (-=) r v = r := !r - v
  let ( *= ) r v = r := !r * v
  let (/=) r v = r := !r / v
  let (%=) r v = r := !r % v
  let max_i64_lim,min_i64_lim = Int64.(max_int,min_int)
  let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module Int64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let slen s = String.length s
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
  let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
  let fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

let calc s =
  let r = ref [] in
  let lv = ref 0L in
  String.iteri (fun i c ->
    if c = '(' then (
      r := i :: !r;
      lv += 1L;
    ) else (
      match !r with
      | i::tl -> (
        r := tl;
        lv -= 1L
      );
      | [] -> lv -= 1L;
    )
  ) s; !lv
let () =
  let n = gi 0 in
  let pos,neg,zero = make 100010 0L,make 100010 0L,ref 0L in
  repi 1 (i32 n) (fun i ->
    let s = scanf " %s" @@ id in
    let v = calc s in
    (* printf "%Ld\n" v; *)
    if v > 0L then (
      pos.(i32 v) <- pos.(i32 v) + 1L
    ) else if v < 0L then (
      neg.(-i32 v) <- neg.(-i32 v) + 1L
    ) else zero += 1L
  );
  let r = ref 0L in
  iteri (fun i v ->
    let w = neg.(i) in
    r += min v w
  ) pos;
  r += !zero/2L;
  printf "%Ld\n" !r


Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print  - 1.

The first line contains two integers n and t (1 ≤ n ≤ 105, 0 ≤ t ≤ n). The second line contains string s1 of length n, consisting of lowercase English letters. The third line contain string s2 of length n, consisting of lowercase English letters.

Print a string of length n, differing from string s1 and from s2 in exactly t characters. Your string should consist only from lowercase English letters. If such string doesn't exist, print -1.

let count s1 s2 n =
	let sam = ref [] and dif = ref [] in
	for i = 0 to n-1 do
		if s1.[i] = s2.[i]
			then sam := i :: !sam
			else dif := i :: !dif;
	done;
	!sam, !dif;;

let let_chos a b =
	if a = 'a'
		then if b = 'b'
			then 'c'
			else 'b'
		else if b = 'a'
			then if a = 'b'
				then 'c'
				else 'b'
			else 'a';;

let t_geq_dif (sam,dif) s1 s2 n t =
	let s3 = String.copy s1 in
		List.iter (fun i -> let a = let_chos (s1.[i]) (s2.[i]) in
				s3.[i] <- a) dif;
	let tab = Array.of_list sam in
		for i = 0 to t - List.length dif - 1 do
			let j = tab.(i) in
				s3.[j] <- let_chos (s1.[j]) (s2.[j]);
		done;
	s3;;

let t_l_dif (sam,dif) s1 s2 n t =
	let s3 = String.copy s1 in
	let rec aux len t' = function
		| l	when t' >= len	-> l, t'
		| a::b::q		-> (s3.[b] <- s2.[b]); aux (len-2) (t'-1) q
		| _			-> [], -1
	in
	let (a,b) = aux (List.length dif) t dif in
		if b = -1
			then "-1"
			else (let tab = Array.of_list (a @ sam) in
				for i = 0 to b-1 do
					let j = tab.(i) in
						s3.[j] <- let_chos (s1.[j]) (s2.[j]);
				done; s3);;

let main () =
	let (n,t,s1,s2) = Scanf.scanf "%d %d %s %s" (fun i j k l -> (i,j,k,l)) in
	let (sam,dif) = count s1 s2 n in
	Printf.printf "%s" (if t >= List.length dif
			then t_geq_dif (sam,dif) s1 s2 n t
			else t_l_dif (sam,dif) s1 s2 n t);;

main ();;


It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with numbers a1 + 1 to a1 + a2 and so on. See the example for a better understanding.Mole can't eat all the worms (Marmot brought a lot) and, as we all know, Mole is blind, so Marmot tells him the labels of the best juicy worms. Marmot will only give Mole a worm if Mole says correctly in which pile this worm is contained.Poor Mole asks for your help. For all juicy worms said by Marmot, tell Mole the correct answers.

The first line contains a single integer n (1 ≤ n ≤ 105), the number of piles. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103, a1 + a2 + ... + an ≤ 106), where ai is the number of worms in the i-th pile. The third line contains single integer m (1 ≤ m ≤ 105), the number of juicy worms said by Marmot. The fourth line contains m integers q1, q2, ..., qm (1 ≤ qi ≤ a1 + a2 + ... + an), the labels of the juicy worms.

Print m lines to the standard output. The i-th line should contain an integer, representing the number of the pile where the worm labeled with the number qi is.

NoteFor the sample input:  The worms with labels from [1, 2] are in the first pile.  The worms with labels from [3, 9] are in the second pile.  The worms with labels from [10, 12] are in the third pile.  The worms with labels from [13, 16] are in the fourth pile.  The worms with labels from [17, 25] are in the fifth pile.

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

let make_array () =
    let n = read () in
    let array = Array.make n (0, 0) in
    let rec loop i array prev =
        if i < n
        then
            let quantity = read () in
            let min = prev + 1 in
            let max = prev + quantity in
            let () = Array.set array i (min, max) in
            loop (i + 1) array max
        else
            (n, array)
    in loop 0 array 0

let make_list () =
    let n = read () in
    let rec loop i list =
        if i < n
        then
            let value = read () in
            loop (i + 1) (value :: list)
        else
            List.rev list
    in loop 0 []

let input () =
    let piles = make_array () in
    let worms = make_list () in
    (piles, worms)

let classify (min, max) value =
    if value >= min && value <= max
    then
        `Inside
    else
        if value < min
        then
            `To_the_left
        else
            `To_the_right

let rec binary_search array value low high =
    let mid = (low + high) / 2 in
    match classify array.(mid) value with
    | `To_the_right -> binary_search array value (mid + 1) high
    | `To_the_left -> binary_search array value low (mid - 1)
    | `Inside -> mid + 1

let wrapper (n, array) value =
    let result = binary_search array value 0 n in
    Printf.printf "%d\n" result

let solve (piles, worms) =
    List.iter (wrapper piles) worms

let () =
    solve (input ())

open Printf
open Scanf

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

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

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

  let ends = Array.make n 0L in
  ends.(0) <- a.(0);

  for i=1 to n-1 do
    ends.(i) <- ends.(i-1) ++ a.(i)
  done;

  let find i =
    let rec bsearch lo hi =
    (* must be in lo, lo+1....hi-1 *)
      if lo+1 = hi then lo else
	let m = (lo+hi)/2 in
	if i > ends.(m-1) then bsearch m hi else bsearch lo m
    in

    bsearch 0 n
  in

  for i=0 to m-1 do
    printf "%d\n" (1 + find q.(i))
  done;


There are $$$n$$$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.The university team for the Olympiad consists of $$$a$$$ student-programmers and $$$b$$$ student-athletes. Determine the largest number of students from all $$$a+b$$$ students, which you can put in the railway carriage so that:  no student-programmer is sitting next to the student-programmer;  and no student-athlete is sitting next to the student-athlete. In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).

The first line contain three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 2\cdot10^{5}$$$, $$$0 \le a, b \le 2\cdot10^{5}$$$, $$$a + b > 0$$$) — total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes. The second line contains a string with length $$$n$$$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.

Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.

NoteIn the first example you can put all student, for example, in the following way: *.AB*In the second example you can put four students, for example, in the following way: *BAB*BIn the third example you can put seven students, for example, in the following way: B*ABAB**A*BThe letter A means a student-programmer, and the letter B — student-athlete.

(* Codeforces 962 B Students in Railway Carriage *)

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

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

let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;

type lastType = P | A | O;; (* programmer, athlete, other *)

let rec tocharlist s i n cl =
	if i==n then cl
	else
		let c = s.[i] in
		tocharlist s (i + 1) n (c :: cl);;

let rec maxstud np na last maxs lc = match lc with
| [] -> maxs
| h :: t ->
	if np==0 && na==0 then maxs
	else if h=='*' then maxstud np na O maxs t
	else if last==O then begin
		if np>na then maxstud (np - 1) na P (maxs + 1) t
		else maxstud np (na - 1) A (maxs + 1) t
		end
	else if (last==P) && (na>0) then maxstud np (na - 1) A (maxs + 1) t
	else if (last==A) && (np>0) then maxstud (np - 1) na P (maxs + 1) t
	else maxstud np na O maxs t;;

let main() =
	let snab = rdln () in (* line with n a b *)
	let (n,a,b) = Scanf.sscanf snab "%d %d %d" (fun a b c -> (a,b,c)) in
	let seats = rdln () in
	let lc = tocharlist seats 0 n [] in
	let maxstu = maxstud a b O 0 lc in
	begin
		(*Printf.printf "%d %d %d\n" n a b;*)
		print_int maxstu;
		print_string "\n"
	end;;

main();;


The Smart Beaver from ABBYY has a lot of hobbies. One of them is constructing efficient hash tables. One of the most serious problems in hash tables is resolving collisions. The Beaver is interested in this problem very much and he decided to explore it in detail.We assume that the hash table consists of h cells numbered from 0 to h - 1. Objects are added to and removed from it. Every object has its own unique identifier. In addition, every object has a corresponding hash value — an integer between 0 and h - 1, inclusive. When an object is added to the table, if the cell corresponding to the hash value of the object is free, then this object goes there. If the cell is already occupied by another object, there is a collision. When an object is deleted from the table, the cell which it occupied becomes empty.The Smart Beaver has recently learned about the method of linear probing to resolve collisions. It is as follows. Let's say that the hash value for the added object equals t and cell t of the table is already occupied. Then we try to add this object to cell (t + m) mod h. If it is also occupied, then we try cell (t + 2·m) mod h, then cell (t + 3·m) mod h, and so on. Note that in some cases it's possible that the new object can not be added to the table. It is guaranteed that the input for this problem doesn't contain such situations.The operation a mod b means that we take the remainder of the division of number a by number b.This technique immediately seemed very inoptimal to the Beaver, and he decided to assess its inefficiency. So, you are given a sequence of operations, each of which is either an addition of an object to the table or a deletion of an object from the table. When adding a new object, a sequence of calls to the table is performed. Calls to occupied cells are called dummy. In other words, if the result of the algorithm described above is the object being added to cell (t + i·m) mod h (i ≥ 0), then exactly i dummy calls have been performed.Your task is to calculate the total number of dummy calls to the table for the given sequence of additions and deletions. When an object is deleted from the table, assume that no dummy calls are performed. The table is empty before performing the operations, that is, initially it doesn't contain any objects.

The first line of input contains three integers h, m and n (1 ≤ m < h), separated by spaces, where h is the size of the hash table, m is the number that is used to resolve collisions, n is the number of operations. The following n lines contains the descriptions of the operations. Their execution order corresponds to the order in which they appear in the input file. Each operation is described by a single line. The operations are described as follows:   "+ id hash"This is the format of the operation that adds an object to the table. The first character is "+" (ASCII 43), followed by a single space, then the object identifier id (0 ≤ id ≤ 109), then another space, and the hash value of the given object hash (0 ≤ hash < h). The object identifier and the hash value of this object are integers. "- id"This is the format of the operation that deletes an object from the table. The first character is "-" (ASCII 45), followed by a single space, then the object identifier id (0 ≤ id ≤ 109). The object identifier is an integer. It is guaranteed that for all addition operations the value of id is unique. It is also guaranteed that the initial data is correct, that is, it's always possible to add an object to the hash table and there won't be any deletions of nonexisting objects. The input limitations for getting 20 points are:    1 ≤ h ≤ 5000  1 ≤ n ≤ 5000  The input limitations for getting 50 points are:    1 ≤ h ≤ 5·104  1 ≤ n ≤ 5·104  The input limitations for getting 100 points are:    1 ≤ h ≤ 2·105  1 ≤ n ≤ 2·105

Print a single number — the total number of dummy calls to the hash table. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams and the %I64d specifier.

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

let g2d n = n land (-n)

let fenwick_new n =
  Array.make n 0

let fenwick_modify ft n x =
  let i = ref (n + 1) in
    while !i <= Array.length ft do
      ft.(!i - 1) <- ft.(!i - 1) + x;
      i := !i + g2d !i;
    done

let fenwick_count ft n =
  let i = ref (n + 1) in
  let res = ref 0 in
    while !i > 0 do
      res := !res + ft.(!i - 1);
      i := !i - g2d !i;
    done;
    !res

let fenwick_count2 ft m n =
  fenwick_count ft n - fenwick_count ft (m - 1)

let _ =
  let sb = Scanf.Scanning.stdib in
  let h = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make h (-1) in
  let b = Array.make (2 * h) (-1) in
  let c = Array.make h (-1) in
  let g = gcd m h in
  let () =
    let pos = ref 0 in
      for i = 0 to h - 1 do
	if c.(i) < 0 then (
	  let k = ref i in
	    for j = 0 to h / g - 1 do
	      c.(!k) <- !pos;
	      b.(!pos) <- !k;
	      b.(!pos + h / g) <- !k;
	      incr pos;
	      k := (!k + m) mod h;
	    done;
	  pos := !pos + h / g;
	)
      done
  in
  let ft = fenwick_new (2 * h) in
  let ht = Hashtbl.create h in
  let res = ref 0L in
    for i = 0 to n - 1 do
      let op = Scanf.bscanf sb "%s " (fun s -> s) in
	match op with
	  | "+" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Scanf.bscanf sb "%d " (fun s -> s) in
	      let l = ref (c.(hash) - 1) in
	      let r = ref (c.(hash) + h / g) in
		while !l < !r - 1 do
		  let m = (!l + !r) / 2 in
(*Printf.printf "step %d %d %d   %d\n" !l !r m (fenwick_count2 ft c.(hash) m);*)
		    if fenwick_count2 ft c.(hash) m < m + 1 - c.(hash)
		    then r := m
		    else l := m
		done;
		res := Int64.add !res (Int64.of_int (!r - c.(hash)));
		let hash = b.(!r) in
(*Printf.printf "add %d %d   %d %d\n" id hash !l !r;*)
		(*while a.(!j) >= 0 do
		  j := (!j + m) mod h;
		  incr res;
		done;*)
		  Hashtbl.replace ht id hash;
		  a.(hash) <- id;
		  fenwick_modify ft c.(hash) 1;
		  fenwick_modify ft (c.(hash) + h / g) 1;
	  | "-" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Hashtbl.find ht id in
		Hashtbl.remove ht id;
		a.(hash) <- -1;
		fenwick_modify ft c.(hash) (-1);
		fenwick_modify ft (c.(hash) + h / g) (-1);
	  | _ -> assert false
    done;
    Printf.printf "%Ld\n" !res;

let _ =
  let sb = Scanf.Scanning.stdib in
  let h = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make h (-1) in
  let ht = Hashtbl.create h in
  let res = ref 0 in
    for i = 0 to n - 1 do
      let op = Scanf.bscanf sb "%s " (fun s -> s) in
	match op with
	  | "+" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Scanf.bscanf sb "%d " (fun s -> s) in
	      let j = ref hash in
		while a.(!j) >= 0 do
		  j := (!j + m) mod h;
		  incr res;
		done;
		Hashtbl.replace ht id !j;
		a.(!j) <- id;
	  | "-" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Hashtbl.find ht id in
		Hashtbl.remove ht id;
		a.(hash) <- -1;
	  | _ -> assert false
    done;
    Printf.printf "%d\n" !res;

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

let g2d n = n land (-n)

let fenwick_new n =
  Array.make n 0

let fenwick_modify ft n x =
  let i = ref (n + 1) in
    while !i <= Array.length ft do
      ft.(!i - 1) <- ft.(!i - 1) + x;
      i := !i + g2d !i;
    done

let fenwick_count ft n =
  let i = ref (n + 1) in
  let res = ref 0 in
    while !i > 0 do
      res := !res + ft.(!i - 1);
      i := !i - g2d !i;
    done;
    !res

let fenwick_count2 ft m n =
  fenwick_count ft n - fenwick_count ft (m - 1)

let _ =
  let sb = Scanf.Scanning.stdib in
  let h = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make h (-1) in
  let b = Array.make (2 * h) (-1) in
  let c = Array.make h (-1) in
  let g = gcd m h in
  let () =
    let pos = ref 0 in
      for i = 0 to h - 1 do
	if c.(i) < 0 then (
	  for j = 0 to h / g - 1 do
	    c.((i + j * m) mod h) <- !pos;
	    b.(!pos) <- (i + j * m) mod h;
	    b.(!pos + h / g) <- (i + j * m) mod h;
	    incr pos
	  done;
	  pos := !pos + h / g;
	)
      done
  in
  let ft = fenwick_new (2 * h) in
  let ht = Hashtbl.create h in
  let res = ref 0 in
    for i = 0 to n - 1 do
      let op = Scanf.bscanf sb "%s " (fun s -> s) in
	match op with
	  | "+" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Scanf.bscanf sb "%d " (fun s -> s) in
	      let l = ref (c.(hash) - 1) in
	      let r = ref (c.(hash) + h / g) in
		while !l < !r - 1 do
		  let m = (!l + !r) / 2 in
(*Printf.printf "step %d %d %d   %d\n" !l !r m (fenwick_count2 ft c.(hash) m);*)
		    if fenwick_count2 ft c.(hash) m < m + 1 - c.(hash)
		    then r := m
		    else l := m
		done;
		res := !res + !r - c.(hash);
		let hash = b.(!r) in
(*Printf.printf "add %d %d   %d %d\n" id hash !l !r;*)
		(*while a.(!j) >= 0 do
		  j := (!j + m) mod h;
		  incr res;
		done;*)
		  Hashtbl.replace ht id hash;
		  a.(hash) <- id;
		  fenwick_modify ft c.(hash) 1;
		  fenwick_modify ft (c.(hash) + h / g) 1;
	  | "-" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Hashtbl.find ht id in
		Hashtbl.remove ht id;
		a.(hash) <- -1;
		fenwick_modify ft c.(hash) (-1);
		fenwick_modify ft (c.(hash) + h / g) (-1);
	  | _ -> assert false
    done;
    Printf.printf "%d\n" !res;

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

let g2d n = n land (-n)

let fenwick_new n =
  Array.make n 0

let fenwick_modify ft n x =
  let i = ref (n + 1) in
    while !i <= Array.length ft do
      ft.(!i - 1) <- ft.(!i - 1) + x;
      i := !i + g2d !i;
    done

let fenwick_count ft n =
  let i = ref (n + 1) in
  let res = ref 0 in
    while !i > 0 do
      res := !res + ft.(!i - 1);
      i := !i - g2d !i;
    done;
    !res

let fenwick_count2 ft m n =
  fenwick_count ft n - fenwick_count ft (m - 1)

let _ =
  let sb = Scanf.Scanning.stdib in
  let h = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make h (-1) in
  let b = Array.make (2 * h) (-1) in
  let c = Array.make h (-1) in
  let g = gcd m h in
  let () =
    let pos = ref 0 in
      for i = 0 to h - 1 do
	if c.(i) < 0 then (
	  for j = 0 to h / g - 1 do
	    c.((i + j * m) mod h) <- !pos;
	    b.(!pos) <- (i + j * m) mod h;
	    b.(!pos + h / g) <- (i + j * m) mod h;
	    incr pos
	  done;
	  pos := !pos + h / g;
	)
      done
  in
  let ft = fenwick_new (2 * h) in
  let ht = Hashtbl.create h in
  let res = ref 0 in
    for i = 0 to n - 1 do
      let op = Scanf.bscanf sb "%s " (fun s -> s) in
	match op with
	  | "+" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Scanf.bscanf sb "%d " (fun s -> s) in
	      let l = ref (c.(hash) - 1) in
	      let r = ref (c.(hash) + h / g) in
		while !l < !r - 1 do
		  let m = (!l + !r) / 2 in
(*Printf.printf "step %d %d %d   %d\n" !l !r m (fenwick_count2 ft c.(hash) m);*)
		    if fenwick_count2 ft c.(hash) m < m + 1 - c.(hash)
		    then r := m
		    else l := m
		done;
		res := !res + !r - c.(hash);
		let hash = b.(!r) in
(*Printf.printf "add %d %d   %d %d\n" id hash !l !r;*)
		(*while a.(!j) >= 0 do
		  j := (!j + m) mod h;
		  incr res;
		done;*)
		  Hashtbl.replace ht id hash;
		  a.(hash) <- id;
		  fenwick_modify ft !r 1;
		  fenwick_modify ft (!r + h / g) 1;
	  | "-" ->
	      let id = Scanf.bscanf sb "%d " (fun s -> s) in
	      let hash = Hashtbl.find ht id in
		Hashtbl.remove ht id;
		a.(hash) <- -1;
		fenwick_modify ft c.(hash) (-1);
		fenwick_modify ft (c.(hash) + h / g) (-1);
	  | _ -> assert false
    done;
    Printf.printf "%d\n" !res;


There's a chip in the point $$$(0, 0)$$$ of the coordinate plane. In one operation, you can move the chip from some point $$$(x_1, y_1)$$$ to some point $$$(x_2, y_2)$$$ if the Euclidean distance between these two points is an integer (i.e. $$$\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$$$ is integer).Your task is to determine the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — number of test cases. The single line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 50$$$) — the coordinates of the destination point.

For each test case, print one integer — the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.

NoteIn the first example, one operation $$$(0, 0) \rightarrow (8, 6)$$$ is enough. $$$\sqrt{(0-8)^2+(0-6)^2}=\sqrt{64+36}=\sqrt{100}=10$$$ is an integer.In the second example, the chip is already at the destination point.In the third example, the chip can be moved as follows: $$$(0, 0) \rightarrow (5, 12) \rightarrow (9, 15)$$$. $$$\sqrt{(0-5)^2+(0-12)^2}=\sqrt{25+144}=\sqrt{169}=13$$$ and $$$\sqrt{(5-9)^2+(12-15)^2}=\sqrt{16+9}=\sqrt{25}=5$$$ are integers.

let distance a b = let x1,y1 = a in
  let x2,y2 = b in (sqrt ((float_of_int (x2-x1))**2. +. (float_of_int (y2-y1))**2.))
;;

let fisi x = match float_of_int(int_of_float x) with
  |r when r = x -> true
  |_ -> false
;;

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let x , y = Scanf.sscanf (input_line stdin) "%d  %d" (fun x y -> (x,y)) in
  let rep = match distance (0,0) (x,y) with
    |0. -> 0
    |r when fisi r -> 1
    |_ -> 2
  in print_endline (string_of_int rep)
done ;
;;


Ivan had string s consisting of small English letters. However, his friend Julia decided to make fun of him and hid the string s. Ivan preferred making a new string to finding the old one. Ivan knows some information about the string s. Namely, he remembers, that string ti occurs in string s at least ki times or more, he also remembers exactly ki positions where the string ti occurs in string s: these positions are xi, 1, xi, 2, ..., xi, ki. He remembers n such strings ti.You are to reconstruct lexicographically minimal string s such that it fits all the information Ivan remembers. Strings ti and string s consist of small English letters only.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of strings Ivan remembers. The next n lines contain information about the strings. The i-th of these lines contains non-empty string ti, then positive integer ki, which equal to the number of times the string ti occurs in string s, and then ki distinct positive integers xi, 1, xi, 2, ..., xi, ki in increasing order — positions, in which occurrences of the string ti in the string s start. It is guaranteed that the sum of lengths of strings ti doesn't exceed 106, 1 ≤ xi, j ≤ 106, 1 ≤ ki ≤ 106, and the sum of all ki doesn't exceed 106. The strings ti can coincide. It is guaranteed that the input data is not self-contradictory, and thus at least one answer always exists.

Print lexicographically minimal string that fits all the information Ivan remembers.

open Printf
open Scanf

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

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 t = Array.make n "" in
  let tlen = Array.make n 0 in
  let x = Array.make n [||] in

  let last_index = ref 0 in

  for i=0 to n-1 do
    t.(i) <- read_string();
    tlen.(i) <- String.length t.(i);
    let k = read_int() in
    x.(i) <- Array.init k read_int;
    last_index := max !last_index (x.(i).(k-1) + tlen.(i) - 1)
  done;

  let m = !last_index + 2 in

  let st_list = Array.make m [] in

  for i=0 to n-1 do
    let k = Array.length x.(i) in
    for j=0 to k-1 do
      let st = x.(i).(j) in
      st_list.(st) <- (i,st)::(st_list.(st));
    done
  done;

  let rec loop pos set = if pos > !last_index then () else
      (* process the events at position pos (boundary) then
	 figure out what is in that box *)
      let set = List.rev_append st_list.(pos) set in
      let rec pop_loop set =
	match set with [] -> []
	  | (ind,st)::tail -> if tlen.(ind) + st > pos then set else pop_loop tail
      in
      let set = pop_loop set in
      let ch = if set = [] then 'a'
	else let (i,ind) = List.hd set in t.(i).[pos-ind]
      in
      printf "%c" ch;
      loop (pos+1) set
  in

  loop 1 [];

  print_newline()


There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct.Every contestant hopes that he can find a teammate so that their team’s strength is as high as possible. That is, a contestant will form a team with highest strength possible by choosing a teammate from ones who are willing to be a teammate with him/her. More formally, two people A and B may form a team if each of them is the best possible teammate (among the contestants that remain unpaired) for the other one. Can you determine who will be each person’s teammate?

There are 2n lines in the input.  The first line contains an integer n (1 ≤ n ≤ 400) — the number of teams to be formed. The i-th line (i > 1) contains i - 1 numbers ai1, ai2, ... , ai(i - 1). Here aij (1 ≤ aij ≤ 106, all aij are distinct) denotes the strength of a team consisting of person i and person j (people are numbered starting from 1.)

Output a line containing 2n numbers. The i-th number should represent the number of teammate of i-th person.

NoteIn the first sample, contestant 1 and 2 will be teammates and so do contestant 3 and 4, so the teammate of contestant 1, 2, 3, 4 will be 2, 1, 4, 3 respectively.

type heap =
	    | E
	    | N of (int * (int * int)) * heap * heap;;

let rec add x = function
	| E		-> N(x,E,E)
	| N(a,l,r)	-> if x > a
				then N(x,r, add a l)
				else N(a,r, add x l);;

let is_empty = function
	| E	-> true
	| _	-> false;;

let root (N(a,_,_)) = a;;

let rec supp = function
	| E		-> E
	| N(_,E,E)	-> E
	| N(_,E,r)	-> let x = root r in
				N(x,E,supp r)
	| N(_,l,E)	-> let x = root l in
				N(x,supp l,E)
	| N(_,l,r)	-> let [a;b] = List.map root [l;r] in
				if a > b
					then N(a,r, supp l)
					else N(b,supp r,l);;

let main () =
	let n = Scanf.scanf "%d" (fun i -> i) in
	let tas = ref E and tab = Array.make (2*n + 1) (-1) in
		for i=2 to 2*n do
			for j=1 to i-1 do
				Scanf.scanf " %d" (fun k -> tas := add (k,(i,j)) !tas);
			done;
		done;
	while not (is_empty !tas) do
		let (_,(b,c)) = root !tas in
			tas := supp !tas;
			if tab.(b) = -1 && tab.(c) = -1
				then begin
					tab.(b) <- c;
					tab.(c) <- b;
				     end;
	done;
	for i=1 to 2*n do
		Printf.printf "%d " (tab.(i));
	done;;

main ();;


Arkady's morning seemed to be straight of his nightmare. He overslept through the whole morning and, still half-asleep, got into the tram that arrived the first. Some time after, leaving the tram, he realized that he was not sure about the line number of the tram he was in.During his ride, Arkady woke up several times and each time he saw the tram stopping at some stop. For each stop he knows which lines of tram stop there. Given this information, can you help Arkady determine what are the possible lines of the tram he was in?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stops Arkady saw. The next $$$n$$$ lines describe the stops. Each of them starts with a single integer $$$r$$$ ($$$1 \le r \le 100$$$) — the number of tram lines that stop there. $$$r$$$ distinct integers follow, each one between $$$1$$$ and $$$100$$$, inclusive, — the line numbers. They can be in arbitrary order. It is guaranteed that Arkady's information is consistent, i.e. there is at least one tram line that Arkady could take.

Print all tram lines that Arkady could be in, in arbitrary order.

NoteConsider the first example. Arkady woke up three times. The first time he saw a stop with lines $$$1$$$, $$$4$$$, $$$6$$$. The second time he saw a stop with lines $$$1$$$, $$$4$$$. The third time he saw a stop with lines $$$10$$$, $$$5$$$, $$$6$$$, $$$4$$$ and $$$1$$$. He can be in a tram of one of two lines: $$$1$$$ or $$$4$$$.

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  let (+=) r v = r := !r + v
  let (-=) r v = r := !r - v
  let ( *= ) r v = r := !r * v
  let (/=) r v = r := !r / v
  let (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module I64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
  let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
  let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
  let fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

module IMap = Map.Make(Int64)
let () =
  let n = get_i64 0 in
  let mp = ref @@ IMap.empty in
  rep 1L n (fun _ ->
    let k = get_i64 0 in
    let a = input_i64_array k in
    iter (fun v ->
      mp := IMap.add v (1L + try IMap.find v !mp with _ -> 0L) !mp
    ) a
  );
  IMap.iter (fun v c ->
    (* printf "%2Ld: %2Ld\n" v c *)
    if c>=n then printf "%Ld " v
  ) !mp


There are $$$n$$$ people who want to participate in a boat competition. The weight of the $$$i$$$-th participant is $$$w_i$$$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are $$$k$$$ teams $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\dots$$$, $$$(a_k, b_k)$$$, where $$$a_i$$$ is the weight of the first participant of the $$$i$$$-th team and $$$b_i$$$ is the weight of the second participant of the $$$i$$$-th team, then the condition $$$a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$$$, where $$$s$$$ is the total weight of each team, should be satisfied.Your task is to choose such $$$s$$$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of participants. The second line of the test case contains $$$n$$$ integers $$$w_1, w_2, \dots, w_n$$$ ($$$1 \le w_i \le n$$$), where $$$w_i$$$ is the weight of the $$$i$$$-th participant.

For each test case, print one integer $$$k$$$: the maximum number of teams people can compose with the total weight $$$s$$$, if you choose $$$s$$$ optimally.

NoteIn the first test case of the example, we can reach the optimal answer for $$$s=6$$$. Then the first boat is used by participants $$$1$$$ and $$$5$$$ and the second boat is used by participants $$$2$$$ and $$$4$$$ (indices are the same as weights).In the second test case of the example, we can reach the optimal answer for $$$s=12$$$. Then first $$$6$$$ participants can form $$$3$$$ pairs.In the third test case of the example, we can reach the optimal answer for $$$s=3$$$. The answer is $$$4$$$ because we have $$$4$$$ participants with weight $$$1$$$ and $$$4$$$ participants with weight $$$2$$$.In the fourth test case of the example, we can reach the optimal answer for $$$s=4$$$ or $$$s=6$$$.In the fifth test case of the example, we can reach the optimal answer for $$$s=3$$$. Note that participant with weight $$$3$$$ can't use the boat because there is no suitable pair for him in the list.

open Printf
open Scanf

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

let get_answer x people =
    let n = Array.length people in
    let pair = Hashtbl.create n in
    let answer = Array.make 1 0 in

    let up id =
        let now = Array.make 1 0 in
        if Hashtbl.mem pair id then (
            let value = Hashtbl.find pair id in
            now.(0) <- value;
        );
        Hashtbl.add pair id (now.(0) + 1);
    in

    for i = 0 to n - 1 do
        let person = people.(i) in
        if Hashtbl.mem pair (x - person) then (
            let cnt = Hashtbl.find pair (x - person) in
            if cnt > 0 then (
                answer.(0) <- (answer.(0) + 1);
                Hashtbl.add pair (x - person) (cnt - 1);
            ) else (
                up person;
            )
        ) else (
            up person;
        )
    done;
    answer.(0)

let solve() =
    let n = read_int() in
    let arr = Array.init n read_int in
    let answer = Array.make 1 0 in
    for i = 2 to 100 do
        answer.(0) <- (max answer.(0) (get_answer i arr))
    done;
    printf "%d\n" answer.(0)

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

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

let get_answer x people =
    let n = Array.length people in
    let pair = Hashtbl.create n in
    let answer = Array.make 1 0 in

    let up id =
        let now = Array.make 1 0 in
        if Hashtbl.mem pair id then (
            let value = Hashtbl.find pair id in
            now.(0) <- value;
        );
        Hashtbl.add pair id (now.(0) + 1);
    in

    for i = 0 to n - 1 do
        let person = people.(i) in
        if Hashtbl.mem pair (x - person) then (
            let cnt = Hashtbl.find pair (x - person) in
            if cnt > 0 then (
                answer.(0) <- (answer.(0) + 1);
                Hashtbl.add pair (x - person) (cnt - 1);
            ) else (
                up person;
            )
        ) else (
            up person;
        )
    done;
    answer.(0)

let solve() =
    let n = read_int() in
    let arr = Array.init n read_int in
    let answer = Array.make 1 0 in
    for i = 2 to 15 do
        answer.(0) <- (max answer.(0) (get_answer i arr))
    done;
    printf "%d\n" answer.(0)

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done


As Gerald sets the table, Alexander sends the greeting cards, and Sergey and his twins create an army of clone snowmen, Gennady writes a New Year contest.The New Year contest begins at 18:00 (6.00 P.M.) on December 31 and ends at 6:00 (6.00 A.M.) on January 1. There are n problems for the contest. The penalty time for each solved problem is set as the distance from the moment of solution submission to the New Year in minutes. For example, the problem submitted at 21:00 (9.00 P.M.) gets penalty time 180, as well as the problem submitted at 3:00 (3.00 A.M.). The total penalty time is calculated as the sum of penalty time for all solved problems. It is allowed to submit a problem exactly at the end of the contest, at 6:00 (6.00 A.M.).Gennady opened the problems exactly at 18:00 (6.00 P.M.) and managed to estimate their complexity during the first 10 minutes of the contest. He believes that writing a solution for the i-th problem will take ai minutes. Gennady can submit a solution for evaluation at any time after he completes writing it. Probably he will have to distract from writing some solution to send the solutions of other problems for evaluation. The time needed to send the solutions can be neglected, i.e. this time can be considered to equal zero. Gennady can simultaneously submit multiple solutions. Besides, he can move at any time from writing one problem to another, and then return to the first problem from the very same place, where he has left it. Thus the total solution writing time of the i-th problem always equals ai minutes. Of course, Gennady does not commit wrong attempts, and his solutions are always correct and are accepted from the first attempt. He can begin to write the solutions starting from 18:10 (6.10 P.M.).Help Gennady choose from the strategies that help him solve the maximum possible number of problems, the one with which his total penalty time will be minimum.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of the problems. The next line contains n space-separated integers ai (1 ≤ ai ≤ 720) — each number shows how much time in minutes Gennady will spend writing a solution to the problem.

Print two integers — the number of problems Gennady will solve and the total penalty time considering that he chooses the optimal strategy.

NoteIn the sample, one of Gennady's possible optimal strategies is as follows. At 18:10 (6:10 PM) he begins to write the first problem and solves it in 30 minutes (18:40 or 6.40 P.M.). At 18:40 (6.40 P.M.) he begins to write the second problem. There are 320 minutes left before the New Year, so Gennady does not have the time to finish writing the second problem before the New Year. At 0:00 (12.00 A.M.) he distracts from the second problem, submits the first one, and returns immediately to writing the second problem. At 0:10 (0.10 A.M.), he completes the solution for the second problem, submits it and gets 10 minute penalty time. Note that as the total duration of the contest is 720 minutes and Gennady has already spent 10 minutes on reading the problems, he will not have time to solve the third problem during the contest. Yes, such problems happen to exist.Competitions by the given rules are held annually on the site http://b23.ru/3wvc

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a
  in
  let res = ref 0 in
  let penalty = ref 0 in
  let t = ref 0 in
  let t1 = 350
  and t2 = 710 in
    for i = 0 to n - 1 do
      t := !t + a.(i);
      if !t <= t1
      then incr res
      else if !t <= t2 then (
	incr res;
	penalty := !penalty + !t - t1;
      )
    done;
    Printf.printf "%d %d\n" !res !penalty


One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:  Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;  Delete the first number of the current sequence. The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105). The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.

Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.

NoteIn the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.

open Scanf
open Str

let (|>) x f = f x

let regexp_spc = regexp " "

let _ =
  let n :: k_ :: _ = () |> read_line |> (split regexp_spc) |> List.map int_of_string in
  let k = k_ - 1 in
  let a = () |> read_line |> (split regexp_spc) |> List.map int_of_string |> Array.of_list in
  let isok = ref true in
  let md = ref (-1) in
  for i = 0 to n-1 do
    if a.(i) <> a.(k) then md := i else ();
    if i > k & a.(i) <> a.(k) then isok := false else ();
  done;

  let ans = if !isok then !md + 1 else -1 in
  ans |> string_of_int |> print_endline

open Scanf
open Str

let (|>) x f = f x

let regexp_spc = regexp " "

let _ =
  let n :: k_ :: _ = () |> read_line |> (split regexp_spc) |> List.map int_of_string in
  let k = k_ - 1 in
  let a = () |> read_line |> (split regexp_spc) |> List.map int_of_string |> Array.of_list in
  let isok = ref true in
  let md = ref 0 in
  for i = 0 to n-1 do
    if a.(i) <> a.(k) then md := i else ();
    if i > k & a.(i) <> a.(k) then isok := false else ();
  done;

  let ans = if !isok then !md + 1 else -1 in
  ans |> string_of_int |> print_endline