In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya's birthday, and her mother decided to spend no more than m bourles on the gift to the daughter. Tanya will choose several different types of toys from the new collection as a gift. Of course, she does not want to get a type of toy which she already has.Tanya wants to have as many distinct types of toys in her collection as possible as the result. The new collection is too diverse, and Tanya is too little, so she asks you to help her in this.

The first line contains two integers n (1 ≤ n ≤ 100 000) and m (1 ≤ m ≤ 109) — the number of types of toys that Tanya already has and the number of bourles that her mom is willing to spend on buying new toys. The next line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the types of toys that Tanya already has.

In the first line print a single integer k — the number of different types of toys that Tanya should choose so that the number of different types of toys in her collection is maximum possible. Of course, the total cost of the selected toys should not exceed m. In the second line print k distinct space-separated integers t1, t2, ..., tk (1 ≤ ti ≤ 109) — the types of toys that Tanya should choose. If there are multiple answers, you may print any of them. Values of ti can be printed in any order.

NoteIn the first sample mom should buy two toys: one toy of the 2-nd type and one toy of the 5-th type. At any other purchase for 7 bourles (assuming that the toys of types 1, 3 and 4 have already been bought), it is impossible to buy two and more toys.

open Scanf
open Printf

let scan_int () = Scanf.scanf " %d " (fun i -> i);;
let scan_string () = Scanf.scanf " %s" (fun i -> i);;

let answer ts m =
  let rec aux ts m i c acc =
    if c > m then acc
    else
      if i >= Array.length ts
      then aux ts (m-c) i (c+1) (c::acc)
      else
        let t = Array.get ts i in
        if c < t
        then aux ts (m-c) i (c+1) (c::acc)
        else aux ts m (i+1) (c+1) acc
  in aux ts m 0 1 []

let () =
  let n = scan_int () in
  let m = scan_int () in

  let ts = Array.make n 0 in

  for i=0 to n-1 do
    let t = scan_int () in
    Array.set ts i t
  done;

  Array.sort compare ts;

  let ans = answer ts m in
  Printf.printf "%d\n" (List.length ans);
  List.iter (fun t -> Printf.printf "%d " t) ans;
  Printf.printf "\n";;

open Scanf
open Printf

let scan_int () = Scanf.scanf " %d " (fun i -> i);;
let scan_string () = Scanf.scanf " %s" (fun i -> i);;

let answer ts m =
  let rec aux ts m i c acc =
    if c > m || i >= Array.length ts then acc
    else
      let t = Array.get ts i in
      if c < t
      then aux ts (m-c) i (c+1) (c::acc)
      else aux ts m (i+1) (c+1) acc
  in aux ts m 0 1 []

let () =
  let n = scan_int () in
  let m = scan_int () in

  let ts = Array.make n 0 in

  for i=0 to n-1 do
    let t = scan_int () in
    Array.set ts i t
  done;

  Array.sort compare ts;

  let ans = answer ts m in
  Printf.printf "%d\n" (List.length ans);
  List.iter (fun t -> Printf.printf "%d " t) ans;
  Printf.printf "\n";;


For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \le j < d$$$ and $$$d < j \le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \le j \le n$$$.Help mayor find the earliest not-so-rainy day of summer.

The first line contains three integers $$$n$$$, $$$x$$$ and $$$y$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le x, y \le 7$$$) — the number of days in summer, the number of days citizens watch the weather before the celebration and the number of days they do that after. The second line contains $$$n$$$ distinct integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ denotes the rain amount on the $$$i$$$-th day.

Print a single integer — the index of the earliest not-so-rainy day of summer. We can show that the answer always exists.

NoteIn the first example days $$$3$$$ and $$$8$$$ are not-so-rainy. The $$$3$$$-rd day is earlier.In the second example day $$$3$$$ is not not-so-rainy, because $$$3 + y = 6$$$ and $$$a_3 > a_6$$$. Thus, day $$$8$$$ is the answer. Note that $$$8 + y = 11$$$, but we don't consider day $$$11$$$, because it is not summer.

open Scanf
open Printf

let readInt () = scanf " %d" (fun x -> x)

exception Ret of int

let solve n x y a =
  try
    for i=0 to n-1 do
    let ok =
      try
        for j=max 0 (i-x) to i-1 do if a.(j) <= a.(i) then raise Exit done;
        for j=i+1 to min (n-1) (i+y) do if a.(j) <= a.(i) then raise Exit done;
        true
      with Exit -> false
    in
    if ok then raise (Ret i)
    done;
    -1
  with Ret i -> i

let main () =
  let n = readInt () in
  let x = readInt () in
  let y = readInt () in
  let a = Array.init n (fun _ -> readInt ()) in
  printf "%d\n" (solve n x y a + 1)

let () = main ()


Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the maximum value of his brother's array b. Now you have to help Devu in achieving this condition. You can perform multiple operations on the arrays. In a single operation, you are allowed to decrease or increase any element of any of the arrays by 1. Note that you are allowed to apply the operation on any index of the array multiple times.You need to find minimum number of operations required to satisfy Devu's condition so that the brothers can play peacefully without fighting.

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). The second line will contain n space-separated integers representing content of the array a (1 ≤ ai ≤ 109). The third line will contain m space-separated integers representing content of the array b (1 ≤ bi ≤ 109).

You need to output a single integer representing the minimum number of operations needed to satisfy Devu's condition.

NoteIn example 1, you can increase a1 by 1 and decrease b2 by 1 and then again decrease b2 by 1. Now array a will be [3; 3] and array b will also be [3; 3]. Here minimum element of a is at least as large as maximum element of b. So minimum number of operations needed to satisfy Devu's condition are 3.In example 3, you don't need to do any operation, Devu's condition is already satisfied.

open Printf
open Scanf

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

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

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

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
  let b = Array.init m (fun _ -> read_int()) in

  let next_hi_event s =
    let (h0,_) = Imap.max_binding s in
    let s = Imap.remove h0 s in
    if Imap.is_empty s then h0 else
      let (h1,_) = Imap.max_binding s in
      h0-h1
  in

  let next_lo_event s =
    let (h0,_) = Imap.min_binding s in
    let s = Imap.remove h0 s in
    if Imap.is_empty s then h0 else
      let (h1,_) = Imap.min_binding s in
      h1-h0
  in

  let add_to h delta s =
    let c = try Imap.find h s with Not_found -> 0 in
    Imap.add h (c+delta) s
  in

  let buildset a sz =
    fold 0 (sz-1) (fun i ac -> add_to a.(i) 1 ac) Imap.empty
  in

  let lower_set move_size s =
    let (h,c) = Imap.max_binding s in
    let s = Imap.remove h s in
    add_to (h-move_size) c s
  in

  let raise_set move_size s =
    let (h,c) = Imap.min_binding s in
    let s = Imap.remove h s in
    add_to (h+move_size) c s
  in

  let rec loop a_set b_set ac =
    let (hb,wb) = Imap.max_binding b_set in
    let (ha,wa) = Imap.min_binding a_set in
    if hb <= ha then ac else
      if wb <= wa then ( (* push down on b *)
	let move_size = next_hi_event b_set in
	let move_size = min move_size (hb-ha) in
	let b_set = lower_set move_size b_set in
	let ac = ac ++ (Int64.of_int move_size) ** (Int64.of_int wb) in
	loop a_set b_set ac
      ) else (	         (* push up on a *)
	let move_size = next_lo_event a_set in
	let move_size = min move_size (hb-ha) in
	let a_set = raise_set move_size a_set in
	let ac = ac ++ (Int64.of_int move_size) ** (Int64.of_int wa) in
	loop a_set b_set ac
      )
  in

  let a_set = buildset a n in
  let b_set = buildset b m in

  printf "%Ld\n" (loop a_set b_set 0L)


You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the size of deck you have. The second line contains $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ ($$$1 \le p_i \le n$$$; $$$p_i \neq p_j$$$ if $$$i \neq j$$$) — values of card in the deck from bottom to top. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print the deck with maximum possible order. Print values of cards in the deck from bottom to top. If there are multiple answers, print any of them.

(** https://codeforces.com/contest/1492/problem/B *)

let deck () =
    let _ = read_line () in
    let cards =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map int_of_string in
    cards in

let max_deck cards =
    let rec helper currmax cs stack deck =
        match cs with
        | [] -> List.flatten ((List.rev stack)::deck)
        | card::rest ->
            if card > currmax
            then
                let new_deck = if stack <> [] then (List.rev stack)::deck else deck in
                let new_stack = [card] in
                helper card rest new_stack new_deck
            else
                helper currmax rest (card::stack) deck in
    helper 0 cards [] [] in

let print_deck cards =
    let rec helper cs =
        match cs with
        | [] -> print_newline ()
        | h::t ->
            Printf.printf "%d " h;
            helper t in
    helper cards in

let nb_case = read_int () in
for i = 0 to nb_case-1 do
    deck ()
    |> max_deck
    |> print_deck
done


In an attempt to escape the Mischievous Mess Makers' antics, Farmer John has abandoned his farm and is traveling to the other side of Bovinia. During the journey, he and his k cows have decided to stay at the luxurious Grand Moo-dapest Hotel. The hotel consists of n rooms located in a row, some of which are occupied.Farmer John wants to book a set of k + 1 currently unoccupied rooms for him and his cows. He wants his cows to stay as safe as possible, so he wishes to minimize the maximum distance from his room to the room of his cow. The distance between rooms i and j is defined as |j - i|. Help Farmer John protect his cows by calculating this minimum possible distance.

The first line of the input contains two integers n and k (1 ≤ k < n ≤ 100 000) — the number of rooms in the hotel and the number of cows travelling with Farmer John. The second line contains a string of length n describing the rooms. The i-th character of the string will be '0' if the i-th room is free, and '1' if the i-th room is occupied. It is guaranteed that at least k + 1 characters of this string are '0', so there exists at least one possible choice of k + 1 rooms for Farmer John and his cows to stay in.

Print the minimum possible distance between Farmer John's room and his farthest cow.

NoteIn the first sample, Farmer John can book room 3 for himself, and rooms 1 and 4 for his cows. The distance to the farthest cow is 2. Note that it is impossible to make this distance 1, as there is no block of three consecutive unoccupied rooms.In the second sample, Farmer John can book room 1 for himself and room 3 for his single cow. The distance between him and his cow is 2.In the third sample, Farmer John books all three available rooms, taking the middle room for himself so that both cows are next to him. His distance from the farthest cow is 1.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let next i =
    let i = ref (i + 1) in
      while !i < n && s.[!i] = '1' do
	incr i
      done;
      !i
  in
  let res = ref n in
  let l = ref (-1) in
  let r = ref (-1) in
  let _ =
    l := next !l;
    for i = 1 to k + 1 do
      r := next !r;
    done;
  in
  let m1 = ref (!l + (!r - !l) / 2) in
  let m2 = ref (!r - (!r - !l) / 2) in
  let _ =
    while s.[!m1] = '1' do
      decr m1
    done;
    while s.[!m2] = '1' do
      incr m2
    done;
  in
    while !r < n do
      let d = min (!r - !m1) (!m2 - !l) in
	(*Printf.printf "asd %d %d %d %d  %d\n" !l !m1 !m2 !r d;*)
	res := min !res d;
	l := next !l;
	r := next !r;
	let m = (!l + !r) / 2 in
	  while next !m1 <= m do
	    m1 := next !m1
	  done;
	  while !m2 <= m do
	    m2 := next !m2
	  done
    done;
    Printf.printf "%d\n" !res;


The Bitlandians are quite weird people. They have their own problems and their own solutions. They have their own thoughts and their own beliefs, they have their own values and their own merits. They have their own dishes and their own sausages!In Bitland a sausage is an array of integers! A sausage's deliciousness is equal to the bitwise excluding OR (the xor operation) of all integers in that sausage. One day, when Mr. Bitkoch (the local cook) was going to close his BitRestaurant, BitHaval and BitAryo, the most famous citizens of Bitland, entered the restaurant and each ordered a sausage.But Mr. Bitkoch had only one sausage left. So he decided to cut a prefix (several, may be zero, first array elements) of the sausage and give it to BitHaval and a postfix (several, may be zero, last array elements) of the sausage and give it to BitAryo. Note that one or both pieces of the sausage can be empty. Of course, the cut pieces mustn't intersect (no array element can occur in both pieces).The pleasure of BitHaval and BitAryo is equal to the bitwise XOR of their sausages' deliciousness. An empty sausage's deliciousness equals zero.Find a way to cut a piece of sausage for BitHaval and BitAryo that maximizes the pleasure of these worthy citizens.

The first line contains an integer n (1 ≤ n ≤ 105). The next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 1012) — Mr. Bitkoch's sausage. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print a single integer — the maximum pleasure BitHaval and BitAryo can get from the dinner.

let nbits = 40
let ( ^ ) = Int64.logxor

type trie = Empty | Node of trie * trie

let rec insert_into_trie n list =
  let (l,r) = match n with Empty -> (Empty,Empty) | Node(l,r) -> (l,r) in
    match list with [] -> Node(l,r)
      | 0::tail -> Node (insert_into_trie l tail, r)
      | _::tail -> Node (l, insert_into_trie r tail)

let rec best_in_trie t x guide = match (t,guide) with
  | (_, []) -> x
  | (Empty,_) -> failwith "best_in_trie fail"
  | (Node(l,r), g::tail) ->
      let (t,b) = if (g=1 && l=Empty) || (g=0 && r<>Empty) then (r,1L) else (l,0L) in
	best_in_trie t (Int64.logor b (Int64.shift_left x 1)) tail

let bits_to_list x = (* make a list of bits, high order first *)
  let rec loop i x ac = if i=nbits then ac else
    loop (i+1) (Int64.shift_right_logical x 1) (Int64.to_int ((Int64.logand x 1L))::ac)
  in
    loop 0 x []

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

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

let () =
  let n = read_int 0 in
  let a = Array.init n read_long in
  let allxor = sum 0 (n-1) (fun i -> a.(i)) in

  let rec loop i xor0 t ac =
    (* i=0....n, represent the n+1 dividing line positions
       xor0 is the xor to the left of the line, t is the current trie
       (not including xor0), ac is the max value achieved so far.    *)
    let t = insert_into_trie t (bits_to_list xor0) in
    let xor1 = xor0 ^ allxor in
    let guide = bits_to_list xor1 in
    let best = best_in_trie t 0L guide in
    let ac = max ac (best ^ xor1) in
      if i >= n then ac else
	loop (i+1) (a.(i) ^ xor0) t ac
  in
    Printf.printf "%Ld\n" (loop 0 0L Empty 0L)


Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

let ( * ) = Int64.mul
let ( + ) = Int64.add
let ( - ) = Int64.sub
let ( / ) = Int64.div
let zero = Int64.zero
let one = Int64.one
let two = Int64.of_int 2

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

let make_list () =
    let n = read () in
    let rec loop i list =
        if i < n
        then
            let value = read () in
            loop (i + one) (value :: list)
        else
            List.sort (Pervasives.compare) list
    in loop zero []

let get_min_max list =
    let min = List.hd list in
    let max = List.hd (List.rev list) in
    (min, max)

let counter value list =
    Int64.of_int (List.length (List.filter (fun x -> x = value) list))

let get_max_pairs (min, max) list =
    let min_count = counter min list in
    let max_count = counter max list in
    if min = max
    then
        (min_count * (min_count - one)) / two
    else
        min_count * max_count

let solve () =
    let flowers = make_list () in
    let (min, max) = get_min_max flowers in
    let max_diff = max - min in
    let max_pairs = get_max_pairs (min, max) flowers in
    (max_diff, max_pairs)

let print (a, b) = Printf.printf "%Ld %Ld\n" a b

let () = print (solve ())

let ( * ) = Int64.mul
let ( + ) = Int64.add
let ( - ) = Int64.sub
let zero = Int64.zero
let one = Int64.one

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

let make_list () =
    let n = read () in
    let rec loop i list =
        if i < n
        then
            let value = read () in
            loop (i + one) (value :: list)
        else
            List.sort (Pervasives.compare) list
    in loop zero []

let counter value list =
    Int64.of_int (List.length (List.filter (fun x -> x = value) list))

let get_min_max list =
    let min = List.hd list in
    let max = List.hd (List.rev list) in
    (min, max)

let solve () =
    let flowers = make_list () in
    let (min, max) = get_min_max flowers in
    let max_diff = max - min in
    let min_count = counter min flowers in
    let max_count = counter max flowers in
    let max_pairs = max_count * min_count in
    (max_diff, max_pairs)

let print (a, b) = Printf.printf "%Ld %Ld\n" a b

let () = print (solve ())

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

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.sort (Pervasives.compare) list
    in loop 0 []

let counter value list =
    List.length (List.filter (fun x -> x = value) list)

let get_min_max list =
    let min = List.hd list in
    let max = List.hd (List.rev list) in
    (min, max)

let solve () =
    let flowers = make_list () in
    let (min, max) = get_min_max flowers in
    let max_diff = max - min in
    let min_count = counter min flowers in
    let max_count = counter max flowers in
    let max_pairs = max_count * min_count in
    (max_diff, max_pairs)

let print (a, b) = Printf.printf "%d %d\n" a b

let () = print (solve ())


Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.

The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.

If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes). Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct. If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair. Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.

open Printf
open Scanf

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

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

  let n2l n = char_of_int ((int_of_char 'a') + n) in
  let l2n c = (int_of_char c) - (int_of_char 'a') in

  let fix s = Array.init n (fun i -> l2n s.[i]) in
  let s = fix s in
  let t = fix t in

  let map = Array.make 26 (-1) in
  let rmap = Array.make 26 (-1) in

  let error = ref false in
  for i=0 to n-1 do
    let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||
      (map.(s.(i)) <> -1 && rmap.(t.(i)) <> -1 &&
	 map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))
    in
    if good then (
      map.(s.(i)) <- t.(i);
      rmap.(t.(i)) <- s.(i);
      rmap.(s.(i)) <- t.(i);
      map.(t.(i)) <- s.(i);
    ) else (
      error := true
    )
  done;

  if !error then printf "-1\n" else (
    let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in
    printf "%d\n" swapcount;
    for c=0 to 25 do
      if map.(c) <> -1 && map.(c) > c then
	printf "%c %c\n" (n2l c) (n2l map.(c))
    done;
  )

open Printf
open Scanf

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

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

  let n2l n = char_of_int ((int_of_char 'a') + n) in
  let l2n c = (int_of_char c) - (int_of_char 'a') in

  let fix s = Array.init n (fun i -> l2n s.[i]) in
  let s = fix s in
  let t = fix t in

  let map = Array.make 26 (-1) in
  let rmap = Array.make 26 (-1) in

  let error = ref false in
  for i=0 to n-1 do
    let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||
      (map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))
    in
    if good then (
      map.(s.(i)) <- t.(i);
      rmap.(t.(i)) <- s.(i);
    ) else (
      error := true
    )
  done;

  if !error then printf "-1\n" else (
    let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) <> c then 1 else 0) in
    printf "%d\n" swapcount;
    for c=0 to 25 do
      if map.(c) <> -1 && map.(c) > c then
	printf "%c %c\n" (n2l c) (n2l map.(c))
    done;
  )

open Printf
open Scanf

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

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

  let n2l n = char_of_int ((int_of_char 'a') + n) in
  let l2n c = (int_of_char c) - (int_of_char 'a') in

  let fix s = Array.init n (fun i -> l2n s.[i]) in
  let s = fix s in
  let t = fix t in

  let map = Array.make 26 (-1) in
  let rmap = Array.make 26 (-1) in

  let error = ref false in
  for i=0 to n-1 do
    let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||
      (map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i) && rmap.(s.(i)) = t.(i) && map.(t.(i)) = s.(i))
    in
    if good then (
      map.(s.(i)) <- t.(i);
      rmap.(t.(i)) <- s.(i);
    ) else (
      error := true
    )
  done;

  if !error then printf "-1\n" else (
    let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in
    printf "%d\n" swapcount;
    for c=0 to 25 do
      if map.(c) <> -1 && map.(c) > c then
	printf "%c %c\n" (n2l c) (n2l map.(c))
    done;
  )

open Printf
open Scanf

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

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

  let n2l n = char_of_int ((int_of_char 'a') + n) in
  let l2n c = (int_of_char c) - (int_of_char 'a') in

  let fix s = Array.init n (fun i -> l2n s.[i]) in
  let s = fix s in
  let t = fix t in

  let map = Array.make 26 (-1) in
  let rmap = Array.make 26 (-1) in

  let error = ref false in
  for i=0 to n-1 do
    let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||
      (map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))
    in
    if good then (
      map.(s.(i)) <- t.(i);
      rmap.(t.(i)) <- s.(i);
    ) else (
      error := true
    )
  done;

  if !error then printf "-1\n" else (
    let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in
    printf "%d\n" swapcount;
    for c=0 to 25 do
      if map.(c) <> -1 && map.(c) > c then
	printf "%c %c\n" (n2l c) (n2l map.(c))
    done;
  )

open Printf
open Scanf

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

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

  let n2l n = char_of_int ((int_of_char 'a') + n) in
  let l2n c = (int_of_char c) - (int_of_char 'a') in

  let fix s = Array.init n (fun i -> l2n s.[i]) in
  let s = fix s in
  let t = fix t in

  let map = Array.make 26 (-1) in
  let rmap = Array.make 26 (-1) in

  let error = ref false in
  for i=0 to n-1 do
    let good = (map.(s.(i)) = -1 && rmap.(t.(i)) = -1) ||
      (map.(s.(i)) <> -1 && rmap.(t.(i)) <> -1 &&
	 map.(s.(i)) = t.(i) && rmap.(t.(i)) = s.(i))
    in
    if good then (
      map.(s.(i)) <- t.(i);
      rmap.(t.(i)) <- s.(i);
    ) else (
      error := true
    )
  done;

  if !error then printf "-1\n" else (
    let swapcount = sum 0 25 (fun c -> if map.(c) <> -1 && map.(c) > c then 1 else 0) in
    printf "%d\n" swapcount;
    for c=0 to 25 do
      if map.(c) <> -1 && map.(c) > c then
	printf "%c %c\n" (n2l c) (n2l map.(c))
    done;
  )


Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares?

The first line contains four space-separated integers a1, a2, a3, a4 (0 ≤ a1, a2, a3, a4 ≤ 104). The second line contains string s (1 ≤ |s| ≤ 105), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.

Print a single integer — the total number of calories that Jury wastes.

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

let digit_to_int c =
    Pervasives.int_of_char c - Pervasives.int_of_char '0'

let input () =
    let costs = Scanf.scanf "%d %d %d %d " (fun a b c d -> [a; b; c; d]) in
    let moves = Scanf.scanf "%s" (fun s -> List.map digit_to_int (str_to_list s)) in
    (costs, moves)

let solve (costs, moves) =
    List.fold_left (+) 0 (List.map (fun n -> List.nth costs (n - 1)) moves)

let print result = Printf.printf "%d\n" result
let () = print (solve (input ()))

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

let digit_to_int c =
    Pervasives.int_of_char c - Pervasives.int_of_char '0'

let input () =
    let costs = Scanf.scanf "%d %d %d %d " (fun a b c d -> [a; b; c; d]) in
    let moves = Scanf.scanf "%s" (fun s -> List.map digit_to_int (str_to_list s)) in
    (costs, moves)

let solve (costs, moves) =
    let rec loop list i total =
        match list with
        | (head :: tail) ->
            let quantity = List.length (List.filter (fun n -> n = i) moves) in
            let curr_cost = head * quantity in
            loop tail (i + 1) (total + curr_cost)
        | [] -> total
    in loop costs 1 0

let print result = Printf.printf "%d\n" result
let () = print (solve (input ()))

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 a = Array.init 4 (fun _ -> read_int()) in
  let s = read_string () in

  let n = String.length s in

  let t = ref 0 in

  for i=0 to n-1 do
    let d = (int_of_char s.[i]) - (int_of_char '1') in
    t := !t + a.(d)
  done;

  printf "%d\n" !t

let read_int()=Scanf.scanf "%d " (fun x->x);;
let a=read_int();;
let b=read_int();;
let c=read_int();;
let tab=Array.make 5 0;;
tab.(1)<-a;;
tab.(2)<-b;;
tab.(3)<-c;;
let d=Scanf.scanf "%d\n" (fun x->x);;
tab.(4)<-d;;
let s=Scanf.scanf "%s" (fun x->x);;
let n=String.length(s);;
let nb=ref 0;;
for i=0 to n-1 do
   nb:= !nb+tab.(int_of_char(s.[i])-48)
done;;
print_int !nb;;

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)

open Printf
open Scanf
open Array

module S = String
module Q = Queue
module T = Stack
module H = Hashtbl
module L = List

(* misc *)
let neg_compare x y = - compare x y
let min3 a b c = min a (min b c)
let mid3 a b c = if a < b then max a (min b c) else max b (min a c)
let max3 a b c = max a (max b c)
let min4 a b c d = min (min a b) (min c d)
let max4 a b c d = max (max a b) (max c d)
let itb a = a <> 0
let bti b = if b then 1 else 0
let rec bsearch_min a b test =
  if b - a = 1 then b else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_min a mid test else
  bsearch_min mid b test
let rec bsearch_max a b test =
  if b - a = 1 then a else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_max mid b test else
  bsearch_max a mid test
(* int *)
let sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)
let sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i)
(* float *)
let round f = truncate (f +. 0.5)
let inv_float f = 1. /. f
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let (@@) a b = a b
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
let rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let default x = function Some y -> y | None -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
let swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t
(* int, int *)
let (++) (a,b) (c,d) = (a+c,b+d)
let (--) (a,b) (c,d) = (a-c,b-d)
(* number theory *)
let sieve_under len = (* len > 0 *)
  let sieve  = Array.make len true in
  Array.fill sieve 0 (min len 2) false;
  let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in
  for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;
  sieve
(* Arithmetic *)
let negate x = -x
let rec factorial n = if n = 0 then 1 else n * factorial (n-1)
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
let rec modpow m x n =
  if n = 0 then 1 else
  let n' = n/2 in
  let p = modpow m x n' in
  if is_even n then (p*p mod m) else
  (x*(p*p mod m) mod m)
let modinv m i = let _,x,_ = extgcd m i in x
(* IO *)
let is_digit c =
  let i = int_of_char c in
  48 <= i && i < 58
let is_space c = c = ' ' || c = '\n' || c = '\t' || c = '\r'
let read_char () = try input_char stdin with End_of_file -> '\000'
let rec read_letter () =
  let c = read_char() in
  if is_space c then read_letter() else c
let read_int () =
  let digit c = int_of_char c - 48 in
  let rec read n =
    let c = read_char() in
    if is_digit c then read (10*n + (digit c)) else
    n
  in
  let rec run c =
    if is_digit c then read (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -read (digit c) else run c
    end else
    if c = '\000' then 0 else
    run (read_char())
  in
  run (read_char())
let read_float () =
  let digit c = float (int_of_char c - 48) in
  let rec read_decimial m f =
    let c = read_char () in
    if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f
  in
  let rec read_integral n =
    let c = read_char () in
    if is_digit c then read_integral (10. *. n +. digit c) else
    if c = '.' then n +. read_decimial 0.1 0.0 else
    n
  in
  let rec run c = begin
    if is_digit c then read_integral (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -. read_integral (digit c) else
      run c
    end else
    if c = '.' then read_decimial 0.1 0.0 else
    if c = '\000' then 0.0 else
    run (read_char())
  end in
  run (read_char())
let read_word () =
  let open Buffer in
  let buf = create 128 in
  let rec read c =
    if is_space c || c = '\000' then contents buf else begin
      add_char buf c;
      read (read_char())
    end
  in
  let rec run c =
    if is_space c then run (read_char()) else
    if c = '\000' then "" else
    read c
  in
  run (read_char())
let read_line () =
  let open Buffer in
  let buf = create (4*1024) in
  let rec run c =
    if c = '\n' || c = '\000' then contents buf else begin
      add_char buf c;
      run (read_char())
    end
  in
  run (read_char())
let newline () = print_newline()
let print_int n = printf "%d\n" n
let print_tuple s (x,y) = printf s x y
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  let arr = init 4 (fun i -> read_int()) in
  let str = read_line() in

  let len = S.length str in
  let rec run i acc =
    if i = len then acc else
    run (i+1) (acc + arr.(int_of_char str.[i] - 49))
  in
  printf "%d\n" (run 0 0)


A row of $$$n$$$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}$$$ and as $$$\color{red}{\texttt{R}}\color{blue}{\texttt{B}}$$$.During use, the stamp must completely fit on the given $$$n$$$ cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.For example, one possible sequence of stamps to make the picture $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\color{blue}{\texttt{B}}\texttt{W}$$$ could be $$$\texttt{WWWWW} \to \texttt{WW}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\texttt{W} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\texttt{W} \to \color{blue}{\texttt{B}}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}\texttt{W}$$$. Here $$$\texttt{W}$$$, $$$\color{red}{\texttt{R}}$$$, and $$$\color{blue}{\texttt{B}}$$$ represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.Given a final picture, is it possible to make it using the stamp zero or more times?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the picture. The second line of each test case contains a string $$$s$$$ — the picture you need to make. It is guaranteed that the length of $$$s$$$ is $$$n$$$ and that $$$s$$$ only consists of the characters $$$\texttt{W}$$$, $$$\texttt{R}$$$, and $$$\texttt{B}$$$, representing a white, red, or blue cell, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output "YES" if it possible to make the picture using the stamp zero or more times, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

12
5
BRBBW
1
B
2
WB
2
RW
3
BRB
3
RBB
7
WWWWWWW
9
RBWBWRRBW
10
BRBRBRBRRB
12
BBBRWWRRRWBR
10
BRBRBRBRBW
5
RBWBW

YES
NO
NO
NO
YES
YES
YES
NO
YES
NO
YES
NO

NoteThe first test case is explained in the statement.For the second, third, and fourth test cases, it is not possible to stamp a single cell, so the answer is "NO".For the fifth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{blue}{\texttt{B}}$$$.For the sixth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}$$$.For the seventh test case, you don't need to use the stamp at all.

let getInt () = Scanf.scanf " %d" (fun i -> i);;

let getList(n): int list =
  let rec getList2 ((n: int), (acc: int list)) = match n with
	  | 0 -> List.rev acc
	  | _ -> getList2 (n-1, getInt() :: acc)
  in getList2(n, [])

let getLine() = Scanf.scanf " %s" (fun i -> i);;

let rec solve((s: char list), (w: int), (b: int)): bool =
  let len = w + b in
  match s with
  | [] -> (len = 0 || (w > 0 && b > 0))

  | 'W' :: xs -> if len = 0 || (w > 0 && b > 0) then solve(xs, 0, 0)
  else false

  | 'B' :: xs -> solve(xs, w, b + 1)

  | 'R' :: xs -> solve(xs, w + 1, b)

  | _ -> false

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

let main() =
  let t = getInt() in
  for i = 1 to t do
    let n = getInt() in let s = getLine() in let arr = explode(s)
  in if solve(arr, 0, 0) then print_endline("YES")
  else print_endline("NO")
  done;;

main();;


Ashish has a tree consisting of $$$n$$$ nodes numbered $$$1$$$ to $$$n$$$ rooted at node $$$1$$$. The $$$i$$$-th node in the tree has a cost $$$a_i$$$, and binary digit $$$b_i$$$ is written in it. He wants to have binary digit $$$c_i$$$ written in the $$$i$$$-th node in the end.To achieve this, he can perform the following operation any number of times:   Select any $$$k$$$ nodes from the subtree of any node $$$u$$$, and shuffle the digits in these nodes as he wishes, incurring a cost of $$$k \cdot a_u$$$. Here, he can choose $$$k$$$ ranging from $$$1$$$ to the size of the subtree of $$$u$$$. He wants to perform the operations in such a way that every node finally has the digit corresponding to its target.Help him find the minimum total cost he needs to spend so that after all the operations, every node $$$u$$$ has digit $$$c_u$$$ written in it, or determine that it is impossible.

First line contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ denoting the number of nodes in the tree. $$$i$$$-th line of the next $$$n$$$ lines contains 3 space-separated integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ $$$(1 \leq a_i \leq 10^9, 0 \leq b_i, c_i \leq 1)$$$  — the cost of the $$$i$$$-th node, its initial digit and its goal digit. Each of the next $$$n - 1$$$ lines contain two integers $$$u$$$, $$$v$$$ $$$(1 \leq u, v \leq n, \text{ } u \ne v)$$$, meaning that there is an edge between nodes $$$u$$$ and $$$v$$$ in the tree.

Print the minimum total cost to make every node reach its target digit, and $$$-1$$$ if it is impossible.

NoteThe tree corresponding to samples $$$1$$$ and $$$2$$$ are: In sample $$$1$$$, we can choose node $$$1$$$ and $$$k = 4$$$ for a cost of $$$4 \cdot 1$$$ = $$$4$$$ and select nodes $$${1, 2, 3, 5}$$$, shuffle their digits and get the desired digits in every node.In sample $$$2$$$, we can choose node $$$1$$$ and $$$k = 2$$$ for a cost of $$$10000 \cdot 2$$$, select nodes $$${1, 5}$$$ and exchange their digits, and similarly, choose node $$$2$$$ and $$$k = 2$$$ for a cost of $$$2000 \cdot 2$$$, select nodes $$${2, 3}$$$ and exchange their digits to get the desired digits in every node.In sample $$$3$$$, it is impossible to get the desired digits, because there is no node with digit $$$1$$$ initially.

open Printf
open Scanf

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

let long x = Int64.of_int x
let short x = Int64.to_int x

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

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

let () =
  let n = read_int() in
  let a = Array.make n 0L in
  let b = Array.make n 0 in
  let c = Array.make n 0 in
  for i=0 to n-1 do
    a.(i) <- read_long ();
    b.(i) <- read_int ();
    c.(i) <- read_int ();
  done;

  let tree = Array.make n [] in

  for i=1 to n-1 do
    let (u,v) = read_pair() in
    let (u,v) = (u-1,v-1) in
    tree.(u) <- v::tree.(u);
    tree.(v) <- u::tree.(v)
  done;

  let ones_there = sum 0 (n-1) (fun i -> b.(i)) in
  let ones_wanted = sum 0 (n-1) (fun i -> c.(i)) in
  if ones_there <> ones_wanted then (
    printf "-1\n"
  ) else (

    (*
    let ex = Array.make_matrix 2 n 0 in  (*excess 0s and 1s *)

    let rec dfs0 p u =
      let rec loop li ac0 ac1 =
	match li with
	  | [] -> (ac0, ac1)
	  | v::tail ->
	    if v = p then loop tail ac0 ac1 else
	      let (v0, v1) = dfs0 u v in
	      loop tail (ac0+v0) (ac1+v1)
      in
      let (ac0, ac1) = loop tree.(u) 0 0 in
      let ac0 = ac0 + (if b.(u) = 0 && c.(u) = 1 then 1 else 0) in
      let ac1 = ac1 + (if b.(u) = 1 && c.(u) = 0 then 1 else 0) in
(*      let change = min ac0 ac1 in
      let (ac0, ac1) = (ac0 - change, ac1 - change) in *)
      ex.(0).(u) <- ac0;
      ex.(1).(u) <- ac1;
      (ac0, ac1)
    in
    let _ = dfs (-1) 0 in
    *)

    let rec dfs p u mincost =
    (* return (excess_ones, excess_zeros, cost) for this subtree *)
      let rec loop li ac0 ac1 ac_cost =
	match li with
	  | [] -> (ac0, ac1, ac_cost)
	  | v::tail ->
	    if v = p then loop tail ac0 ac1 ac_cost else
	      let (v0, v1, v_cost) = dfs u v (min mincost a.(v)) in
	      loop tail (ac0+v0) (ac1+v1) (ac_cost ++ v_cost)
      in
      let (ac0, ac1, ac_cost) = loop tree.(u) 0 0 0L in
      let ac0 = ac0 + (if b.(u) = 0 && c.(u) = 1 then 1 else 0) in
      let ac1 = ac1 + (if b.(u) = 1 && c.(u) = 0 then 1 else 0) in
      let change = min ac0 ac1 in
      let cost = ac_cost ++ 2L ** (long change) ** mincost in
      (ac0 - change, ac1 - change, cost)
    in

    let (_, _, cost) = dfs (-1) 0 a.(0) in
    printf "%Ld\n" cost
  )

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 long x = Int64.of_int x

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

let () =
  let n = read_int() in
  let a = Array.make n 0L in
  let b = Array.make n 0 in
  let c = Array.make n 0 in
  for i=0 to n-1 do
    a.(i) <- read_long ();
    b.(i) <- read_int ();
    c.(i) <- read_int ();
  done;

  let tree = Array.make n [] in

  for i=1 to n-1 do
    let (u,v) = read_pair() in
    let (u,v) = (u-1,v-1) in
    tree.(u) <- v::tree.(u);
    tree.(v) <- u::tree.(v)
  done;

  let rec dfs p u mincost =
    (* return (excess_ones, excess_zeros, cost) for this subtree *)
    let rec loop li ac0 ac1 ac_cost =
      match li with
	| [] -> (ac0, ac1, ac_cost)
	| v::tail ->
	  if v = p then loop tail ac0 ac1 ac_cost else
	    let (v0, v1, v_cost) = dfs u v (min mincost a.(v)) in
	    loop tail (ac0+v0) (ac1+v1) (ac_cost ++ v_cost)
    in
    let (ac0, ac1, ac_cost) = loop tree.(u) 0 0 0L in
    let ac0 = ac0 + (if b.(u) = 0 && c.(u) = 1 then 1 else 0) in
    let ac1 = ac1 + (if b.(u) = 1 && c.(u) = 0 then 1 else 0) in
    let change = min ac0 ac1 in
    let cost = ac_cost ++ 2L ** (long change) ** mincost in
    (ac0 - change, ac1 - change, cost)
  in

  let (c0, c1, cost) = dfs (-1) 0 a.(0) in
  printf "%Ld\n" (if c0 + c1 <> 0 then -1L else cost)


You've got a non-decreasing sequence x1, x2, ..., xn (1 ≤ x1 ≤ x2 ≤ ... ≤ xn ≤ q). You've also got two integers a and b (a ≤ b; a·(n - 1) < q).Your task is to transform sequence x1, x2, ..., xn into some sequence y1, y2, ..., yn (1 ≤ yi ≤ q; a ≤ yi + 1 - yi ≤ b). The transformation price is the following sum: . Your task is to choose such sequence y that minimizes the described transformation price.

The first line contains four integers n, q, a, b (2 ≤ n ≤ 6000; 1 ≤ q, a, b ≤ 109; a·(n - 1) < q; a ≤ b). The second line contains a non-decreasing integer sequence x1, x2, ..., xn (1 ≤ x1 ≤ x2 ≤ ... ≤ xn ≤ q).

In the first line print n real numbers — the sought sequence y1, y2, ..., yn (1 ≤ yi ≤ q; a ≤ yi + 1 - yi ≤ b). In the second line print the minimum transformation price, that is, . If there are multiple optimal answers you can print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.

(* It's a DP algorithm.  Keep y_opt.(i) which is the natural place
   where the point y.(i) will land when considering only points 0, 1,
   2... i.

   To compute y_opt.(i) we assume we have already computed the
   previous ones.  What we do now is see if y.(i) acting alone would
   be within the window defined by y_opt.(i-1).  If it is, we're done
   with y_opt.(i).  Say y.(i) is too high to be compatible with
   y_opt.(i-1).  Then we glue these two points together by asserting
   y.(i)-y.(i-1)=b.  (Analogously, if y.(i) is too low compared to
   y_opt.(i-1) we assert y.(i)-y.(i-1)=a instead.)  This pair of
   points has a natural position uninfluenced by anything outside of
   them.  If this position is compatible with y_opt.(i-2) then we're
   done, otherwise we add y.(i-2) to the chain and continue.  So the
   elements are chained together by a sequence of as and bs,
   intermixed.

   We can prove by induction that the solution that this finds is
   optimal.  The base case is when y.(i) is within the window allowed
   by y_opt.(i-1).  Clearly this is the right answer.  Now suppose
   that we have established that in the optimal solution some chain of
   differences relating y.(k),...,y.(i-2), y.(i) must occur.  This
   means that when searching for the optimal solution we need only
   consider these values moving in lockstep as specified by the chain.
   Looking at point k-1 if the chain is too low, then the optimal
   solution must also have y.(k-1) in the chain being a below y.(k),
   and if point k-1 is too high then it must be in the chain b below
   y.(i).  (The intuition is that of a spring.  If you move your
   finger toward a spring and you touch the spring, pushing harder on
   the spring will keep your finger in contact with the spring.  The
   spring will not suddenly pull away from your finger as you push
   harder.  The (x-y)^2 cost function ensures that this is the correct
   model.)

   So the algorithm is O(n^2).  It might be possible to work out a
   version of this algorithm that is O(n log n) by keeping the chains
   in a search tree.  Then instead of starting from scratch each time
   when adding a new point, it would edit the current chain.  It is
   not clear that this can be made to work.

               Danny Sleator <sleator@cs.cmu.edu>
*)

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) +. a) 0.0
let sq x = x *. x
let (++) (a,b,c) (d,e,f) = (a+.d, b+.e, c+.f)

let quad_min (a,b,c) = -. (b /. (2.0 *. a))
  (* ax^2 + bx + c is our quadratic.  Return the value of x that minimizes it *)
  (* a cannot be zero *)

let () =
  let n = read_int 0 in
  let q0 = read_float 0 in
  let a0 = read_float 0 in
  let b0 = read_float 0 in

  let x = Array.init n read_float in
  let y_opt = Array.copy x in
  let chain = Array.make n 0.0 in

  let bound h v = max (1.0+.h) (min q0 v) in

  let rec pull_chain j h q = if j<0 then (bound h (quad_min q), j) else
    (* Set the group of points j+1, j+2, ... i all to differ by cumulative h
       the quadratic represented by this group is q. *)
    let yi_nat = bound h (quad_min q) in
      if y_opt.(j) < yi_nat -. h -. b0 then
	let ny = x.(j) +. h +. b0 in
	  chain.(j) <- b0;
	  pull_chain (j-1) (h+.b0) (q ++ (1.0, -2.0 *. ny, sq ny))
      else if y_opt.(j) > yi_nat -. h -. a0 then
	let ny = x.(j) +. h +. a0 in
	  chain.(j) <- a0;
	  pull_chain (j-1) (h+.a0) (q ++ (1.0, -2.0 *. ny, sq ny))
      else
	(yi_nat, j)
  in

    for i=1 to n-1 do
      let myq = (1.0, -2.0*.x.(i), sq x.(i)) in
      let (yopt, j) = pull_chain (i-1) 0.0 myq in
	y_opt.(i) <- yopt;
    done;

    let rec fill_in_y i = if i<0 then () else
      let (_, j) = pull_chain (i-1) 0.0 (1.0, -2.0*.x.(i), sq x.(i)) in
	for k=i-1 downto j+1 do
	  y_opt.(k) <- y_opt.(k+1) -. chain.(k);
	done;
	fill_in_y j
    in
      fill_in_y (n-1);

      let total = sum 0 (n-1) (fun i-> sq (y_opt.(i) -. x.(i))) in

	for i=0 to n-1 do
	  Printf.printf "%.8f " y_opt.(i);
	done;
	print_newline();
	Printf.printf "%.8f\n" total;

(* It's a DP algorithm.  Keep y_opt.(i) which is the natural place
   where the point y.(i) will land when considering only points 0, 1,
   2... i.

   To compute y_opt.(i) we assume we have already computed the
   previous ones.  What we do now is see if y.(i) acting alone would
   be within the window defined by y_opt.(i-1).  If it is, we're done
   with y_opt.(i).  Say y.(i) is too high to be compatible with
   y_opt.(i-1).  Then we glue fix y.(i-1)=y.(i)-b and compute the
   natural position for this pair of points using the sum of their
   potentials.  If this is compatible with y_opt.(i-2) then we're
   done, otherwise we add that to the group and continue.  The chain
   can consist of a sequence of as and bs, intermixed.

   So the algorithm is O(n^2).  It could be optimized as follows.
   Remember how far back the block went and continuing from where we
   left off computing y_opt.(i).  So if y.(i+1) also is pulling up we
   can continue from where we left off.  Can this be turned into an
   O(n) algorithm?
*)

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

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

let sq x = x *. x

let (++) (a,b,c) (d,e,f) = (a+.d, b+.e, c+.f)

let quad_min (a,b,c) =
  (* ax^2 + bx + c is our quadratic.  Return the value of x that minimizes it *)
  (* a cannot be zero *)
  -. (b /. (2.0 *. a))

let quad_eval (a,b,c) x = a *. (sq x) +. b *. x +. c

let () =
  let n = read_int 0 in
  let q0 = read_float 0 in
  let a0 = read_float 0 in
  let b0 = read_float 0 in

  let x = Array.init n read_float in
  let y_opt = Array.copy x in
  let chain = Array.make n 0.0 in
  let jarray = Array.make n (-1) in

  let bound h v = max (1.0+.h) (min q0 v) in

  let rec pull_chain j h q = if j<0 then (bound h (quad_min q), j) else
    (* set the group of points j+1, j+2, ... i all to differ by cumulative h
       the quadratic represented by this group is q. Find its natural position. *)
    let yi_nat = bound h (quad_min q) in
      if y_opt.(j) < yi_nat -. h -. b0 then
	let ny = x.(j) +. h +. b0 in
	  chain.(j) <- b0;
	  pull_chain (j-1) (h+.b0) (q ++ (1.0, -2.0 *. ny, sq ny))
      else if y_opt.(j) > yi_nat -. h -. a0 then
	let ny = x.(j) +. h +. a0 in
	  chain.(j) <- a0;
	  pull_chain (j-1) (h+.a0) (q ++ (1.0, -2.0 *. ny, sq ny))
      else
	(yi_nat, j)
  in

    for i=1 to n-1 do
      let myq = (1.0, -2.0*.x.(i), sq x.(i)) in
      let (yopt, j) = pull_chain (i-1) 0.0 myq in
	y_opt.(i) <- yopt;
	jarray.(i) <- j;
    done;

    let rec fill_in_y i = if i<0 then () else
      let myq = (1.0, -2.0*.x.(i), sq x.(i)) in
      let (_, j) = pull_chain (i-1) 0.0 myq in
      let rec loop k = if k<=j then () else
	let delta = chain.(k) in
	  y_opt.(k) <- y_opt.(k+1) -. delta;
	  loop (k-1)
      in
	loop (i-1);
	fill_in_y j
    in

      fill_in_y (n-1);

      let total = sum 0 (n-1) (fun i-> sq (y_opt.(i) -. x.(i))) in

	for i=0 to n-1 do
	  Printf.printf "%.8f " y_opt.(i);
	done;
	print_newline();
	Printf.printf "%.8f\n" total;

(* It's a DP algorithm.  Keep y_opt.(i) which is the natural place
   where the point y.(i) will land when considering only points 0, 1,
   2... i.

   To compute y_opt.(i) we assume we have already computed the
   previous ones.  What we do now is see if y.(i) acting alone would
   be within the window defined by y_opt.(i-1).  If it is, we're done
   with y_opt.(i).  Say y.(i) is too high to be compatible with
   y_opt.(i-1).  Then we glue these two points together by asserting
   y.(i)-y.(i-1)=b.  (Analogously, if y.(i) is too low compared to
   y_opt.(i-1) we assert y.(i)-y.(i-1)=a instead.)  This pair of
   points has a natural position uninfluenced by anything outside of
   them.  If this position is compatible with y_opt.(i-2) then we're
   done, otherwise we add y.(i-2) to the chain and continue.  So the
   elements are chained together by a sequence of as and bs,
   intermixed.

   We can prove by induction that the solution that this finds is
   optimal.  The base case is when y.(i) is within the window allowed
   by y_opt.(i-1).  Clearly this is the right answer.  Now suppose
   that we have established that in the optimal solution some chain of
   differences relating y.(k),...,y.(i-2), y.(i) must occur.  This
   means that when searching for the optimal solution we need only
   consider these values moving in lockstep as specified by the chain.
   Looking at point k-1 if the chain is too low, then the optimal
   solution must also have y.(k-1) in the chain being a below y.(k),
   and if point k-1 is too high then it must be in the chain b below
   y.(i).  (The intuition is that of a spring.  If you move your
   finger toward a spring and you touch the spring, pushing harder on
   the spring will keep your finger in contact with the spring.  The
   spring will not suddenly pull away from your finger as you push
   harder.  The (x-y)^2 cost function ensures that this is the correct
   model.)

   So the algorithm is O(n^2).  It might be possible to work out a
   version of this algorithm that is O(n log n) by keeping the chains
   in a search tree.  Then instead of starting from scratch each time
   when adding a new point, it would edit the current chain.  It is
   not clear that this can be made to work.

               Danny Sleator <sleator@cs.cmu.edu>
*)

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) +. a) 0.0
let sq x = x *. x
let (++) (a,b,c) (d,e,f) = (a+.d, b+.e, c+.f)

let quad_min (a,b,c) = -. (b /. (2.0 *. a))
  (* ax^2 + bx + c is our quadratic.  Return the value of x that minimizes it *)
  (* a cannot be zero *)

let () =
  let n = read_int 0 in
  let q0 = read_float 0 in
  let a0 = read_float 0 in
  let b0 = read_float 0 in

  let x = Array.init n read_float in
  let y_opt = Array.copy x in
  let chain = Array.make n 0.0 in

  let bound h v = max (1.0+.h) (min q0 v) in

  let rec pull_chain j h q = if j<0 then (bound h (quad_min q), j) else
    (* Set the group of points j+1, j+2, ... i all to differ by cumulative h
       the quadratic represented by this group is q. *)
    let yi_nat = bound h (quad_min q) in
      if y_opt.(j) < yi_nat -. h -. b0 then
	let ny = x.(j) +. h +. b0 in
	  chain.(j) <- b0;
	  pull_chain (j-1) (h+.b0) (q ++ (1.0, -2.0 *. ny, sq ny))
      else if y_opt.(j) > yi_nat -. h -. a0 then
	let ny = x.(j) +. h +. a0 in
	  chain.(j) <- a0;
	  pull_chain (j-1) (h+.a0) (q ++ (1.0, -2.0 *. ny, sq ny))
      else
	(yi_nat, j)
  in

    for i=1 to n-1 do
      let myq = (1.0, -2.0*.x.(i), sq x.(i)) in
      let (yopt, j) = pull_chain (i-1) 0.0 myq in
	y_opt.(i) <- yopt;
    done;

    let rec fill_in_y i = if i<0 then () else
      let (_, j) = pull_chain (i-1) 0.0 (1.0, -2.0*.x.(i), sq x.(i)) in
	for k=i-1 downto j+1 do
	  y_opt.(k) <- y_opt.(k+1) -. chain.(k);
	done;
	fill_in_y j
    in
      fill_in_y (n-1);

      let total = sum 0 (n-1) (fun i-> sq (y_opt.(i) -. x.(i))) in

	for i=0 to n-1 do
	  Printf.printf "%.8f " y_opt.(i);
	done;
	Printf.printf "%.8f\n" total;


Bash got tired on his journey to become the greatest Pokemon master. So he decides to take a break and play with functions.Bash defines a function f0(n), which denotes the number of ways of factoring n into two factors p and q such that gcd(p, q) = 1. In other words, f0(n) is the number of ordered pairs of positive integers (p, q) such that p·q = n and gcd(p, q) = 1.But Bash felt that it was too easy to calculate this function. So he defined a series of functions, where fr + 1 is defined as:Where (u, v) is any ordered pair of positive integers, they need not to be co-prime.Now Bash wants to know the value of fr(n) for different r and n. Since the value could be huge, he would like to know the value modulo 109 + 7. Help him!

The first line contains an integer q (1 ≤ q ≤ 106) — the number of values Bash wants to know. Each of the next q lines contain two integers r and n (0 ≤ r ≤ 106, 1 ≤ n ≤ 106), which denote Bash wants to know the value fr(n).

Print q integers. For each pair of r and n given, print fr(n) modulo 109 + 7 on a separate line.

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

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

let _ =
  let m = 2000000 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 n2 = 1000000 in
  let prime = Array.make (n2 + 1) true in
  let p = Array.make (n2 + 1) 0 in
  let pd = Array.init (n2 + 1) (fun i -> i) in
  let pk = ref 0 in
  let () =
    for i = 2 to n2 do
      if prime.(i) then (
	p.(!pk) <- i;
	incr pk;
	pd.(i) <- i;
	let j = ref (2 * i) in
          while !j <= n2 do
	    let jj = !j in
              prime.(jj) <- false;
	      pd.(jj) <- i;
              j := jj + i
          done
      )
    done;
    prime.(1) <- false;
  in
  let pk = !pk - 1 in
  let fp = Array.make 20 0 in
  let fd = Array.make 20 0 in
  let factor x =
    let r = ref 0 in
    let x = ref x in
      while !x > 1 && not (pd.(!x) = !x) do
	let pr = pd.(!x) in
	  let d = ref 0 in
	    while !x mod pr = 0 do
	      incr d;
	      x := !x / pr;
	    done;
	    fp.(!r) <- pr;
	    fd.(!r) <- !d;
	    incr r;
      done;
      if !x > 1 then (
	fp.(!r) <- !x;
	fd.(!r) <- 1;
	incr r;
      );
      !r
  in
  let min (x : int) y = if x < y then x else y in
  let q = getnum () in
    for _ca = 1 to q do
      let r = getnum () in
      let n = getnum () in
      let t = factor n in
      let res = ref 1L in
	for i = 0 to t - 1 do
	  let x = fd.(i) in
	    res := mmod (!res *| Int64.of_int fact.(x + r - 1));
	    res := mmod (!res *| Int64.of_int ifact.(r));
	    res := mmod (!res *| Int64.of_int ifact.(x));
	    res := mmod (!res *| Int64.of_int (2 * x + r));
	    (*Printf.printf "qwe %d %Ld\n" x !res;*)
	done;
	Printf.printf "%Ld\n" !res;
    done;


Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions.  Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs bi manapoints and changes the preparation time of each potion to ai instead of x.  Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs di manapoints and instantly create ci potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.

The first line of the input contains three integers n, m, k (1 ≤ n ≤ 2·109, 1 ≤ m, k ≤ 2·105) — the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type. The second line of the input contains two integers x and s (2 ≤ x ≤ 2·109, 1 ≤ s ≤ 2·109) — the initial number of seconds required to prepare one potion and the number of manapoints Anton can use. The third line contains m integers ai (1 ≤ ai < x) — the number of seconds it will take to prepare one potion if the i-th spell of the first type is used. The fourth line contains m integers bi (1 ≤ bi ≤ 2·109) — the number of manapoints to use the i-th spell of the first type. There are k integers ci (1 ≤ ci ≤ n) in the fifth line — the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that ci are not decreasing, i.e. ci ≤ cj if i < j. The sixth line contains k integers di (1 ≤ di ≤ 2·109) — the number of manapoints required to use the i-th spell of the second type. It's guaranteed that di are not decreasing, i.e. di ≤ dj if i < j.

Print one integer — the minimum time one has to spent in order to prepare n potions.

NoteIn the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10 + 80 = 90, and the preparation time is 4·5 = 20 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each).In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20·10 = 200.

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

let find_best d s =
  let rec aux l r =
    match r - l with
    | 0 -> None
    | 1 -> if d.(l) <= s then Some l else None
    | h ->
      let mid = l + h / 2 in
      if d.(mid) > s then
        aux l mid
      else
        aux mid r
  in aux 0 (Array.length d)

let solve n m k x s a b c d =
  let best_time = ref (
      let open Int64 in
      match find_best d s with
      | None -> n * x
      | Some j -> (n - c.(j)) * x
    ) in
  for i = 0 to m - 1 do
    let seconds = a.(i) in
    let cost = b.(i) in
    if cost <= s then
      let time =
        let open Int64 in
        match find_best d (s - cost) with
        | None -> n * seconds
        | Some j -> (n - c.(j)) * seconds in
      best_time := min !best_time time
  done;
  !best_time

let () =
  Scanf.scanf "%Ld %d %d %Ld %Ld " @@ fun n m k x s ->
  let a = Array.init m (fun _ -> Scanf.scanf "%Ld " (fun x -> x)) in
  let b = Array.init m (fun _ -> Scanf.scanf "%Ld " (fun x -> x)) in
  let c = Array.init k (fun _ -> Scanf.scanf "%Ld " (fun x -> x)) in
  let d = Array.init k (fun _ -> Scanf.scanf "%Ld " (fun x -> x)) in
  solve n m k x s a b c d |> Printf.printf "%Ld\n"

let find_best d s =
  let rec aux l r =
    match r - l with
    | 0 -> None
    | 1 -> if d.(l) <= s then Some l else None
    | h ->
      let mid = l + h / 2 in
      if d.(mid) > s then
        aux l mid
      else
        aux mid r
  in aux 0 (Array.length d)

let solve n m k x s a b c d =
  let best_time = ref (
      match find_best d s with
      | None -> n * x
      | Some j -> (n - c.(j)) * x
    ) in
  for i = 0 to m - 1 do
    let seconds = a.(i) in
    let cost = b.(i) in
    if cost <= s then
      let time =
        match find_best d (s - cost) with
        | None -> n * seconds
        | Some j -> (n - c.(j)) * seconds in
      best_time := min !best_time time
  done;
  !best_time

let () =
  Scanf.scanf "%d %d %d %d %d " @@ fun n m k x s ->
  let a = Array.init m (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let b = Array.init m (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let c = Array.init k (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let d = Array.init k (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  solve n m k x s a b c d |> Printf.printf "%d\n"


Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.

let first_sup w n =
   let x = ref @@ -1 in
      for i = n - 1 downto (String.index w '.') + 1 do
         if w.[i] > '4' && w.[i] <= '9' then x := i
      done;
      !x

let incr_w w =
   let f_d = String.index w '.' in
   let x = ref true in
      for i = f_d - 1 downto 0 do
         if !x
         then (if w.[i] = '9'
               then w.[i] <- '0'
               else (w.[i] <- char_of_int (1 + int_of_char w.[i]);
                     x := false)
              )
      done;
   (if !x then "1" else "") ^ (String.sub w 0 f_d)

let wo_trail w =
   let n = String.length w in
   let len = ref n and flg = ref true in
      while !flg && w.[!len - 1] = '0' do decr len done;
      String.sub w 0 !len

let rec f f_d i w t =
   if i = -1 || t = 0
      then wo_trail w
   else if i = f_d + 1
      then incr_w w
   else (w.[i] <- '0';
         w.[i-1] <- char_of_int (1 + int_of_char w.[i-1]);
         if w.[i-1] = '5' then f f_d (i-1) w (t-1) else wo_trail w
        )

let _ =
    let (n,t,w) = Scanf.scanf "%d %d %s" (fun n t w -> (n, t, w)) in
    let f_i = first_sup w n in
    let f_d = String.index w '.' in
       if f_i >= 0 then for i = f_i + 1 to String.length w - 1 do w.[i] <- '0'; done;
       print_endline @@ (f f_d f_i w t)

let first_sup w n =
   let x = ref @@ -1 in
      for i = n - 1 downto (String.index w '.') + 1 do
         if w.[i] > '4' && w.[i] <= '9' then x := i
      done;
      !x

let incr_w w =
   let f_d = String.index w '.' in
   let x = ref true in
      for i = f_d - 1 downto 0 do
         if !x
         then (if w.[i] = '9'
               then w.[i] <- '0'
               else (w.[i] <- char_of_int (1 + int_of_char w.[i]);
                     x := false)
              )
      done;
   (if !x then "1" else "") ^ (String.sub w 0 f_d)

let wo_trail w =
   let n = String.length w in
   let len = ref n and flg = ref true in
      while !flg && w.[!len - 1] = '0' do decr len done;
      String.sub w 0 !len

let rec f f_d i w t =
   if i = -1 || t = 0
      then wo_trail w
   else if i = f_d + 1
      then incr_w w
   else (w.[i] <- '0';
         w.[i-1] <- char_of_int (1 + int_of_char w.[i-1]);
         if w.[i-1] = '5' then f f_d (i-1) w (t-1) else w
        )

let _ =
    let (n,t,w) = Scanf.scanf "%d %d %s" (fun n t w -> (n, t, w)) in
    let f_i = first_sup w n in
    let f_d = String.index w '.' in
       if f_i >= 0 then for i = f_i + 1 to String.length w - 1 do w.[i] <- '0'; done;
       print_endline @@ (f f_d f_i w t)


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

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

let x =get_i64 0 let a = input_i64_array x
let () =
	Array.sort compare a;
	let l = Array.to_list a in
	let h = List.hd l in let t = List.tl l in
	List.fold_left (fun (u,c) v ->
		if v <> u + 1L then (v,c+v-u-1L) else (v,c)
	) (h,0L) t
	|> snd |> printf "%Ld\n"

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

let x =get_i64 0 let a = input_i64_array x
let () =
	Array.sort compare a;
	let l = Array.to_list a in
	let h = List.hd l in let t = List.tl l in
	List.fold_left (fun (u,c) v ->
		if v <> u + 1L then (v,c+1L) else (v,c)
	) (h,0L) t
	|> snd |> printf "%Ld\n"


Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers $$$a_1,a_2,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.For each $$$i$$$ ($$$1\le i\le n$$$), you're asked to choose a $$$j$$$ ($$$1\le j\le m$$$) and let $$$c_i=a_i\& b_j$$$, where $$$\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).

Print one integer: the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$.

open Printf
open Scanf

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

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

let () =
  let n = read_int() in
  let m = read_int() in
  let a = Array.init n read_int in
  let b = Array.init m read_int in

  let rec solve mask remain = if remain = 0 then mask else (

    let rec find_bit i = if i=n then 0 else (
    (* finds the (remain-1) bit of the new mask *)
      if exists 0 (m-1) (fun j ->
	let c = a.(i) land b.(j) in
	(c land (lnot mask) = 0) && (c land (1 lsl (remain-1)) = 0)
	(* this j works with this i *)
      ) then
	find_bit (i+1) else 1
    ) in

    let mask' = if find_bit 0 = 1 then mask else mask land (lnot (1 lsl (remain-1))) in
    solve mask' (remain-1)
  ) in

  let answer = solve ((1 lsl 30)-1) 30 in

  printf "%d\n" answer


Let's call a positive integer $$$n$$$ ordinary if in the decimal notation all its digits are the same. For example, $$$1$$$, $$$2$$$ and $$$99$$$ are ordinary numbers, but $$$719$$$ and $$$2021$$$ are not ordinary numbers.For a given number $$$n$$$, find the number of ordinary numbers among the numbers from $$$1$$$ to $$$n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case is characterized by one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case output the number of ordinary numbers among numbers from $$$1$$$ to $$$n$$$.

module Stdlib = Pervasives

let std_inp = Stdlib.stdin;;
let std_outp = Stdlib.stdout;;

(* let std_inp = Stdlib.open_in "input.txt";; *)

let identity x = x;;
let tup2 x1 x2 = (x1, x2);;

let min a b = if a < b then a else b;;

let rec repeat n (f, state, inp, outp) =
  if n = 0 then state
  else
    let state = f state inp outp in
    repeat (n - 1) (f, state, inp, outp);;

let space_regexp = Str.regexp " ";;

type triplet = Never | Maybe | Guaranteed;;

exception Unreachable_by_statement of unit
let solution _state inp outp =
  let rec digits x acc =
    if x = 0 then acc
    else digits (x / 10) ((x mod 10)::acc)
  in
  let folder (prev_digit, len, regularity_state) element =
    let last_digit = element mod 10 in
    if regularity_state != Maybe then (last_digit, len + 1, regularity_state)
    else
      if last_digit > prev_digit then (last_digit, len + 1, Guaranteed)
      else if last_digit = prev_digit then (last_digit, len + 1, Maybe)
      else (last_digit, len + 1, Never)
  in
  let x = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let (first_digit, digits_tail) =
    match (digits x []) with
    | [] -> raise @@ Unreachable_by_statement ()
    | (head::tail)-> (head, tail)
  in
  (* let () = List.map string_of_int digs |> String.concat " " |> Printf.fprintf outp "%s\n" in *)
  let (_, len, regularity_state) = List.fold_left folder (first_digit, 1, Maybe) digits_tail in
  let result =
    let result_base = (len - 1) * 9 + first_digit - 1 in
    match regularity_state with
    | Guaranteed | Maybe -> result_base + 1
    | Never -> result_base
  in
  let () = Printf.fprintf outp "%d\n" result in
  ();;

let () =
  let inp = std_inp and outp = std_outp in
  let tests_count = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let _state = repeat tests_count (solution, (), inp, outp) in
  ();;

module Stdlib = Pervasives

let std_inp = Stdlib.stdin;;
let std_outp = Stdlib.stdout;;

(* let std_inp = Stdlib.open_in "input.txt";; *)

let identity x = x;;
let tup2 x1 x2 = (x1, x2);;

let min a b = if a < b then a else b;;

let rec repeat n (f, state, inp, outp) =
  if n = 0 then state
  else
    let state = f state inp outp in
    repeat (n - 1) (f, state, inp, outp);;

let space_regexp = Str.regexp " ";;

let solution _state inp outp =
  let rec reduce x (last_dig, len, min_digit) =
    if x = 0 then (last_dig, len, min_digit)
    else
      let new_last_dig = x mod 10 in
      reduce (x / 10) (new_last_dig, len + 1, min min_digit new_last_dig)
  in
  let x = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let (last_dig, len, min_dig) = reduce x (x mod 10, 0, 10) in
  let result = (len - 1) * 9 + last_dig - (if min_dig = last_dig then 0 else 1) in
  let () = Printf.fprintf outp "%d\n" result in
  ();;

let () =
  let inp = std_inp and outp = std_outp in
  let tests_count = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let _state = repeat tests_count (solution, (), inp, outp) in
  ();;

module Stdlib = Pervasives

let std_inp = Stdlib.stdin;;
let std_outp = Stdlib.stdout;;

(* let std_inp = Stdlib.open_in "input.txt";; *)

let identity x = x;;
let tup2 x1 x2 = (x1, x2);;

let min a b = if a < b then a else b;;

let rec repeat n (f, state, inp, outp) =
  if n = 0 then state
  else
    let state = f state inp outp in
    repeat (n - 1) (f, state, inp, outp);;

let space_regexp = Str.regexp " ";;

let solution _state inp outp =
  let rec reduce x (last_dig, len, regular) =
    if x = 0 then (last_dig, len, regular)
    else
      let new_last_dig = x mod 10 in
      reduce (x / 10) (new_last_dig, len + 1, regular && (new_last_dig = last_dig))
  in
  let x = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let (last_dig, len, regular) = reduce x (x mod 10, 0, true) in
  let result = (len - 1) * 9 + last_dig - (if regular then 0 else 1) in
  let () = Printf.fprintf outp "%d\n" result in
  ();;

let () =
  let inp = std_inp and outp = std_outp in
  let tests_count = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let _state = repeat tests_count (solution, (), inp, outp) in
  ();;

module Stdlib = Pervasives

let std_inp = Stdlib.stdin;;
let std_outp = Stdlib.stdout;;

(* let std_inp = Stdlib.open_in "input.txt";; *)

let identity x = x;;
let tup2 x1 x2 = (x1, x2);;

let min a b = if a < b then a else b;;

let rec repeat n (f, state, inp, outp) =
  if n = 0 then state
  else
    let state = f state inp outp in
    repeat (n - 1) (f, state, inp, outp);;

let space_regexp = Str.regexp " ";;

let solution _state inp outp =
  let rec reduce x (min_dig, len) =
    if x = 0 then (min_dig, len)
    else
      let last_dig = x mod 10 in
      reduce (x / 10) (min min_dig last_dig, len + 1)
  in
  let x = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let (min_dig, len) = reduce x (10, 0) in
  let result = (len - 1) * 9 + min_dig in
  let () = Printf.fprintf outp "%d\n" result in
  ();;

let () =
  let inp = std_inp and outp = std_outp in
  let tests_count = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let _state = repeat tests_count (solution, (), inp, outp) in
  ();;