Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.

The first line contains positive integer n (1 ≤ n ≤ 100) — the number of USB flash drives. The second line contains positive integer m (1 ≤ m ≤ 105) — the size of Sean's file. Each of the next n lines contains positive integer ai (1 ≤ ai ≤ 1000) — the sizes of USB flash drives in megabytes. It is guaranteed that the answer exists, i. e. the sum of all ai is not less than m.

Print the minimum number of USB flash drives to write Sean's file, if he can split the file between drives.

NoteIn the first example Sean needs only two USB flash drives — the first and the third.In the second example Sean needs all three USB flash drives.In the third example Sean needs only one USB flash drive and he can use any available USB flash drive — the first or the second.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a;
    let pos = ref (n - 1) in
    let s = ref 0 in
      while !pos >= 0 && !s + a.(!pos) < m do
	s := !s + a.(!pos);
	decr pos;
      done;
      Printf.printf "%d\n" (n - !pos)

open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))
let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)

let () =

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

  Array.sort (fun a b -> compare b a) a;

  let rec loop i ac = if ac >= m then i else loop (i+1) (ac + a.(i)) in

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


A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.You are given a string $$$s$$$ of length $$$n$$$, consisting of digits.In one operation you can delete any character from string $$$s$$$. For example, it is possible to obtain strings 112, 111 or 121 from string 1121.You need to determine whether there is such a sequence of operations (possibly empty), after which the string $$$s$$$ becomes a telephone number.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of string $$$s$$$. The second line of each test case contains the string $$$s$$$ ($$$|s| = n$$$) consisting of digits.

For each test print one line. If there is a sequence of operations, after which $$$s$$$ becomes a telephone number, print YES. Otherwise, print NO.

NoteIn the first test case you need to delete the first and the third digits. Then the string 7818005553535 becomes 88005553535.

open Scanf
open Printf

let gemacht n s =
	let rec loop i =
		if i = n then None
		else if s.[i] = '8' then Some i
		else loop (i + 1)
	in
	match loop 0 with
	| None -> false
	| Some i -> n - i >= 11

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let () =
	let t = read_int () in
	for i = 1 to t do
		let n = read_int () in
		let s = read_string () in
		if gemacht n s then printf "YES\n" else printf "NO\n";
	done

open Printf
open Scanf

let solve n s =
  let rec loop i = if i >= n then None
    else if s.[i] = '8' then Some i
    else loop (i+1)
  in
  match loop 0 with
    | None -> false
    | Some j -> n-1-j >= 10

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in
    let s = read_string() in
    if solve n s then printf "YES\n" else printf "NO\n"
  done


In some country live wizards. They love to ride trolleybuses.A city in this country has a trolleybus depot with n trolleybuses. Every day the trolleybuses leave the depot, one by one and go to the final station. The final station is at a distance of d meters from the depot. We know for the i-th trolleybus that it leaves at the moment of time ti seconds, can go at a speed of no greater than vi meters per second, and accelerate with an acceleration no greater than a meters per second squared. A trolleybus can decelerate as quickly as you want (magic!). It can change its acceleration as fast as you want, as well. Note that the maximum acceleration is the same for all trolleys.Despite the magic the trolleys are still powered by an electric circuit and cannot overtake each other (the wires are to blame, of course). If a trolleybus catches up with another one, they go together one right after the other until they arrive at the final station. Also, the drivers are driving so as to arrive at the final station as quickly as possible.You, as head of the trolleybuses' fans' club, are to determine for each trolley the minimum time by which it can reach the final station. At the time of arrival at the destination station the trolleybus does not necessarily have zero speed. When a trolley is leaving the depot, its speed is considered equal to zero. From the point of view of physics, the trolleybuses can be considered as material points, and also we should ignore the impact on the speed of a trolley bus by everything, except for the acceleration and deceleration provided by the engine.

The first input line contains three space-separated integers n, a, d (1 ≤ n ≤ 105, 1 ≤ a, d ≤ 106) — the number of trolleybuses, their maximum acceleration and the distance from the depot to the final station, correspondingly. Next n lines contain pairs of integers ti vi (0 ≤ t1 < t2... < tn - 1 < tn ≤ 106, 1 ≤ vi ≤ 106) — the time when the i-th trolleybus leaves the depot and its maximum speed, correspondingly. The numbers in the lines are separated by spaces.

For each trolleybus print a single line the time it arrives to the final station. Print the times for the trolleybuses in the order in which the trolleybuses are given in the input. The answer will be accepted if the absolute or relative error doesn't exceed 10 - 4.

NoteIn the first sample the second trolleybus will catch up with the first one, that will happen at distance 510.5 meters from the depot. The trolleybuses will go the remaining 9489.5 meters together at speed 10 meters per second. As a result, both trolleybuses will arrive to the final station by the moment of time 1000.5 seconds. The third trolleybus will not catch up with them. It will arrive to the final station by the moment of time 11000.05 seconds.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Scanf.bscanf sb "%d " (fun s -> s) in
  let d = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = float_of_int a
  and d = float_of_int d in
  let t = Array.make n 0.0 in
  let v = Array.make n 0.0 in
  let prev = ref (-1.0) in
    for i = 0 to n - 1 do
      t.(i) <- float_of_int (Scanf.bscanf sb "%d " (fun s -> s));
      v.(i) <- float_of_int (Scanf.bscanf sb "%d " (fun s -> s));
    done;
    for i = 0 to n - 1 do
      let t1 = v.(i) /. a in
      let d1 = t1 *. t1 *. a /. 2.0 in
      let t2 =
	if d1 < d then (
	  t1 +. (d -. d1) /. v.(i)
	) else (
	  sqrt (2.0 *. d /. a)
	)
      in
      let t3 = t2 +. t.(i) in
	if !prev <= 0.0 || !prev < t3 then (
	  prev := t3;
	  Printf.printf "%.9f\n" t3
	) else (
	  Printf.printf "%.9f\n" !prev
	)
    done


Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to the player with the larger number and returns the balls to the jar. The winner of the game is the one who wins at least two of the three rounds.Andrew wins rounds 1 and 2 while Jerry wins round 3, so Andrew wins the game. However, Jerry is unhappy with this system, claiming that he will often lose the match despite having the higher overall total. What is the probability that the sum of the three balls Jerry drew is strictly higher than the sum of the three balls Andrew drew?

The first line of input contains a single integer n (2 ≤ n ≤ 2000) — the number of balls in the jar. The second line contains n integers ai (1 ≤ ai ≤ 5000) — the number written on the ith ball. It is guaranteed that no two balls have the same number.

Print a single real value — the probability that Jerry has a higher total, given that Andrew wins the first two rounds and Jerry wins the third. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first case, there are only two balls. In the first two rounds, Andrew must have drawn the 2 and Jerry must have drawn the 1, and vice versa in the final round. Thus, Andrew's sum is 5 and Jerry's sum is 4, so Jerry never has a higher total.In the second case, each game could've had three outcomes — 10 - 2, 10 - 1, or 2 - 1. Jerry has a higher total if and only if Andrew won 2 - 1 in both of the first two rounds, and Jerry drew the 10 in the last round. This has probability .

open Printf
open Scanf

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

  let nn = n * (n-1) in

  let mdiff = 4999 in

  let prob = Array.make (mdiff+1) 0.0 in
  (* prob.(i) = probability of winning by by i *)

  let dp = 1.0 /. (float nn) in
  for i=0 to n-1 do
    for j=0 to n-1 do
      if i <> j then
	let diff = abs (a.(i) - a.(j)) in
	prob.(diff) <- prob.(diff) +. dp
    done
  done;

  let sum = Array.make (mdiff+2) 0.0 in
  (* sum.(i) = probability that the winner wins by i or more *)

  for i=mdiff downto 0 do
    sum.(i) <- sum.(i+1) +. prob.(i)
  done;

  let total = ref 0.0 in

  for s1 = 1 to mdiff do
    let p1 = prob.(s1) in
    for s2 = 1 to mdiff-s1 do
      let p2 = prob.(s2) in
      let p3 = sum.(s1+s2+1) in
      total := !total +. (p1*.p2*.p3)
    done
  done;

  printf "%.10f\n" !total


The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.You are given two strings $$$s$$$ and $$$t$$$ of the same length $$$n$$$. Their characters are numbered from $$$1$$$ to $$$n$$$ from left to right (i.e. from the beginning to the end).In a single move you can do the following sequence of actions:  choose any valid index $$$i$$$ ($$$1 \le i \le n$$$),  move the $$$i$$$-th character of $$$s$$$ from its position to the beginning of the string or move the $$$i$$$-th character of $$$s$$$ from its position to the end of the string. Note, that the moves don't change the length of the string $$$s$$$. You can apply a move only to the string $$$s$$$.For example, if $$$s=$$$"test" in one move you can obtain:  if $$$i=1$$$ and you move to the beginning, then the result is "test" (the string doesn't change),  if $$$i=2$$$ and you move to the beginning, then the result is "etst",  if $$$i=3$$$ and you move to the beginning, then the result is "stet",  if $$$i=4$$$ and you move to the beginning, then the result is "ttes",  if $$$i=1$$$ and you move to the end, then the result is "estt",  if $$$i=2$$$ and you move to the end, then the result is "tste",  if $$$i=3$$$ and you move to the end, then the result is "tets",  if $$$i=4$$$ and you move to the end, then the result is "test" (the string doesn't change). You want to make the string $$$s$$$ equal to the string $$$t$$$. What is the minimum number of moves you need? If it is impossible to transform $$$s$$$ to $$$t$$$, print -1.

The first line contains integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of independent test cases in the input. Each test case is given in three lines. The first line of a test case contains $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the strings $$$s$$$ and $$$t$$$. The second line contains $$$s$$$, the third line contains $$$t$$$. Both strings $$$s$$$ and $$$t$$$ have length $$$n$$$ and contain only lowercase Latin letters. There are no constraints on the sum of $$$n$$$ in the test (i.e. the input with $$$q=100$$$ and all $$$n=100$$$ is allowed).

For every test print minimum possible number of moves, which are needed to transform $$$s$$$ into $$$t$$$, or -1, if it is impossible to do.

3
9
iredppipe
piedpiper
4
estt
test
4
tste
test

4
1
a
z
5
adhas
dasha
5
aashd
dasha
5
aahsd
dasha

NoteIn the first example, the moves in one of the optimal answers are:  for the first test case $$$s=$$$"iredppipe", $$$t=$$$"piedpiper": "iredppipe" $$$\rightarrow$$$ "iedppiper" $$$\rightarrow$$$ "piedpiper";  for the second test case $$$s=$$$"estt", $$$t=$$$"test": "estt" $$$\rightarrow$$$ "test";  for the third test case $$$s=$$$"tste", $$$t=$$$"test": "tste" $$$\rightarrow$$$ "etst" $$$\rightarrow$$$ "test".

let to_arr s =
  let n = String.length s in
  Array.init n (String.get s)

let longest n s t z =
  let rec iter acc i j =
    if i>=n || j>=n then
      acc
    else if s.(i) = t.(j) then
      iter (acc + 1) (i + 1) (j + 1)
    else
      iter acc (i + 1) j in
  iter 0 0 z

let solve n s t =
  let s = to_arr s in
  let t = to_arr t in
  let s' = Array.copy s in
  let t' = Array.copy t in
  Array.fast_sort compare s';
  Array.fast_sort compare t';
  if s' <> t' then -1 else
    Array.init n (longest n s t)
    |> Array.fold_left max 0
    |> (fun x -> n - x)

let () =
  let t = read_int () in
  for i = 1 to t do
    let n = read_int () in
    let s = read_line () in
    let t = read_line () in
    Printf.printf "%d\n" (solve n s t)
  done


Phoenix has $$$n$$$ coins with weights $$$2^1, 2^2, \dots, 2^n$$$. He knows that $$$n$$$ is even.He wants to split the coins into two piles such that each pile has exactly $$$\frac{n}{2}$$$ coins and the difference of weights between the two piles is minimized. Formally, let $$$a$$$ denote the sum of weights in the first pile, and $$$b$$$ denote the sum of weights in the second pile. Help Phoenix minimize $$$|a-b|$$$, the absolute value of $$$a-b$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 30$$$; $$$n$$$ is even) — the number of coins that Phoenix has.

For each test case, output one integer — the minimum possible difference of weights between the two piles.

NoteIn the first test case, Phoenix has two coins with weights $$$2$$$ and $$$4$$$. No matter how he divides the coins, the difference will be $$$4-2=2$$$.In the second test case, Phoenix has four coins of weight $$$2$$$, $$$4$$$, $$$8$$$, and $$$16$$$. It is optimal for Phoenix to place coins with weights $$$2$$$ and $$$16$$$ in one pile, and coins with weights $$$4$$$ and $$$8$$$ in another pile. The difference is $$$(2+16)-(4+8)=6$$$.

(* Codeforces 1348 Phoenix and Balance train *)

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

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

let rec balance acc p2i i n =
	if i > n then acc
	else
		let np2i = p2i * 2 in
		let ni = i + 1 in
		let pos = (i < (n / 2)) || (i == n) in
		let sign = if pos then 1 else -1 in
		let nacc = acc + (sign * p2i) in
		balance nacc np2i ni n;;

let do_one () =
	let n = gr () in
	let b = balance 0 2 1 n in
	begin
		print_int b;
    print_string "\n";
	end;;

let rec do_all t = match t with
	| 0 -> ()
	| _ ->
		begin
			do_one ();
			do_all (t-1)
		end;;

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

main();;


Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.Let us say that his initial per chapter learning power of a subject is x hours. In other words he can learn a chapter of a particular subject in x hours.Well Devu is not complete dumb, there is a good thing about him too. If you teach him a subject, then time required to teach any chapter of the next subject will require exactly 1 hour less than previously required (see the examples to understand it more clearly). Note that his per chapter learning power can not be less than 1 hour.You can teach him the n subjects in any possible order. Find out minimum amount of time (in hours) Devu will take to understand all the subjects and you will be free to do some enjoying task rather than teaching a dumb guy.Please be careful that answer might not fit in 32 bit data type.

The first line will contain two space separated integers n, x (1 ≤ n, x ≤ 105). The next line will contain n space separated integers: c1, c2, ..., cn (1 ≤ ci ≤ 105).

Output a single integer representing the answer to the problem.

NoteLook at the first example. Consider the order of subjects: 1, 2. When you teach Devu the first subject, it will take him 3 hours per chapter, so it will take 12 hours to teach first subject. After teaching first subject, his per chapter learning time will be 2 hours. Now teaching him second subject will take 2 × 1 = 2 hours. Hence you will need to spend 12 + 2 = 14 hours.Consider the order of subjects: 2, 1. When you teach Devu the second subject, then it will take him 3 hours per chapter, so it will take 3 × 1 = 3 hours to teach the second subject. After teaching the second subject, his per chapter learning time will be 2 hours. Now teaching him the first subject will take 2 × 4 = 8 hours. Hence you will need to spend 11 hours.So overall, minimum of both the cases is 11 hours.Look at the third example. The order in this example doesn't matter. When you teach Devu the first subject, it will take him 3 hours per chapter. When you teach Devu the second subject, it will take him 2 hours per chapter. When you teach Devu the third subject, it will take him 1 hours per chapter. In total it takes 6 hours.

open Printf
open Scanf

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

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

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

  Array.sort compare c;

  let answer = sum 0 (n-1) (
    fun i ->
      let x' = max 1L (x -- (Int64.of_int i)) in
      c.(i) ** x'
  ) in

  printf "%Ld\n" answer

let solve n x c =
  let rec aux i x time =
    if (i = n) then time
    else
      let chapters = c.(i) in
        aux (i+1) (max (x-1) 1) Int64.(add time (mul chapters (of_int x)))
  in
    aux 0 x Int64.zero

let main =
  let (n, x) = Scanf.scanf "%d %d\n" (fun n x -> (n,x)) in
  let c = Array.init n (fun _ -> Scanf.scanf "%Ld " (fun x -> x)) in
  let () = Array.fast_sort compare c in
  let solution = solve n x c in
    Printf.printf "%Ld\n" solution

let solve n x c =
  let rec aux i x time =
    if (i = n) then time
    else
      let chapters = c.(i) in
        aux (i+1) (max (x-1) 1) (time + chapters*x)
  in
    aux 0 x 0

let main =
  let (n, x) = Scanf.scanf "%d %d\n" (fun n x -> (n,x)) in
  let c = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let () = Array.fast_sort compare c in
  let solution = solve n x c in
    Printf.printf "%d\n" solution


Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$.Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$.Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop.Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$.Your task is to get the number of games Maxim will buy.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_j \le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.

Print a single integer — the number of games Maxim will buy.

NoteThe first example is described in the problem statement.In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.

open Printf open Scanf
let input_int_array n =
	Array.init n (fun _ -> Scanf.scanf " %d" (fun v -> v))
let get_int () = Scanf.scanf " %d" (fun v -> v)
let get_2_ints () = Scanf.scanf " %d %d" (fun u v -> u,v)
let get_3_ints () = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w)
let get_4_ints () = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x)
let get_5_ints () = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)

let print_int_endline n = n |> string_of_int |> print_endline

let () =
	let n,m = get_2_ints ()
	in
	let ac = input_int_array n
	in let aa = input_int_array m
	in
	let jdx = ref 0
	in
	Array.fold_left (fun u v ->
		if !jdx < m && v <= aa.(!jdx) then (
			jdx := !jdx + 1; u+1
		) else u
	) 0 ac
	|> print_int_endline


Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:  it is up to a passenger to choose a plane to fly on;  if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 1000) — ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets. The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.

Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.

NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane.

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let m = Scanf.scanf " %d" (fun x -> x) in
  let a = Array.make m 0 in
  let b = Array.make m 0 in
  for i = 0 to m - 1 do
    let t = Scanf.scanf " %d" (fun x -> x) in
    a.(i) <- t;
    b.(i) <- t
  done;

  let x = ref 0 in
  let r = ref n in
  Array.sort (fun x y -> x - y) a;
  for i = 0 to m - 1 do
    let c = min a.(i) !r in
    x := !x + c * a.(i) - c * (c - 1) / 2;
    r := !r - c
  done;

  let y = ref 0 in
  let r = ref n in
  Array.sort (fun x y -> y - x) b;
  while !r > 0 do
    let c = b.(0) in
    for i = 0 to m - 1 do
      if !r > 0 && b.(i) = c then begin
        y := !y + c;
        r := !r - 1;
        b.(i) <- b.(i) - 1
      end
    done
  done;

  print_int !y;
  print_char ' ';
  print_int !x;
  print_char '\n'
;;

open Printf;;
open Scanf;;

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

let solve (n, m, arr) =
  let mx, mn = (ref 0, ref 0) in
  let a = ref arr in
  let b = ref (Array.copy arr) in
  for i = 0 to n - 1 do
    begin
      Array.fast_sort (fun x y -> x - y) !a;
      a := (Array.of_list (List.filter (fun x -> x > 0) (Array.to_list !a)));
      Array.fast_sort (fun x y -> x - y) !b;
      b := (Array.of_list (List.filter (fun x -> x > 0) (Array.to_list !b)));
      let len_a = Array.length !a in
      mx := (!mx + !a.(len_a - 1));
      mn := !mn + !b.(0);
      !a.(len_a - 1) <- !a.(len_a - 1) - 1;
      !b.(0) <- !b.(0) - 1
    end
  done;
  !mx, !mn

let main () =
  let inp = input () in
  let (mx, mn) = solve inp in
  printf "%d %d\n" mx mn

let () = main ()


Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.

The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.

Print one number — the answer to the problem modulo 109 + 7.

NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.

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

let _ =
  let m = 5000 in
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let mmod n =
    let r = Int64.rem n mmm in
      if r < 0L
      then r +| mmm
      else r
  in
  let inv = Array.make (m + 1) 1 in
  let _ =
    for i = 2 to m do
      inv.(i) <-
	Int64.to_int
	(Int64.rem
	   (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)
	   mmm);
    done
  in
  let fact = Array.make (m + 1) 1 in
  let ifact = Array.make (m + 1) 1 in
  let () =
    for i = 2 to m do
      fact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);
      ifact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);
    done;
  in
  let binom n k =
    Int64.to_int
      (Int64.rem
	 (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|
	      Int64.of_int ifact.(k)) mmm)
  in
  let (+/) x y =
    let s = x + y in
      if s < 0 || s >= mm
      then s - mm
      else s
  in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let a = Array.make_matrix 26 (n + 1) 0 in
  let sum = Array.make (n + 1) 0 in
  let _ =
    for i = 0 to n - 1 do
      let c = Char.code s.[i] - Char.code 'a' in
	for j = 1 to n do
	  let prev = a.(c).(j) in
	    a.(c).(j) <- if j = 1 then 1 else 0;
	    a.(c).(j) <- a.(c).(j) +/ sum.(j - 1) +/ (mm - a.(c).(j - 1));
	    (*for k = 0 to 25 do
	      if k <> c
	      then a.(c).(j) <- a.(c).(j) +/ a.(k).(j - 1);
	      done;*)
	    sum.(j) <- sum.(j) +/ a.(c).(j) +/ (mm - prev);
	done;
    done;
    (*for i = 0 to 25 do
      for j = 0 to n do
	Printf.printf " %d" a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
  in
  let res = ref 0L in
    for i = 1 to n do
      let s = ref 0 in
	for j = 0 to 25 do
	  s := !s +/ a.(j).(i)
	done;
	res := mmod (!res +|
			 Int64.of_int (binom (n - 1) (i - 1)) *|
			     Int64.of_int !s);
    done;
    Printf.printf "%Ld\n" !res


The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.

The first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.

In the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.

let read format f = Scanf.bscanf Scanf.Scanning.stdib format f

let bfs graph start f =
  let flags = Array.make (Array.length graph) false in
  let q = Queue.create () in
  let fold_vertex result v =
    List.fold_left (fun result (i, dir) ->
      if not flags.(i) then (Queue.add i q; flags.(i) <- true; f result v i dir)
      else result) result graph.(v)
  in
  let rec main_loop result = match Queue.is_empty q with
    | true -> result
    | false -> main_loop (fold_vertex result (Queue.take q))
  in
  Queue.add start q;
  flags.(start) <- true;
  main_loop

let () =
  let n = read "%d\n" (fun x -> x) in
  let graph = Array.make n [] in
  for i = 1 to n - 1 do
    let f, t = read "%d %d\n" (fun f t -> f - 1, t - 1) in
    graph.(f) <- (t, true) :: graph.(f);
    graph.(t) <- (f, false) :: graph.(t)
  done;
  let sum = bfs graph 0 (fun sum _ _ dir -> if dir then sum else sum + 1) 0 in
  let sums = Array.make n sum in
  let min_sum = bfs graph 0 (fun min_sum f t dir ->
    sums.(t) <- sums.(f) + (if dir then 1 else -1);
    min min_sum sums.(t)) sum
  in
  print_endline (string_of_int min_sum);
  let b = Buffer.create (10 * n) in
  Array.iteri (fun i s ->
    if s = min_sum then Buffer.add_string b (string_of_int (i + 1) ^ " ")) sums;
  print_endline (Buffer.sub b 0 (Buffer.length b - 1))

let read format f = Scanf.bscanf Scanf.Scanning.stdib format f

module L = struct
  let iter lst f = List.iter f lst
  let map lst f = List.map f lst
end

module A = struct
  let iteri f a = Array.iteri a f
end

let bfs graph n start f =
  let flags = Array.make n false in
  let q = Queue.create () in
  Queue.add start q;
  flags.(start) <- true;
  while not (Queue.is_empty q) do
    let v = Queue.take q in
    L.iter graph.(v) (fun (i, dir) ->
      if not flags.(i) then
        (Queue.add i q;
         f v i dir;
         flags.(i) <- true))
  done

let () =
  let n = read "%d\n" (fun x -> x) in
  let graph = Array.make n [] in
  for i = 1 to n - 1 do
    let f, t = read "%d %d\n" (fun f t -> f - 1, t - 1) in
    graph.(f) <- (t, true) :: graph.(f);
    graph.(t) <- (f, false) :: graph.(t)
  done;
  let sum = ref 0 in
  bfs graph n 0 (fun _ _ dir -> if not dir then incr sum);
  let sums = Array.make n !sum in
  let min_sum = ref !sum in
  bfs graph n 0 (fun f t dir ->
    sums.(t) <- sums.(f) + (if dir then 1 else -1);
    min_sum := min !min_sum sums.(t));
  print_endline (string_of_int !min_sum);
  let b = Buffer.create (10 * n) in
  A.iteri sums (fun i s ->
    if s = !min_sum then Buffer.add_string b (string_of_int (i + 1) ^ " "));
  print_endline (Buffer.sub b 0 (Buffer.length b - 1))

let read format f = Scanf.bscanf Scanf.Scanning.stdib format f

let (=::) list_ref a = list_ref := a :: !list_ref

module L = struct
  let iter lst f = List.iter f lst
  let map lst f = List.map f lst
  let sort = List.sort
end

let bfs graph n start f =
  let flags = Array.make n false in
  let q = Queue.create () in
  Queue.add start q;
  while not (Queue.is_empty q) do
    let v = Queue.take q in
    L.iter !(graph.(v)) (fun (i, dir) ->
      if not flags.(i) then
        (Queue.add i q;
         f v i dir;
         flags.(i) <- true))
  done

let () =
  let n = read "%d\n" (fun x -> x) in
  let graph = Array.make n (ref []) in
  for i = 1 to n - 1 do
    let f, t = read "%d %d\n" (fun f t -> f - 1, t - 1) in
    graph.(f) =:: (t, true);
    graph.(t) =:: (f, false)
  done;
  let sum = ref 0 in
  bfs graph n 0 (fun f t dir -> if not dir then incr sum);
  let sums = Array.make n !sum in
  let min = ref !sum in
  let minis = ref [] in
  bfs graph n 0 (fun f t dir ->
    sums.(t) <- sums.(f) + (if dir then 1 else -1);
    if sums.(t) < !min then (min := sums.(t); minis := [t])
    else if sums.(t) = !min then minis =:: t);
  print_endline (string_of_int !min);
  print_endline (String.concat " "
                   (L.map (L.sort compare !minis)
                      (fun i -> (string_of_int (i + 1)))))

let read format f = Scanf.bscanf Scanf.Scanning.stdib format f

let (=::) list_ref a = list_ref := a :: !list_ref

module L = struct
  let iter lst f = List.iter f lst
  let map lst f = List.map f lst
  let sort = List.sort
end

let bfs graph n start f =
  let flags = Array.make n false in
  let q = Queue.create () in
  Queue.add start q;
  while not (Queue.is_empty q) do
    let v = Queue.take q in
    L.iter !(graph.(v)) (fun (i, dir) ->
      if not flags.(i) then
        (Queue.add i q;
         f v i dir;
         flags.(i) <- true))
  done

let () =
  let n = read "%d\n" (fun x -> x) in
  let graph = Array.init n (fun _ -> ref []) in
  for i = 1 to n - 1 do
    let f, t = read "%d %d\n" (fun f t -> f - 1, t - 1) in
    graph.(f) =:: (t, true);
    graph.(t) =:: (f, false)
  done;
  let sum = ref 0 in
  bfs graph n 0 (fun f t dir -> if not dir then incr sum);
  let sums = Array.make n !sum in
  let min = ref !sum in
  let minis = ref [] in
  bfs graph n 0 (fun f t dir ->
    sums.(t) <- sums.(f) + (if dir then 1 else -1);
    if sums.(t) < !min then (min := sums.(t); minis := [t])
    else if sums.(t) = !min then minis =:: t);
  print_endline (string_of_int !min);
  print_endline (String.concat " "
                   (L.map (L.sort compare !minis)
                      (fun i -> (string_of_int (i + 1)))))

let read format f = Scanf.bscanf Scanf.Scanning.stdib format f

let (=::) list_ref a = list_ref := a :: !list_ref

let list_iter lst f = List.iter f lst

let list_map lst f = List.map f lst

let bfs graph n start f =
  let flags = Array.make n false in
  let q = Queue.create () in
  Queue.add start q;
  while not (Queue.is_empty q) do
    let v = Queue.take q in
    list_iter !(graph.(v)) (fun (i, dir) ->
      if not flags.(i) then
        (Queue.add i q;
         f v i dir;
         flags.(i) <- true))
  done

let () =
  let n = read "%d\n" (fun x -> x) in
  let graph = Array.make n (ref []) in
  for i = 1 to n - 1 do
    let f, t = read "%d %d\n" (fun f t -> f - 1, t - 1) in
    graph.(f) =:: (t, true);
    graph.(t) =:: (f, false)
  done;
  let sum = ref 0 in
  bfs graph n 0 (fun f t dir -> if not dir then incr sum);
  let sums = Array.make n 0 in
  sums.(0) <- !sum;
  let min = ref !sum in
  let minis = ref [] in
  bfs graph n 0 (fun f t dir ->
    sums.(t) <- (if dir then (+) else (-)) sums.(f) 1;
    if sums.(t) < !min then
      (minis := [t];
       min := sums.(t))
    else if sums.(t) = !min then
      minis =:: t);
  print_endline (string_of_int !min);
  print_endline (String.concat " "
                   (list_map !minis (fun i -> (string_of_int (i + 1)))))


A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and "(()" are not.We can see that each opening bracket in RBS is paired with some closing bracket, and, using this fact, we can define nesting depth of the RBS as maximum number of bracket pairs, such that the $$$2$$$-nd pair lies inside the $$$1$$$-st one, the $$$3$$$-rd one — inside the $$$2$$$-nd one and so on. For example, nesting depth of "" is $$$0$$$, "()()()" is $$$1$$$ and "()((())())" is $$$3$$$.Now, you are given RBS $$$s$$$ of even length $$$n$$$. You should color each bracket of $$$s$$$ into one of two colors: red or blue. Bracket sequence $$$r$$$, consisting only of red brackets, should be RBS, and bracket sequence, consisting only of blue brackets $$$b$$$, should be RBS. Any of them can be empty. You are not allowed to reorder characters in $$$s$$$, $$$r$$$ or $$$b$$$. No brackets can be left uncolored.Among all possible variants you should choose one that minimizes maximum of $$$r$$$'s and $$$b$$$'s nesting depth. If there are multiple solutions you can print any of them.

The first line contains an even integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of RBS $$$s$$$. The second line contains regular bracket sequence $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{$$$"(", ")"$$$\}$$$).

Print single string $$$t$$$ of length $$$n$$$ consisting of "0"-s and "1"-s. If $$$t_i$$$ is equal to 0 then character $$$s_i$$$ belongs to RBS $$$r$$$, otherwise $$$s_i$$$ belongs to $$$b$$$.

NoteIn the first example one of optimal solutions is $$$s = $$$ "$$$\color{blue}{()}$$$". $$$r$$$ is empty and $$$b = $$$ "$$$()$$$". The answer is $$$\max(0, 1) = 1$$$.In the second example it's optimal to make $$$s = $$$ "$$$\color{red}{(}\color{blue}{(}\color{red}{)}\color{blue}{)}$$$". $$$r = b = $$$ "$$$()$$$" and the answer is $$$1$$$.In the third example we can make $$$s = $$$ "$$$\color{red}{(}\color{blue}{((}\color{red}{)()}\color{blue}{)())}$$$". $$$r = $$$ "$$$()()$$$" and $$$b = $$$ "$$$(()())$$$" and the answer is $$$2$$$.

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let s = read_string() in

  let color = Array.make n 0 in

  let rec parse i depth = if i<n then (
    match s.[i] with
      | '(' ->
	color.(i) <- depth mod 2;
	parse (i+1) (depth+1)
      | ')' ->
	color.(i) <- (depth+1) mod 2;
	parse (i+1) (depth -1)
      | _ -> failwith "bad input"
  ) in

  parse 0 0;

  for i=0 to n-1 do
    printf "%d" color.(i)
  done;

  print_newline()


Wilbur is playing with a set of n points on the coordinate plane. All points have non-negative integer coordinates. Moreover, if some point (x, y) belongs to the set, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y also belong to this set.Now Wilbur wants to number the points in the set he has, that is assign them distinct integer numbers from 1 to n. In order to make the numbering aesthetically pleasing, Wilbur imposes the condition that if some point (x, y) gets number i, then all (x',y') from the set, such that x' ≥ x and y' ≥ y must be assigned a number not less than i. For example, for a set of four points (0, 0), (0, 1), (1, 0) and (1, 1), there are two aesthetically pleasing numberings. One is 1, 2, 3, 4 and another one is 1, 3, 2, 4.Wilbur's friend comes along and challenges Wilbur. For any point he defines it's special value as s(x, y) = y - x. Now he gives Wilbur some w1, w2,..., wn, and asks him to find an aesthetically pleasing numbering of the points in the set, such that the point that gets number i has it's special value equal to wi, that is s(xi, yi) = yi - xi = wi.Now Wilbur asks you to help him with this challenge.

The first line of the input consists of a single integer n (1 ≤ n ≤ 100 000) — the number of points in the set Wilbur is playing with. Next follow n lines with points descriptions. Each line contains two integers x and y (0 ≤ x, y ≤ 100 000), that give one point in Wilbur's set. It's guaranteed that all points are distinct. Also, it is guaranteed that if some point (x, y) is present in the input, then all points (x', y'), such that 0 ≤ x' ≤ x and 0 ≤ y' ≤ y, are also present in the input. The last line of the input contains n integers. The i-th of them is wi ( - 100 000 ≤ wi ≤ 100 000) — the required special value of the point that gets number i in any aesthetically pleasing numbering.

If there exists an aesthetically pleasant numbering of points in the set, such that s(xi, yi) = yi - xi = wi, then print "YES" on the first line of the output. Otherwise, print "NO". If a solution exists, proceed output with n lines. On the i-th of these lines print the point of the set that gets number i. If there are multiple solutions, print any of them.

NoteIn the first sample, point (2, 0) gets number 3, point (0, 0) gets number one, point (1, 0) gets number 2, point (1, 1) gets number 5 and point (0, 1) gets number 4. One can easily check that this numbering is aesthetically pleasing and yi - xi = wi.In the second sample, the special values of the points in the set are 0,  - 1, and  - 2 while the sequence that the friend gives to Wilbur is 0, 1, 2. Therefore, the answer does not exist.

exception YOLO

let main () =
	let assigned = Hashtbl.create 0 in
	let n = Scanf.scanf "%d" (fun i->i) and tab = Array.make 200002 []
	and res = ref [] in
	for i=1 to n do
		Scanf.scanf " %d %d"
	(fun i j -> tab.(100000 + j - i) <- (i,j)::tab.(100000 + j - i)) ;
	done;
	for i=0 to 200001 do
		tab.(i) <- List.sort compare tab.(i);
	done;
	for i=1 to n do
		Scanf.scanf " %d" (fun i -> let (t::q) = tab.(i + 100000) in
		tab.(i + 100000) <- q; res := t:: !res; Hashtbl.add assigned t ();
		let (c,d) = t in if Hashtbl.mem assigned (c+1,d) || Hashtbl.mem assigned (c,d+1) then raise YOLO);
	done;
	Printf.printf "YES";
	List.iter (fun (i,j) -> Printf.printf "\n%d %d" i j) (List.rev !res);;

try
main ()
with _ -> Printf.printf "NO";;

let main () =
	let n = Scanf.scanf "%d" (fun i->i) and tab = Array.make 200002 []
	and res = ref [] in
	for i=1 to n do
		Scanf.scanf " %d %d"
	(fun i j -> tab.(100000 + j - i) <- (i,j)::tab.(100000 + j - i)) ;
	done;
	for i=0 to 200001 do
		tab.(i) <- List.sort compare tab.(i);
	done;
	for i=1 to n do
		Scanf.scanf " %d" (fun i -> let a = tab.(i + 100000) in
		tab.(i + 100000) <- List.tl a; res := (List.hd a):: !res);
	done;
	Printf.printf "YES";
	List.iter (fun (i,j) -> Printf.printf "\n%d %d" i j) (List.rev !res);;

try
main ()
with _ -> Printf.printf "NO";;

let main () =
	let n = Scanf.scanf "%d" (fun i->i) and tab = Array.make 200000 []
	and res = ref [] in
	for i=1 to n do
		Scanf.scanf " %d %d"
	(fun i j -> tab.(100000 + j - i) <- (i,j)::tab.(100000 + j - i)) ;
	done;
	for i=1 to n do
		Scanf.scanf " %d" (fun i -> let a = tab.(i + 100000) in
		tab.(i + 100000) <- List.tl a; res := (List.hd a):: !res);
	done;
	Printf.printf "YES";
	List.iter (fun (i,j) -> Printf.printf "\n%d %d" i j) (List.rev !res);;

try
main ()
with _ -> Printf.printf "NO";;


The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:  The players move in turns; In one move the player can remove an arbitrary letter from string s.  If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.

The input contains a single line, containing string s (1 ≤ |s|  ≤  103). String s consists of lowercase English letters.

In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.

(* CF odd game prob 276 B *)
open Filename;;

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

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

let ss = rdln();;

let rec isOdd s i c cnt =
	if i >= String.length s then ((cnt mod 2) = 1)
	else
		let cnt1 = cnt + (if c = s.[i] then 1 else 0) in
		isOdd s (i+1) c cnt1;;

let rec nOdd s c cnto =
	if c > 'z' then cnto
	else
		let iso = isOdd s 0 c 0 in
		let cnto1 = cnto + (if iso then 1 else 0) in
		let nextc = char_of_int (int_of_char c + 1) in
		nOdd s nextc cnto1;;

let main() =
	let no = nOdd ss 'a' 0 in
	let so = if no < 2 || (no mod 2) = 1 then "First" else "Second" in
	( print_string so; print_newline() );;

main();;

let () =
  let s = read_line() in
  let n = String.length s in
  let h = Array.make 26 0 in

    for i=0 to n-1 do
      let c = (int_of_char s.[i]) - (int_of_char 'a') in
	h.(c) <- h.(c) +1
    done;

    let odd = ref 0 in

      for i=0 to 25 do
	if h.(i) mod 2 = 1 then odd := !odd + 1
      done;

      if (!odd >= 1 && !odd mod 2 = 0) then Printf.printf "Second\n" else Printf.printf "First\n"


As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup.  Then at one turn Barney swaps the cup in the middle with any of other two cups randomly (he choses each with equal probability), so the chosen cup becomes the middle one. Game lasts n turns and Barney independently choses a cup to swap with the middle one within each turn, and the key always remains in the cup it was at the start.After n-th turn Barney asks a girl to guess which cup contains the key. The girl points to the middle one but Barney was distracted while making turns and doesn't know if the key is under the middle cup. That's why he asked you to tell him the probability that girl guessed right.Number n of game turns can be extremely large, that's why Barney did not give it to you. Instead he gave you an array a1, a2, ..., ak such that   in other words, n is multiplication of all elements of the given array.Because of precision difficulties, Barney asked you to tell him the answer as an irreducible fraction. In other words you need to find it as a fraction p / q such that , where  is the greatest common divisor. Since p and q can be extremely large, you only need to find the remainders of dividing each of them by 109 + 7.Please note that we want  of p and q to be 1, not  of their remainders after dividing by 109 + 7.

The first line of input contains a single integer k (1 ≤ k ≤ 105) — the number of elements in array Barney gave you. The second line contains k integers a1, a2, ..., ak (1 ≤ ai ≤ 1018) — the elements of the array.

In the only line of output print a single string x / y where x is the remainder of dividing p by 109 + 7 and y is the remainder of dividing q by 109 + 7.

let p = 1_000_000_007L

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

let ( *** ) (a,b,c,d) (e,f,g,h) =
  ((a**e ++ b**g)%%p, (a**f ++ b**h)%%p, (c**e ++ d**g)%%p, (c**f ++ d**h)%%p)

let identity = (1L, 0L, 0L, 1L)

let rec ( ^ ) m e =
  if e=0L then identity else
    let a = m ^ (Int64.shift_right e 1) in
    if (Int64.logand e 1L)=0L then a *** a else m *** (a *** a)

open Printf
open Scanf

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

let () =

  let k = read_int() in
  let a = Array.init k (fun _ -> (read_long()) %% (p -- 1L)) in

  let rec prod i ac = if i=k then ac else
      prod (i+1) ((a.(i) ** ac) %% (p -- 1L))
  in

  let pr = prod 0 1L in

  let (a,b,c,d) = (0L, 1L, 2L, 1L) ^ pr in
  let (two_to_power, _,_,_) = (2L, 0L, 0L, 2L) ^ pr in
  let (two_inverse, _,_,_) = (2L, 0L, 0L, 2L) ^ (p -- 2L) in
  (* this should work cause the a_i's cannot be 0 *)

  printf "%Ld/%Ld\n" ((a ** two_inverse)%%p) ((two_to_power ** two_inverse)%%p)


Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.

In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.

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

let ident x = x ;;
let ident2 x y = (x, y) ;;
let ident3 x y z = (x, y, z) ;;
let ident4 x y z w = (x, y, z, w) ;;
let ident5 x y z w v = (x, y, z, w, v) ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

let () =
  let n = Scanf.scanf "%d " ident in
  let an = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d " ident :: acc) in
  let bn = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d " ident :: acc) in
  let cn = fold_for 0 n ~init:[] ~f:(fun acc _ ->
    Scanf.scanf "%d " ident :: acc) in
  let rec combine an bn cn = match an, bn, cn with
  | (a :: an, b :: bn, c :: cn) -> (a, b, c) :: combine an bn cn
  | ([], [], []) -> []
  | _ -> failwith "combine" in
  let xs = combine an bn cn in
  let map = Hashtbl.create 1000 in
  let rec iter prev i xs =
    try
      Hashtbl.find map (prev, i)
    with
    | Not_found -> begin
      match xs with
      | (a, b, c) :: ((_ :: _) as xs) -> begin
        let res =
          match prev with
          | `p -> max (b + iter `p (i + 1) xs) (c + iter `f (i + 1) xs)
          | `f -> max (a + iter `p (i + 1) xs) (b + iter `f (i + 1) xs) in
        Hashtbl.add map (prev, i) res;
        res
      end
      | [a, b, c] -> begin
        let res =
          match prev with
          | `p -> (b + iter `p (i + 1) [])
          | `f -> (a + iter `p (i + 1) []) in
        Hashtbl.add map (prev, i) res;
        res
      end
      | [] -> 0
    end
  in
  Printf.printf "%d\n" @@ iter `f 0 xs
;;

let line_stream_from_channel in_chan =
  Stream.from
  (fun _ ->
    try Some (input_line in_chan)
    with _ -> None);;

let rec print_l l = match l with
| hd::tl -> (print_int hd; print_string " ";print_l tl)
| _ -> print_newline ();;

let to_List strm len=
  let lt = List.map int_of_string (Str.split (Str.regexp " ") (Stream.next strm)) in
  if List.length lt != len then failwith "WrangData" else lt;;

let oComp x y = match x,y with
| Some i, Some j -> Some(max i j)
| None, i -> i
| i, None -> i;;

let oAdd o x = match o with
|Some y -> Some (x+y)
|None -> None;;

let total l =
  List.fold_left (+) 0 l;;
let path_cached l1 l2 =
  let path_ht = Hashtbl.create ((List.length l1)*4 ) in
  let length = List.length l1 in
  let hnum l s ol = (
                (List.length l) +1
                + (if ol!=[] then length else 0))*s in
  let rec path l1 l2 switch ol =
    let out =
      try Hashtbl.find path_ht (hnum l1 switch ol)

      with Not_found ->
     (let res = (match l1, l2, ol with
    | h1::t1, h2::t2, [] -> (
      let vnew, valt = ((*if switch=1 then*) h1,h2 (*else h2,h1*)) in
      oComp ((*if (vlast + vnew <=0)&&(tl!=[])   then None
                                else*) oAdd (path t1 t2 (-1*switch) (vnew::[])) vnew)
      ((*if (vlast<valt)&&(tl!=[]) then None
                                else*) (path t1 t2 (switch) ol))
                              )

    | h1::t1, h2::t2, vlast::tl-> (
      let vnew, valt = (if switch=1 then h1,h2 else h2,h1) in
      oComp ((*if (vlast + vnew <=0)  then None
                                    else*) (oAdd (path t1 t2 (-1*switch) (vnew::ol)) vnew))
            ((*if (vlast<valt)        then None
                                    else*) (path t1 t2 (switch) ol))
                                   )
    |_ -> if (switch= -1) then Some 0
                          else None) in
    Hashtbl.add path_ht (hnum l1 switch ol) res;
(*
    print_string "Added ";
    print_int (hnum l1 switch ol);
    print_string " with res = ";
    (match shifted_res with
    |Some num -> print_int num;
    |None -> print_string "None";);
    print_string "\n\t";
    print_l ol;
    (*print_newline ();*)
*)
    res) in
    out in
  path l1 l2 1 [] ;;

let main =
  let stream = line_stream_from_channel stdin in
  try
    let n = int_of_string (Stream.next stream) in
    let a = to_List stream n in
    let b = to_List stream n in
    let c = to_List stream n in
    let rev_ab = List.rev_map2 (fun x y -> x-y) a b in
    let rev_cb = List.rev_map2 (fun x y -> x-y) c b in
(*
    print_l rev_ab;
    print_l rev_cb;
*)
    let oRes = path_cached rev_ab rev_cb in
    match oRes with
    | Some i -> print_int (i+ (total b)); print_newline ();
    | None -> print_string "No result";
  with _ -> raise Exit
;;

let () =
  try main
  with Exit -> print_string "Bye-Bye\n";;

let line_stream_from_channel in_chan =
  Stream.from
  (fun _ ->
    try Some (input_line in_chan)
    with _ -> None);;

let to_List strm len=
  let lt = List.map int_of_string (Str.split (Str.regexp " ") (Stream.next strm)) in
  if List.length lt != len then failwith "WrangData" else lt;;

let oComp x y = match x,y with
| Some i, Some j -> Some(max i j)
| None, i -> i
| i, None -> i;;

let oAdd o x = match o with
|Some y -> Some (x+y)
|None -> None;;

let total l =
  List.fold_left (+) 0 l;;
let path_cached l1 l2 =
  let path_ht = Hashtbl.create ((List.length l1)*2 + 2 ) in
  let rec path l1 l2 switch ol =
    let out =
      try Hashtbl.find path_ht (((List.length l1) +1)*switch)

      with Not_found ->
     (let res = (match l1, l2, ol with
    | h1::t1, h2::t2, [] -> (
      let vnew, valt = ((*if switch=1 then*) h1,h2 (*else h2,h1*)) in
      oComp ((*if (vlast + vnew <=0)&&(tl!=[])   then None
                                else*) (path t1 t2 (-1*switch) (vnew::[])))
      ((*if (vlast<valt)&&(tl!=[]) then None
                                else*) (path t1 t2 (switch) ol))
                              )

    | h1::t1, h2::t2, vlast::tl-> (
      let vnew, valt = (if switch=1 then h1,h2 else h2,h1) in
      oComp (if (vlast + vnew <=0)  then None
                                    else (path t1 t2 (-1*switch) (vnew::ol)))
            (if (vlast<valt)        then None
                                    else (path t1 t2 (switch) ol))
                                   )
    |_ -> if (switch= -1) then Some (total ol)
                          else None) in
     let shifted_res = (oAdd res (-(total ol))) in
    Hashtbl.add path_ht (((List.length l1) +1)*switch) shifted_res;
    (*print_string "Added ";
    print_int ((List.length l1)*switch);
    print_string " with res = ";
    (match shifted_res with
    |Some num -> print_int num;
    |None -> print_string "None";);
    print_newline ();*)
    shifted_res) in
    oAdd out (total ol) in
  path l1 l2 1 [] ;;

let main =
  let stream = line_stream_from_channel stdin in
  try
    let n = int_of_string (Stream.next stream) in
    let a = to_List stream n in
    let b = to_List stream n in
    let c = to_List stream n in
    let rev_ab = List.rev_map2 (fun x y -> x-y) a b in
    let rev_cb = List.rev_map2 (fun x y -> x-y) c b in
    let oRes = path_cached rev_ab rev_cb in
    match oRes with
    | Some i -> print_int (i+ (total b)); print_newline ();
    | None -> print_string "No result";
  with _ -> raise Exit
;;

let () =
  try main
  with Exit -> print_string "Bye-Bye\n";;


Igor K. very much likes a multiplayer role playing game WineAge II. Who knows, perhaps, that might be the reason for his poor performance at the university. As any person who plays the game, he is interested in equipping his hero with as good weapon and outfit as possible. One day, as he was reading the game's forum yet again, he discovered a very interesting fact. As it turns out, each weapon in the game is characterised with k different numbers: a1, ..., ak. They are called hit indicators and according to the game developers' plan they are pairwise coprime. The damage that is inflicted during a hit depends not only on the weapon's characteristics, but also on the hero's strength parameter. Thus, if the hero's strength equals n, than the inflicted damage will be calculated as the number of numbers on the segment , that aren't divisible by any hit indicator ai.Recently, having fulfilled another quest, Igor K. found a new Lostborn sword. He wants to know how much damage he will inflict upon his enemies if he uses it.

The first line contains two integers: n and k (1 ≤ n ≤ 1013, 1 ≤ k ≤ 100). They are the indicator of Igor K's hero's strength and the number of hit indicators. The next line contains space-separated k integers ai (1 ≤ ai ≤ 1000). They are Lostborn sword's hit indicators. The given k numbers are pairwise coprime.

Print the single number — the damage that will be inflicted by Igor K.'s hero when he uses his new weapon.  Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make k 0 in
  let _ =
    for i = 0 to k - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    (*Array.sort (fun x y -> compare y x) a;*)
    Array.sort compare a;
  in
  let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in
  let sn = isqrt n in
  let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in
  let n2 = min 250000L n in
  let n2 = Int64.to_int n2 in
  let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in
  let _ =
    for i = 1 to n2 do
      phi'.(i).(0) <- i;
      for j = 1 to k do
	phi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)
      done;
    done;
  in
  let n3 = n /| Int64.of_int n2 in
  let (c, q) =
    let c = ref 0 in
    let q = ref 1 in
      while !c < k && !q * a.(!c) <= n2 do
	q := !q * a.(!c);
	incr c;
      done;
      (!c, !q)
  in
  let cnt = ref 0 in
  let cnt1 = ref 0 in
  let cnt2 = ref 0 in
  let cnt3 = ref 0 in
  let cnt4 = ref 0 in
  (*let rec phi m k =
    (*incr cnt;*)
    if k = 0
    then (
      (*incr cnt1;*)
      n /| m
    ) else if k = c then (
      (*incr cnt4;*)
      (n /| m /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)
    ) else if m > n3
    then (
      (*incr cnt2;*)
      Int64.of_int phi'.(Int64.to_int (n /| m)).(k)
    ) else (
      (*incr cnt3;*)
      phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)
    )
  in
  let res = phi 1L k in*)
  let rec phi32 n k =
    (*incr cnt;*)
    if k = 0
    then n
    else if k = c
    then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)
    else if n <= n2
    then phi'.(n).(k)
    else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)
  in
  let rec phi n k =
    if k = 0
    then n
    else if k = c
    then
      (n /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)
    else if n <= 1000000000L
    then Int64.of_int (phi32 (Int64.to_int n) k)
    else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)
  in
  let res = phi n k in
    Printf.eprintf "asd %d %d %d %d %d %d\n" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;
    Printf.printf "%Ld\n" res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make k 0 in
  let _ =
    for i = 0 to k - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    (*Array.sort (fun x y -> compare y x) a;*)
    Array.sort compare a;
  in
  let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in
  let sn = isqrt n in
  let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in
  let n2 = min 150000L n in
  let n2 = Int64.to_int n2 in
  let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in
  let _ =
    for i = 1 to n2 do
      phi'.(i).(0) <- i;
      for j = 1 to k do
	phi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)
      done;
    done;
  in
  let n3 = n /| Int64.of_int n2 in
  let (c, q) =
    let c = ref 0 in
    let q = ref 1 in
      while !c < k && !q * a.(!c) <= n2 do
	q := !q * a.(!c);
	incr c;
      done;
      (!c, !q)
  in
  let cnt = ref 0 in
  let cnt1 = ref 0 in
  let cnt2 = ref 0 in
  let cnt3 = ref 0 in
  let cnt4 = ref 0 in
  (*let rec phi m k =
    (*incr cnt;*)
    if k = 0
    then (
      (*incr cnt1;*)
      n /| m
    ) else if k = c then (
      (*incr cnt4;*)
      (n /| m /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)
    ) else if m > n3
    then (
      (*incr cnt2;*)
      Int64.of_int phi'.(Int64.to_int (n /| m)).(k)
    ) else (
      (*incr cnt3;*)
      phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)
    )
  in
  let res = phi 1L k in*)
  let rec phi32 n k =
    (*incr cnt;*)
    if k = 0
    then n
    else if k = c
    then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)
    else if n <= n2
    then phi'.(n).(k)
    else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)
  in
  let rec phi n k =
    if k = 0
    then n
    else if k = c
    then
      (n /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)
    else if n <= 1000000000L
    then Int64.of_int (phi32 (Int64.to_int n) k)
    else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)
  in
  let res = phi n k in
    Printf.eprintf "asd %d %d %d %d %d %d\n" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;
    Printf.printf "%Ld\n" res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make k 0 in
  let _ =
    for i = 0 to k - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    (*Array.sort (fun x y -> compare y x) a;*)
    Array.sort compare a;
  in
  let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in
  let sn = isqrt n in
  let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in
  let n2 = min 250000L n in
  let n2 = Int64.to_int n2 in
  let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in
  let _ =
    for i = 1 to n2 do
      phi'.(i).(0) <- i;
      for j = 1 to k do
	phi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)
      done;
    done;
  in
  let n3 = n /| Int64.of_int n2 in
  let (c, q) =
    let c = ref 0 in
    let q = ref 1 in
      while !c < k && !q * a.(!c) <= n2 do
	q := !q * a.(!c);
	incr c;
      done;
      (!c, !q)
  in
  let cnt = ref 0 in
  let cnt1 = ref 0 in
  let cnt2 = ref 0 in
  let cnt3 = ref 0 in
  let cnt4 = ref 0 in
  let rec phi m k =
    incr cnt;
    if k = 0
    then (
      incr cnt1;
      n /| m
    ) else if k = c then (
      incr cnt4;
      (n /| m /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)
    ) else if m > n3
    then (
      incr cnt2;
      Int64.of_int phi'.(Int64.to_int (n /| m)).(k)
    ) else (
      incr cnt3;
      phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)
    )
  in
  let res = phi 1L k in
    Printf.eprintf "asd %d %d %d %d %d %d\n" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;
    Printf.printf "%Ld\n" res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make k 0 in
  let _ =
    for i = 0 to k - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    (*Array.sort (fun x y -> compare y x) a;*)
    Array.sort compare a;
  in
  let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in
  let sn = isqrt n in
  let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in
  let n2 = min 200000L n in
  let n2 = Int64.to_int n2 in
  let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in
  let _ =
    for i = 1 to n2 do
      phi'.(i).(0) <- i;
      for j = 1 to k do
	phi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)
      done;
    done;
  in
  let n3 = n /| Int64.of_int n2 in
  let (c, q) =
    let c = ref 0 in
    let q = ref 1 in
      while !c < k && !q * a.(!c) <= n2 do
	q := !q * a.(!c);
	incr c;
      done;
      (!c, !q)
  in
  let cnt = ref 0 in
  let cnt1 = ref 0 in
  let cnt2 = ref 0 in
  let cnt3 = ref 0 in
  let cnt4 = ref 0 in
  (*let rec phi m k =
    (*incr cnt;*)
    if k = 0
    then (
      (*incr cnt1;*)
      n /| m
    ) else if k = c then (
      (*incr cnt4;*)
      (n /| m /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)
    ) else if m > n3
    then (
      (*incr cnt2;*)
      Int64.of_int phi'.(Int64.to_int (n /| m)).(k)
    ) else (
      (*incr cnt3;*)
      phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)
    )
  in
  let res = phi 1L k in*)
  let rec phi32 n k =
    (*incr cnt;*)
    if k = 0
    then n
    else if k = c
    then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)
    else if n <= n2
    then phi'.(n).(k)
    else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)
  in
  let rec phi n k =
    if k = 0
    then n
    else if k = c
    then
      (n /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)
    else if n <= 1000000000L
    then Int64.of_int (phi32 (Int64.to_int n) k)
    else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)
  in
  let res = phi n k in
    Printf.eprintf "asd %d %d %d %d %d %d\n" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;
    Printf.printf "%Ld\n" res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make k 0 in
  let _ =
    for i = 0 to k - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    (*Array.sort (fun x y -> compare y x) a;*)
    Array.sort compare a;
  in
  let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in
  let sn = isqrt n in
  let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in
  let n2 = min 250000L n in
  let n2 = Int64.to_int n2 in
  let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in
  let _ =
    for i = 1 to n2 do
      phi'.(i).(0) <- i;
      for j = 1 to k do
	phi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)
      done;
    done;
  in
  let n3 = n /| Int64.of_int n2 in
  let (c, q) =
    let c = ref 0 in
    let q = ref 1 in
      while !c < k && !q * a.(!c) <= n2 do
	q := !q * a.(!c);
	incr c;
      done;
      (!c, !q)
  in
  let cnt = ref 0 in
  let cnt1 = ref 0 in
  let cnt2 = ref 0 in
  let cnt3 = ref 0 in
  let cnt4 = ref 0 in
  let rec phi m k =
    (*incr cnt;*)
    if k = 0
    then (
      (*incr cnt1;*)
      n /| m
    ) else if k = c then (
      (*incr cnt4;*)
      (n /| m /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)
    ) else if m > n3
    then (
      (*incr cnt2;*)
      Int64.of_int phi'.(Int64.to_int (n /| m)).(k)
    ) else (
      (*incr cnt3;*)
      phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)
    )
  in
  let res = phi 1L k in
    Printf.eprintf "asd %d %d %d %d %d %d\n" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;
    Printf.printf "%Ld\n" res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make k 0 in
  let _ =
    for i = 0 to k - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    (*Array.sort (fun x y -> compare y x) a;*)
    Array.sort compare a;
  in
  let isqrt n = Int64.of_float (sqrt (Int64.to_float n)) in
  let sn = isqrt n in
  let cn = Int64.of_float ((Int64.to_float n) ** (1.0 /. 3.0) +. 0.00001) in
  let n2 = min 170000L n in
  let n2 = Int64.to_int n2 in
  let phi' = Array.make_matrix (n2 + 1) (k + 1) 0 in
  let _ =
    for i = 1 to n2 do
      phi'.(i).(0) <- i;
      for j = 1 to k do
	phi'.(i).(j) <- phi'.(i).(j - 1) - phi'.(i / a.(j - 1)).(j - 1)
      done;
    done;
  in
  let n3 = n /| Int64.of_int n2 in
  let (c, q) =
    let c = ref 0 in
    let q = ref 1 in
      while !c < k && !q * a.(!c) <= n2 do
	q := !q * a.(!c);
	incr c;
      done;
      (!c, !q)
  in
  let cnt = ref 0 in
  let cnt1 = ref 0 in
  let cnt2 = ref 0 in
  let cnt3 = ref 0 in
  let cnt4 = ref 0 in
  (*let rec phi m k =
    (*incr cnt;*)
    if k = 0
    then (
      (*incr cnt1;*)
      n /| m
    ) else if k = c then (
      (*incr cnt4;*)
      (n /| m /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem (n /| m) (Int64.of_int q))).(c)
    ) else if m > n3
    then (
      (*incr cnt2;*)
      Int64.of_int phi'.(Int64.to_int (n /| m)).(k)
    ) else (
      (*incr cnt3;*)
      phi m (k - 1) -| phi (m *| Int64.of_int a.(k - 1)) (k - 1)
    )
  in
  let res = phi 1L k in*)
  let rec phi32 n k =
    (*incr cnt;*)
    if k = 0
    then n
    else if k = c
    then (n / q) * phi'.(q).(k) + phi'.(n mod q).(c)
    else if n <= n2
    then phi'.(n).(k)
    else phi32 n (k - 1) - phi32 (n / a.(k - 1)) (k - 1)
  in
  let rec phi n k =
    if k = 0
    then n
    else if k = c
    then
      (n /| Int64.of_int q) *|
	  Int64.of_int phi'.(q).(k) +|
	      Int64.of_int
		phi'.(Int64.to_int (Int64.rem n (Int64.of_int q))).(c)
    else if n <= 1000000000L
    then Int64.of_int (phi32 (Int64.to_int n) k)
    else phi n (k - 1) -| phi (n /| Int64.of_int a.(k - 1)) (k - 1)
  in
  let res = phi n k in
    Printf.eprintf "asd %d %d %d %d %d %d\n" !cnt !cnt1 !cnt2 !cnt3 !cnt4 c;
    Printf.printf "%Ld\n" res


You are given an integer $$$n$$$. You have to apply $$$m$$$ operations to it.In a single operation, you must replace every digit $$$d$$$ of the number with the decimal representation of integer $$$d + 1$$$. For example, $$$1912$$$ becomes $$$21023$$$ after applying the operation once.You have to find the length of $$$n$$$ after applying $$$m$$$ operations. Since the answer can be very large, print it modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases. The only line of each test case contains two integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the initial number and the number of operations.

For each test case output the length of the resulting number modulo $$$10^9+7$$$.

NoteFor the first test, $$$1912$$$ becomes $$$21023$$$ after $$$1$$$ operation which is of length $$$5$$$.For the second test, $$$5$$$ becomes $$$21$$$ after $$$6$$$ operations which is of length $$$2$$$.For the third test, $$$999$$$ becomes $$$101010$$$ after $$$1$$$ operation which is of length $$$6$$$.For the fourth test, $$$88$$$ becomes $$$1010$$$ after $$$2$$$ operations which is of length $$$4$$$.

(* efficiency improvement to c0.ml *)
(* no mod operators. No longs.  Precompute all powers up to maxm *)
(* if too slow, there are still other ways to make it faster *)
open Printf
open Scanf

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

(* The following trick allows you to do addition mod p = 1_000_000_007
   of two numbers which are in [0,p-1].  It works when the
   ints are 31 bits (and longer) *)
let p = 1_000_000_007
let ( +++ ) a b = let x = a+b in if x >= p || x < 0 then x-p else x
let sum i j f = fold i j (fun i a -> (f i) +++ a) 0

let mat = Array.make_matrix 10 10 0
let () =
  mat.(0).(9) <- 1;
  mat.(1).(9) <- 1;
  for i=1 to 9 do
    mat.(i).(i-1) <- 1
  done

let mat_row_form = Array.init 10 (fun i ->
(* row i is a list of the indices where there's a 1 in mat *)
  fold 0 9 (fun j ac -> if mat.(i).(j) <> 0 then j::ac else ac) []
)

let mult_by_mat a =
  (* use the fact that mat is sparse *)
  let c = Array.make_matrix 10 10 0 in
  for i=0 to 9 do
    for j=0 to 9 do
      c.(i).(j) <- List.fold_left (
	fun ac k -> ac +++ a.(k).(j)
      ) 0 mat_row_form.(i)
    done
  done;
  c

let rec diglist n ac = if n=0 then ac else diglist (n/10) ((n mod 10)::ac)

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in
  let n = Array.make cases 0 in
  let m = Array.make cases 0 in

  for case = 0 to cases-1 do
    n.(case) <- read_int();
    m.(case) <- read_int();
  done;

  let maxm = maxf 0 (cases-1) (fun i -> m.(i)) in

  let power = Array.make (maxm+1) mat in
  (* power.(0) is wrong but is never used *)

  for i=2 to maxm do
    power.(i) <- mult_by_mat power.(i-1)
  done;

  for case = 0 to cases-1 do
    let dl = diglist n.(case) [] in
    let mymat = power.(m.(case)) in
    let count = Array.init 10 (fun j -> sum 0 9 (fun i -> mymat.(i).(j))) in
    (* count.(i) is the contribution of an initial digit i *)

    let answer = List.fold_left (fun ac d -> ac +++ count.(d)) 0 dl in
    printf "%d\n" answer
  done


Watto, the owner of a spare parts store, has recently got an order for the mechanism that can process strings in a certain way. Initially the memory of the mechanism is filled with n strings. Then the mechanism should be able to process queries of the following type: "Given string s, determine if the memory of the mechanism contains string t that consists of the same number of characters as s and differs from s in exactly one position".Watto has already compiled the mechanism, all that's left is to write a program for it and check it on the data consisting of n initial lines and m queries. He decided to entrust this job to you.

The first line contains two non-negative numbers n and m (0 ≤ n ≤ 3·105, 0 ≤ m ≤ 3·105) — the number of the initial strings and the number of queries, respectively. Next follow n non-empty strings that are uploaded to the memory of the mechanism. Next follow m non-empty strings that are the queries to the mechanism. The total length of lines in the input doesn't exceed 6·105. Each line consists only of letters 'a', 'b', 'c'.

For each query print on a single line "YES" (without the quotes), if the memory of the mechanism contains the required string, otherwise print "NO" (without the quotes).

type tree = Empty | Node of tree * tree * tree

let rec insert t str i len =
  if i=len then Node (Empty,Empty,Empty) else (
    let (ta,tb,tc) = match t with Empty -> (Empty,Empty,Empty) | Node (a,b,c) -> (a,b,c) in
    match str.[i] with
      | 'a' -> Node (insert ta str (i+1) len, tb, tc)
      | 'b' -> Node (ta, insert tb str (i+1) len, tc)
      | 'c' -> Node (ta, tb, insert tc str (i+1) len)
      | _ -> failwith "bad input"
  )

let rec search t str i len ecount =
  if ecount > 1 || t=Empty then false
  else if i=len then ecount=1 else (
    match t with Empty -> false
      | Node (ta,tb,tc) ->
	let ec x = if str.[i]=x then 0 else 1 in
	search ta str (i+1) len (ecount + (ec 'a')) ||
	  search tb str (i+1) len (ecount + (ec 'b')) ||
	  search tc str (i+1) len (ecount + (ec 'c'))
  )

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let string = Array.init n (fun _ -> read_string()) in
  let query = Array.init m (fun _ -> read_string()) in

  let tree = Array.make (6*100_000+1) Empty in

  for i=0 to n-1 do
    let len = String.length string.(i) in
    tree.(len) <- insert tree.(len) string.(i) 0 len;
  done;

  for i=0 to m-1 do
    let len = String.length query.(i) in
    let ans = search tree.(len) query.(i) 0 len 0 in
    if ans then printf "YES\n" else printf "NO\n"
  done

type 'a trie = {
  value : 'a option;
  children :  'a trie option array;
}

let list_of_string s = Array.to_list (Array.init (String.length s) (String.get s))

(* empty trie *)
let empty () =
  { value = None;
    children = Array.make 3 None;
  }

let insert t s =
  let rec insert' t p = function
    | [] -> { t with value = Some p }
    | c :: cs ->
        (* index into child array *)
        let i = Char.code c - Char.code 'a' in
        (* replacement node *)
        let n = match t.children.(i) with
        | None -> empty ()
        | Some t -> t
        in
        t.children.(i) <- Some (insert' n c cs);
        t
  in
  insert' t 'z' (list_of_string s)

let find t s =
  let rec find' t p c = function
  | [] -> c && t.value = Some p
  | x :: xs ->
      if c
      then begin
        match t.children.(Char.code x - Char.code 'a') with
        | None -> false
        | Some c -> find' c x true xs
      end
      else begin
        let rec aux a i =
          if i = 3 then a
          else
            match t.children.(i) with
            | None -> aux a (succ i)
            | Some t -> aux (a || find' t (Char.chr (i + Char.code 'a')) (Char.code x - Char.code 'a' <> i) xs) (succ i)
        in
        aux false 0
      end
  in
  find' t 'y' false (list_of_string s)

let () = Scanf.scanf "%d %d\n" (fun n m ->
  (* read memory and construct trie *)
  let rec aux t i =
    if i = n then t else begin
      let t = Scanf.scanf "%s\n" (insert t) in
      aux t (succ i)
    end
  in
  let t = aux (empty ()) 0 in

  (* read and response to queries *)
  for i = 1 to m do
    let q = Scanf.scanf "%s\n" (fun s -> s) in
    print_endline (if find t q then "YES" else "NO")
  done
)