Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.

The first line of the input contains a single integer n (1 ≤ n ≤ 500 000) — the number of hashtags being edited now. Each of the next n lines contains exactly one hashtag of positive length. It is guaranteed that the total length of all hashtags (i.e. the total length of the string except for characters '#') won't exceed 500 000.

Print the resulting hashtags in any of the optimal solutions.

NoteWord a1, a2, ..., am of length m is lexicographically not greater than word b1, b2, ..., bk of length k, if one of two conditions hold:   at first position i, such that ai ≠ bi, the character ai goes earlier in the alphabet than character bi, i.e. a has smaller character than b in the first position where they differ;  if there is no such position i and m ≤ k, i.e. the first word is a prefix of the second or two words are equal. The sequence of words is said to be sorted in lexicographical order if each word (except the last one) is lexicographically not greater than the next word.For the words consisting of lowercase English letters the lexicographical order coincides with the alphabet word order in the dictionary.According to the above definition, if a hashtag consisting of one character '#' it is lexicographically not greater than any other valid hashtag. That's why in the third sample we can't keep first two hashtags unchanged and shorten the other two.

let print_array a =
	let n = Array.length a in
	for k = 0 to n - 1 do
		print_endline a.(k);
	done;
;;

let read_array n =
	let arr = Array.make n "" in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %s" (fun v -> arr.(k) <- v;);
		done;
		arr
	end
;;

let longest_common_prefix_length l r =
	let n = min (String.length l) (String.length r) in
	let k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)
	begin
		while (!k < n) && ((String.get l !k) = (String.get r !k) ) do
			k := !k + 1;
		done;
		!k
	end
;;

let max_lex_predecessor l r =
	let nl = String.length l in
	let nr = String.length r in
	let m = longest_common_prefix_length l r in
	if (m = nl) || ((m < nr) && (String.get l m) < (String.get r m)) then l
	else (String.sub l 0 m)
;;

let truncate_hashtags a =
	let n = Array.length a in
	let b = Array.make n "" in
	begin
		b.(n-1) <- a.(n-1);
		for k=(n-2) downto 0 do
			b.(k) <- (max_lex_predecessor a.(k) b.(k+1));
		done;
		b
	end
;;

let load_and_process_hashtags n =
	let a = read_array n in
	let b = truncate_hashtags a in
	print_array b
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i " load_and_process_hashtags
;;

read_input ()

let print_array a =
	let n = Array.length a in
	for k = 0 to n - 1 do
		print_endline a.(k);
	done;
;;

let read_array n =
	let arr = Array.make n "" in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %s" (fun v -> arr.(k) <- v;);
		done;
		arr
	end
;;

let longest_common_prefix_length l r =
	let n = min (String.length l) (String.length r) in
	let k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)
	begin
		while (!k < n) && ((String.get l !k) = (String.get r !k) ) do
			k := !k + 1;
		done;
		!k
	end
;;

let max_lex_predecessor_length l r =
	let nl = String.length l in
	let nr = String.length r in
	let m = longest_common_prefix_length l r in
	if (m = nl) || (m = nr) then m
	else if (String.get l m) < (String.get r m) then nl
	else m
;;

let max_lex_predecessor l r =
	let nl = String.length l in
	let m = max_lex_predecessor_length l r in
	if m = nl then l else (String.sub l 0 m)
;;

let truncate_hashtags a =
	let n = Array.length a in
	let b = Array.make n "" in
	begin
		b.(n-1) <- a.(n-1);
		for k=(n-2) downto 0 do
			b.(k) <- (max_lex_predecessor a.(k) b.(k+1));
		done;
		b
	end
;;

let load_and_process_hashtags n =
	let a = read_array n in
	let b = truncate_hashtags a in
	print_array b
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i " load_and_process_hashtags
;;

read_input ()

let print_array a =
	let n = Array.length a in
	for k = 0 to n - 1 do
		print_endline a.(k);
	done;
;;

let read_array n =
	let arr = Array.make n "" in
	let last_v = ref "" in
	begin
		for k = 0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %s" (fun v ->
				begin
					arr.(k) <- if v = !last_v then !last_v else v;
					last_v := v;
				end
			);
		done;
		arr
	end
;;

let longest_common_prefix_length l r =
	let n = min (String.length l) (String.length r) in
	let k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)
	begin
		while (!k < n) && ((String.get l !k) = (String.get r !k) ) do
			k := !k + 1;
		done;
		!k
	end
;;

let truncate_hashtags a =
	let n = Array.length a in
	begin
		for k=(n-2) downto 0 do
			let l = a.(k) in
			let r = a.(k+1) in
			if (l != r) && (String.compare l r) >= 1 then
			begin
				a.(k) <- (String.sub l 0 (longest_common_prefix_length l r));
			end;
		done;
		a
	end
;;

let load_and_process_hashtags n =
	let a = read_array n in
	let b = truncate_hashtags a in
	print_array b
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i " load_and_process_hashtags
;;

read_input ()

let print_array a =
	let n = Array.length a in
	for k = 0 to n - 1 do
		print_endline a.(k);
	done;
;;

let read_array n =
	let arr = Array.make n "" in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %s" (fun v -> arr.(k) <- v;);
		done;
		arr
	end
;;

let longest_common_prefix_length l r =
	let n = min (String.length l) (String.length r) in
	let k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)
	begin
		while (!k < n) && ((String.get l !k) = (String.get r !k) ) do
			k := !k + 1;
		done;
		!k
	end
;;

let max_lex_predecessor_length l r =
	let nl = String.length l in
	let nr = String.length r in
	let m = longest_common_prefix_length l r in
	if (m = nl) || (m = nr) then m
	else if (String.get l m) < (String.get r m) then nl
	else m
;;

let max_lex_predecessor l r =
	let m = max_lex_predecessor_length l r in
	String.sub l 0 m
;;

let truncate_hashtags a =
	let n = Array.length a in
	let b = Array.make n "" in
	begin
		b.(n-1) <- a.(n-1);
		for k=(n-2) downto 0 do
			b.(k) <- (max_lex_predecessor a.(k) b.(k+1));
		done;
		b
	end
;;

let load_and_process_hashtags n =
	let a = read_array n in
	let b = truncate_hashtags a in
	print_array b
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i " load_and_process_hashtags
;;

read_input ()

let print_array a =
	let n = Array.length a in
	for k = 0 to n - 1 do
		print_endline a.(k);
	done;
;;

let read_array n =
	let arr = Array.make n "" in
	begin
		for k = 0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %s" (fun v -> arr.(k) <- v;);
		done;
		arr
	end
;;

let longest_common_prefix_length l r =
	let n = min (String.length l) (String.length r) in
	let k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)
	begin
		while (!k < n) && ((String.get l !k) = (String.get r !k) ) do
			k := !k + 1;
		done;
		!k
	end
;;

let max_lex_predecessor l r =
	let nl = String.length l in
	let nr = String.length r in
	let m = longest_common_prefix_length l r in
	if (m = nl) || ((m < nr) && (String.get l m) < (String.get r m)) then l
	else (String.sub l 0 m)
;;

let truncate_hashtags a =
	let n = Array.length a in
	begin
		for k=(n-2) downto 0 do
			a.(k) <- (max_lex_predecessor a.(k) a.(k+1));
		done;
		a
	end
;;

let load_and_process_hashtags n =
	let a = read_array n in
	let b = truncate_hashtags a in
	print_array b
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i " load_and_process_hashtags
;;

read_input ()

let print_array a =
	let n = Array.length a in
	for k = 0 to n - 1 do
		print_endline a.(k);
	done;
;;

let read_array n =
	let arr = Array.make n "" in
	begin
		for k = 0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %s" (fun v -> arr.(k) <- v;);
		done;
		arr
	end
;;

let longest_common_prefix_length l r =
	let n = min (String.length l) (String.length r) in
	let k = ref 1 in (* little optimization - we know that under index 0 we always have a hash-sign '#' *)
	begin
		while (!k < n) && ((String.get l !k) = (String.get r !k) ) do
			k := !k + 1;
		done;
		!k
	end
;;

let truncate_hashtags a =
	let n = Array.length a in
	begin
		for k=(n-2) downto 0 do
			let l = a.(k) in
			let r = a.(k+1) in
			if (String.compare l r) >= 1 then
			begin
				a.(k) <- (String.sub l 0 (longest_common_prefix_length l r));
			end
		done;
		a
	end
;;

let load_and_process_hashtags n =
	let a = read_array n in
	let b = truncate_hashtags a in
	print_array b
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i " load_and_process_hashtags
;;

read_input ()


Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.

The first line contains integer q (1 ≤ q ≤ 1000), the number of handle change requests. Next q lines contain the descriptions of the requests, one per line. Each query consists of two non-empty strings old and new, separated by a space. The strings consist of lowercase and uppercase Latin letters and digits. Strings old and new are distinct. The lengths of the strings do not exceed 20. The requests are given chronologically. In other words, by the moment of a query there is a single person with handle old, and handle new is not used and has not been used by anyone.

In the first line output the integer n — the number of users that changed their handles at least once. In the next n lines print the mapping between the old and the new handles of the users. Each of them must contain two strings, old and new, separated by a space, meaning that before the user had handle old, and after all the requests are completed, his handle is new. You may output lines in any order. Each user who changes the handle must occur exactly once in this description.

5
Misha ILoveCodeforces
Vasya Petrov
Petrov VasyaPetrov123
ILoveCodeforces MikeMirzayanov
Petya Ivanov

3
Petya Ivanov
Misha MikeMirzayanov
Vasya VasyaPetrov123

let () = Scanf.scanf "%d\n" (fun n ->
  let fwd = Hashtbl.create n in
  let rev = Hashtbl.create n in
  for i = 1 to n do
    Scanf.scanf "%[^ ] %s\n" (fun o n ->
      if Hashtbl.mem rev o then begin
        let s = Hashtbl.find rev o in
        Hashtbl.add rev n s;
        Hashtbl.remove rev o;
        Hashtbl.replace fwd s n
      end else begin
        Hashtbl.add fwd o n;
        Hashtbl.add rev n o
      end
    )
  done;
  Printf.printf "%d\n" (Hashtbl.length fwd);
  Hashtbl.iter (Printf.printf "%s %s\n") fwd
)


Inaka has a disc, the circumference of which is $$$n$$$ units. The circumference is equally divided by $$$n$$$ points numbered clockwise from $$$1$$$ to $$$n$$$, such that points $$$i$$$ and $$$i + 1$$$ ($$$1 \leq i < n$$$) are adjacent, and so are points $$$n$$$ and $$$1$$$.There are $$$m$$$ straight segments on the disc, the endpoints of which are all among the aforementioned $$$n$$$ points.Inaka wants to know if her image is rotationally symmetrical, i.e. if there is an integer $$$k$$$ ($$$1 \leq k < n$$$), such that if all segments are rotated clockwise around the center of the circle by $$$k$$$ units, the new image will be the same as the original one.

The first line contains two space-separated integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 100\,000$$$, $$$1 \leq m \leq 200\,000$$$) — the number of points and the number of segments, respectively. The $$$i$$$-th of the following $$$m$$$ lines contains two space-separated integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) that describe a segment connecting points $$$a_i$$$ and $$$b_i$$$. It is guaranteed that no segments coincide.

Output one line — "Yes" if the image is rotationally symmetrical, and "No" otherwise (both excluding quotation marks). You can output each letter in any case (upper or lower).

NoteThe first two examples are illustrated below. Both images become the same as their respective original ones after a clockwise rotation of $$$120$$$ degrees around the center.

open Printf
open Scanf

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

let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in
  let chord = Array.init m (fun _ -> let (a,b) = read_pair() in (a-1,b-1)) in

  let table = Hashtbl.create 10 in
  for i=0 to m-1 do
    let (a,b) = chord.(i) in
    Hashtbl.add table (a,b) true;
    Hashtbl.add table (b,a) true;
  done;

  let rec find_divisors ac i =
    if i*i > n then ac else (
      let ac = if n mod i = 0 then
	  (if i=1 || i*i=n then (i::ac) else (n/i)::(i::ac))
	else ac
      in
      find_divisors ac (i+1)
    )
  in

  let divisors = find_divisors [] 1 in

  let test_symmetry d =
  (* test with the given divisor *)
    forall 0 (m-1) (fun i ->
      let (a,b) = chord.(i) in
      try Hashtbl.find table ((a+d) mod n, (b+d) mod n) with Not_found -> false
    )
  in

  let answer = List.exists test_symmetry divisors in

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


You have an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \neq j$$$; $$$i \neq k$$$; $$$j \neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i. e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \le n \le 100$$$; $$$1 \le d \le 100$$$) — the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the array $$$a$$$.

For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

NoteIn the first test case, we can prove that we can't make all $$$a_i \le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$.

open Str
open Big_int
open Num

let multitest = true

module Shortcuts = struct
  let loop n f = for i = 0 to n - 1 do f i; done

end

module Helper = struct
  open Shortcuts

  let read_s () = Scanf.scanf "%s\n" (fun x -> x)

  let read_int ?endl () =
    match endl with
    | None -> Scanf.scanf "%d " (fun x -> x)
    | Some () -> Scanf.scanf "%d\n" (fun x -> x)

  let read_array n =
    let a = Array.make n 0 in
    loop (n-1) (fun i -> a.(i) <- read_int ());
    a.(n-1) <- read_int ~endl:() ();
    a

end

module Ext = struct
  module List = struct
    let rec make n x =
      if (n <= 0) then []
      else x :: make (n-1) x

  end

end

module Alg = struct
  let rec gcd x y =
    if y <> 0 then (gcd y (x mod y))
    else (abs x)

  let lcm x y =
    if x = 0 || y = 0 then 0
    else abs (x * y) / (gcd x y)

end

let solve _ =
  let open Shortcuts in
  let open Helper in
  let open Printf in
  let open Ext in
  let open Alg in
  (* ***** Solution code here ***** *)
  let n = read_int () in
  let d = read_int ~endl:() () in
  let a = read_array n in
  Array.sort compare a;
  if (a.(n-1) <= d || a.(0) + a.(1) <= d) then printf "YES\n"
  else printf "NO\n";
  (* ***** ******************* ***** *)
;;

let () =
  let open Helper in
  let open Shortcuts in
  let t = if multitest then read_int ~endl:() () else 1 in
  loop t solve;;


You are given a problemset consisting of $$$n$$$ problems. The difficulty of the $$$i$$$-th problem is $$$a_i$$$. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $$$a_{i_1}, a_{i_2}, \dots, a_{i_p}$$$ be the difficulties of the selected problems in increasing order. Then for each $$$j$$$ from $$$1$$$ to $$$p-1$$$ $$$a_{i_{j + 1}} \le a_{i_j} \cdot 2$$$ should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems in the problemset. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.

Print a single integer — maximum number of problems in the contest satisfying the condition in the problem statement.

NoteDescription of the first example: there are $$$10$$$ valid contests consisting of $$$1$$$ problem, $$$10$$$ valid contests consisting of $$$2$$$ problems ($$$[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$$$), $$$5$$$ valid contests consisting of $$$3$$$ problems ($$$[5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]$$$) and a single valid contest consisting of $$$4$$$ problems ($$$[5, 6, 7, 10]$$$).In the second example all the valid contests consist of $$$1$$$ problem.In the third example are two contests consisting of $$$3$$$ problems: $$$[4, 7, 12]$$$ and $$$[100, 150, 199]$$$.


Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≤ i < j ≤ n.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations. The second line contains n - 1 integer ai (i + 1 ≤ ai ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to ai inclusive.

Print the sum of ρi, j among all pairs of 1 ≤ i < j ≤ n.

NoteIn the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.Consider the second sample:   ρ1, 2 = 1  ρ1, 3 = 2  ρ1, 4 = 3  ρ1, 5 = 3  ρ2, 3 = 1  ρ2, 4 = 2  ρ2, 5 = 2  ρ3, 4 = 1  ρ3, 5 = 1  ρ4, 5 = 1 Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x);;
let print_int x = Printf.printf "%d " x;;
let print_int64 x = Printf.printf "%Ld " x;;
let print s = Printf.printf "%s" s;;

module type S = sig
  val set : int -> int -> unit
  val get : int -> int
  val inc : int -> int -> unit
  val max_range : int -> int -> int
  val max_range_value : int -> int -> int
end

module MakeSegTree (M: (sig val size : int end)) : S = struct
  let n = M.size
  let nn = 3 * n

  let arr = Array.make n 0
  let delta = Array.make nn 0

  let set i v = arr.(i) <- v
  let get i = arr.(i)

  let rec update c b e i =
    let upd c =
      if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then
        delta.(c) <- delta.(2*c+1)
      else
        delta.(c) <- delta.(2*c) in
    if (b > e || i > e || i < b) then ()
    else if ((i = b) && (i = e)) then delta.(c) <- i
    else if i <= (b+e)/2 then begin
      update (2*c) b ((b+e)/2) i; upd c
    end else begin
      update (2*c+1) (((b+e)/2)+1) e i; upd c
    end

  let inc i v =
    arr.(i) <- v;
    update 1 0 (n-1) i

  let rec query c b e i j =
    if (b > e || i > j || b > j || i > e) then -1 else
    if i <= b && e <= j then delta.(c)
    else
      let first = query (2*c) b ((b+e)/2) i j in
      let second = query (2*c+1) ((b+e)/2+1) e i j in
      match first,second with
      | -1,_ -> second
      | _,-1 -> first
      | _,_ ->
        if arr.(first) < arr.(second) then second
        else first

  let max_range i j =
    query 1 0 (n-1) i j

  let max_range_value i j =
    let ind = max_range i j in
    arr.(ind)
end

let () =
  let n = read_int () in
  let module Size = struct
    let size = n
  end in
  let module Segtree = MakeSegTree(Size) in
  let dummy = Array.make (n-1) () in
  let arr = Array.map (fun _ -> read_int() -1) dummy in
  let add_to_seg i e =
    Segtree.inc i e in
  Array.iteri add_to_seg arr;
  Segtree.inc (n-1) 0;
  let dp = Array.make n Int64.zero in
  for i = n-2 downto 0 do
    let ma = Segtree.max_range (i+1) arr.(i) in
    dp.(i) <- Int64.add dp.(ma) (Int64.of_int (- (arr.(i) - ma) + (n - i - 1)));
    (*print_int i;
    print_int ma;
    print_int64 dp.(i);
    print_int64 (Int64.of_int ((arr.(i) - ma) + (n - i - 1)));
    print "\n"; *)
  done;
  print_int64 (Array.fold_left Int64.add Int64.zero dp);;

open Printf
open Scanf

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

let parent v = v/2
let lc v = 2*v
let rc v = 2*v+1

let superceil n =
  let rec loop i ac = if i=0 then ac else loop (i lsr 1) (ac lor i) in
  1 + (loop (n-1) 0)

let max2 (h1,p1) (h2,p2) = let (x,y) = max (h1,-p1) (h2,-p2) in (x,-y)

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 a = Array.init n (fun i -> if i=n-1 then i else -1 + read_int()) in

  let nn = superceil n in

  let t = Array.make (2*nn) (0,0) in

  let rec insert ar (x,i) =
    let rec loop j = if j>0 then (
      ar.(j) <- max2 ar.(j) (x,i);
      loop (parent j)
    ) in
    loop (i+nn)
  in

  let max_in_range i j =
    let rec f v l r ql qr =
      let m = (l+r)/2 in
      if l=ql && r=qr then t.(v) else
	let t1 = if ql<=m then f (lc v) l m ql (min m qr) else (0,0) in
	let t2 = if qr>m then f (rc v) (m+1) r (max ql (m+1)) qr else (0,0) in
	max2 t1 t2
    in
    f 1 0 (nn-1) i j
  in

  for i=0 to n-1 do
    insert t (a.(i),i)
  done;

  let dist = Array.make n 0L in
  (* dist.(i) is the sum over all j>i of the number of hops from i to j *)

  for i=n-2 downto 0 do
    let k = a.(i) in
    let (_,j) = max_in_range (i+1) k in
    (* dist.(i) <-  (k-i) + dist.(j) - (k-j) + (n-1-k) *)
    dist.(i) <- (long (j+n-k-i-1)) ++ dist.(j)
  done;

  let answer = sum 0 (n-2) (fun i -> dist.(i)) 0L in
  printf "%Ld\n" answer

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x);;
let print_int x = Printf.printf "%d " x;;
let print_int64 x = Printf.printf "%Ld " x;;
let print s = Printf.printf "%s" s;;

module type S = sig
  val set : int -> int -> unit
  val get : int -> int
  val inc : int -> int -> unit
  val max_range : int -> int -> int
  val max_range_value : int -> int -> int
end

module MakeSegTree (M: (sig val size : int end)) : S = struct
  let n = M.size
  let nn = 3 * n

  let arr = Array.make n 0
  let delta = Array.make nn 0

  let set i v = arr.(i) <- v
  let get i = arr.(i)

  let rec update c b e i =
    let upd c =
      if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then
        delta.(c) <- delta.(2*c+1)
      else
        delta.(c) <- delta.(2*c) in
    if (b > e || i > e || i < b) then ()
    else if ((i = b) && (i = e)) then delta.(c) <- i
    else if i <= (b+e)/2 then begin
      update (2*c) b ((b+e)/2) i; upd c
    end else begin
      update (2*c+1) (((b+e)/2)+1) e i; upd c
    end

  let inc i v =
    arr.(i) <- v;
    update 1 0 (n-1) i

  let rec query c b e i j =
    if (b > e || i > j || b > j || i > e) then -1 else
    if i <= b && e <= j then delta.(c)
    else
      let first = query (2*c) b ((b+e)/2) i j in
      let second = query (2*c+1) ((b+e)/2+1) e i j in
      match first,second with
      | -1,_ -> second
      | _,-1 -> first
      | _,_ ->
        if arr.(first) < arr.(second) then second
        else first

  let max_range i j =
    query 1 0 (n-1) i j

  let max_range_value i j =
    let ind = max_range i j in
    arr.(ind)
end

let () =
  let n = read_int () in
  let module Size = struct
    let size = n
  end in
  let module Segtree = MakeSegTree(Size) in
  let dummy = Array.make (n-1) () in
  let arr = Array.map (fun _ -> read_int() -1) dummy in
  let add_to_seg i e =
    Segtree.inc i e in
  Array.iteri add_to_seg arr;
  Segtree.inc (n-1) 0;
  let dp = Array.make n Int64.zero in
  for i = n-2 downto 0 do
    let ma = Segtree.max_range (i+1) arr.(i) in
    dp.(i) <- Int64.sub dp.(ma) (Int64.of_int ((arr.(i) - ma) + (n - i - 1)));
  done;
  print_int64 (Array.fold_left Int64.add Int64.zero dp);;

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x);;
let print_int x = Printf.printf "%d " x;;
let print s = Printf.printf "%s" s;;

module type S = sig
  val set : int -> int -> unit
  val get : int -> int
  val inc : int -> int -> unit
  val max_range : int -> int -> int
  val max_range_value : int -> int -> int
end

module MakeSegTree (M: (sig val size : int end)) : S = struct
  let n = M.size
  let nn = 3 * n

  let arr = Array.make n 0
  let delta = Array.make nn 0

  let set i v = arr.(i) <- v
  let get i = arr.(i)

  let rec update c b e i =
    let upd c =
      if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then
        delta.(c) <- delta.(2*c+1)
      else
        delta.(c) <- delta.(2*c) in
    if (b > e || i > e || i < b) then ()
    else if ((i = b) && (i = e)) then delta.(c) <- i
    else if i <= (b+e)/2 then begin
      update (2*c) b ((b+e)/2) i; upd c
    end else begin
      update (2*c+1) (((b+e)/2)+1) e i; upd c
    end

  let inc i v =
    arr.(i) <- v;
    update 1 0 (n-1) i

  let rec query c b e i j =
    if (b > e || i > j || b > j || i > e) then -1 else
    if i <= b && e <= j then delta.(c)
    else
      let first = query (2*c) b ((b+e)/2) i j in
      let second = query (2*c+1) ((b+e)/2+1) e i j in
      match first,second with
      | -1,_ -> second
      | _,-1 -> first
      | _,_ ->
        if arr.(first) < arr.(second) then second
        else first

  let max_range i j =
    query 1 0 (n-1) i j

  let max_range_value i j =
    let ind = max_range i j in
    arr.(ind)
end

let () =
  let n = read_int () in
  let module Size = struct
    let size = n
  end in
  let module Segtree = MakeSegTree(Size) in
  let dummy = Array.make (n-1) () in
  let arr = Array.map read_int dummy in
  let add_to_seg i e =
    Segtree.inc i e in
  Array.iteri add_to_seg arr;
  let dp = Array.make (n-1) 1 in
  let process cur e =
    let res,i = cur in
    let ran = arr.(i) in
    let ma = Segtree.max_range (i+1) (ran-1) in
    if ran < n then dp.(ma) <- dp.(ma) + e;
    (*print_int ma;
    print_int e;
    print_int (res + e*(n-i-1));
    print "\n";*)
    (res + e*(n-i-1)),(i+1) in
  let res,_ = Array.fold_left process (0,0) dp in
  print_int res;;

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x);;
let print_int x = Printf.printf "%d " x;;
let print s = Printf.printf "%s" s;;

module type S = sig
  val set : int -> int -> unit
  val get : int -> int
  val inc : int -> int -> unit
  val max_range : int -> int -> int
  val max_range_value : int -> int -> int
end

module MakeSegTree (M: (sig val size : int end)) : S = struct
  let n = M.size
  let nn = 3 * n

  let arr = Array.make n 0
  let delta = Array.make nn 0

  let set i v = arr.(i) <- v
  let get i = arr.(i)

  let rec update c b e i =
    let upd c =
      if arr.(delta.(2*c)) < arr.(delta.(2*c+1)) then
        delta.(c) <- delta.(2*c+1)
      else
        delta.(c) <- delta.(2*c) in
    if (b > e || i > e || i < b) then ()
    else if ((i = b) && (i = e)) then delta.(c) <- i
    else if i <= (b+e)/2 then begin
      update (2*c) b ((b+e)/2) i; upd c
    end else begin
      update (2*c+1) (((b+e)/2)+1) e i; upd c
    end

  let inc i v =
    arr.(i) <- v;
    update 1 0 (n-1) i

  let rec query c b e i j =
    if (b > e || i > j || b > j || i > e) then -1 else
    if i <= b && e <= j then delta.(c)
    else
      let first = query (2*c) b ((b+e)/2) i j in
      let second = query (2*c+1) ((b+e)/2+1) e i j in
      match first,second with
      | -1,_ -> second
      | _,-1 -> first
      | _,_ ->
        if arr.(first) < arr.(second) then second
        else first

  let max_range i j =
    query 1 0 (n-1) i j

  let max_range_value i j =
    let ind = max_range i j in
    arr.(ind)
end

let () =
  let n = read_int () in
  let module Size = struct
    let size = n
  end in
  let module Segtree = MakeSegTree(Size) in
  let dummy = Array.make (n-1) () in
  let arr = Array.map (fun _ -> read_int() -1) dummy in
  let add_to_seg i e =
    Segtree.inc i e in
  Array.iteri add_to_seg arr;
  Segtree.inc (n-1) 0;
  let dp = Array.make n 0 in
  for i = n-2 downto 0 do
    let ma = Segtree.max_range (i+1) arr.(i) in
    dp.(i) <- dp.(ma) - (arr.(i) - ma) + (n - i - 1);
  done;
  print_int (Array.fold_left (fun a b -> a + b) 0 dp);;


This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them are connected by a cable. The computers are indexed by integers from 1 to n. It's known that any two computers connected by cable directly or through other computersPolycarpus decided to find out the network's topology. A network topology is the way of describing the network configuration, the scheme that shows the location and the connections of network devices.Polycarpus knows three main network topologies: bus, ring and star. A bus is the topology that represents a shared cable with all computers connected with it. In the ring topology the cable connects each computer only with two other ones. A star is the topology where all computers of a network are connected to the single central node.Let's represent each of these network topologies as a connected non-directed graph. A bus is a connected graph that is the only path, that is, the graph where all nodes are connected with two other ones except for some two nodes that are the beginning and the end of the path. A ring is a connected graph, where all nodes are connected with two other ones. A star is a connected graph, where a single central node is singled out and connected with all other nodes. For clarifications, see the picture.    (1) — bus, (2) — ring, (3) — star You've got a connected non-directed graph that characterizes the computer network in Polycarpus' corporation. Help him find out, which topology type the given network is. If that is impossible to do, say that the network's topology is unknown.

The first line contains two space-separated integers n and m (4 ≤ n ≤ 105; 3 ≤ m ≤ 105) — the number of nodes and edges in the graph, correspondingly. Next m lines contain the description of the graph's edges. The i-th line contains a space-separated pair of integers xi, yi (1 ≤ xi, yi ≤ n) — the numbers of nodes that are connected by the i-the edge. It is guaranteed that the given graph is connected. There is at most one edge between any two nodes. No edge connects a node with itself.

In a single line print the network topology name of the given graph. If the answer is the bus, print "bus topology" (without the quotes), if the answer is the ring, print "ring topology" (without the quotes), if the answer is the star, print "star topology" (without the quotes). If no answer fits, print "unknown topology" (without the quotes).

bus topology
ring topology
star topology
unknown topology

(* Codeforces contest 292 B - SMS Center *)

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 rec readlist n acc = match n with | 0 -> List.rev acc | _ -> readlist (n -1) (gr() :: acc);;
let debug = false;;

let n = gr();;  (* size network *)
let m = gr();;  (* number edges *)

let adj = Array.make (n +1) [];;

let rec readpairs n acc = match n with
    | 0 -> List.rev acc
    | _ ->
            let a = gr() in
            let b = gr() in
            readpairs (n -1) ((a, b) :: acc);;

let rec setadj lpr = match lpr with
    | [] -> ()
    | hd :: tl ->
            let (a, b) = hd in
            (
                adj.(a) <- b :: adj.(a);
                adj.(b) <- a :: adj.(b);
                setadj tl
            );;

let rec findone i acc =
    if i > n then acc
    else
        let ln = List.length adj.(i) in
        let nacc = if ln = 1 then (i :: acc) else acc in
        findone (i +1) nacc;;

let nextInSeq prev aa =
    match adj.(aa) with
    | a :: b :: [] ->
            if a = prev then b
            else if b = prev then a
            else raise (Failure "not connected to prev")
    | _ -> -1;;

let rec countLoop start prev cur cnt =
    let nxt = nextInSeq prev cur in
    if nxt = start then cnt
		else if nxt = -1 then (-1)
    else countLoop start cur nxt (cnt +1);;

let main() =
    let prs = readpairs m [] in
    let _ = setadj prs in
    let lone = findone 0 [] in
    let nones = List.length lone in
		(* let _ = print_int nones in *)
    if nones = 0 then
        (
            (* can be only loop *)
            let start = 1 in
            let a = (List.hd adj.(start)) in
            let nloop = countLoop start start a 0 in
            if nloop = n-2 then print_string "ring topology"
            else print_string "unknown topology"
        )
    else if nones = 2 then
        (
            (* checking bus config *)
            let a = List.hd lone in
            let b = List.hd (List.tl lone) in
            let anxt = (List.hd adj.(a)) in
            let nseq = countLoop b a anxt 0 in
            if nseq = n -3 then print_string "bus topology"
            else print_string "unknown topology"
        )
    else if nones = n -1 then
        (
            (* checking star *)
            let a = List.hd lone in
            let center = (List.hd adj.(a)) in
            let nstar = List.length adj.(center) in
            if nstar = n -1 then print_string "star topology"
            else print_string "unknown topology"
        )
    else
        print_string "unknown topology";;

main();;


Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types:  it can contain a single sticker and no toy;  it can contain a single toy and no sticker;  it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$T$$$ lines contain three integers $$$n$$$, $$$s$$$ and $$$t$$$ each ($$$1 \le n \le 10^9$$$, $$$1 \le s, t \le n$$$, $$$s + t \ge n$$$) — the number of eggs, stickers and toys. All queries are independent.

Print $$$T$$$ integers (one number per query) — the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and one toy

NoteIn the first query, we have to take at least $$$6$$$ eggs because there are $$$5$$$ eggs with only toy inside and, in the worst case, we'll buy all of them.In the second query, all eggs have both a sticker and a toy inside, that's why it's enough to buy only one egg.In the third query, we have to buy both eggs: one with a sticker and one with a toy.

module Big = struct

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

  let babs = Int64.abs
  let rem = Int64.rem

end

module Helper = struct

  type t_type =
    | Int of int
    | Long of Int64.t

  let read_int ?endl () =
    match endl with
    | None -> Scanf.scanf "%d " (fun x -> x)
    | Some () -> Scanf.scanf "%d\n" (fun x -> x)

  let read_long ?endl () =
    match endl with
    | None -> Scanf.scanf "%Ld " (fun x -> x)
    | Some () -> Scanf.scanf "%Ld\n" (fun x -> x)

  let read_int_array n =
    let res = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
    Scanf.scanf "\n" (fun _ -> ());
    res

  let read_long_array n =
    let res = Array.init n (fun _ -> Scanf.scanf "%Ld " (fun x -> x)) in
    Scanf.scanf "\n" (fun _ -> ());
    res

  let read_char_array n =
    let res = Array.init n (fun _ -> Scanf.scanf "%c" (fun x -> x)) in
    Scanf.scanf "\n" (fun _ -> ());
    res

  let debug = function
    | Int x -> Printf.printf "%d\n" x
    | Long x -> Printf.printf "%Ld\n" x

  type 'a return = { return : 'b . 'a -> 'b }

  (* From Jane Street Tech Blog *)
  let with_return (type t) (f : _ -> t) =
    let module M = struct exception Return of t end in
    let return = { return = (fun x -> raise (M.Return x)); } in
    try f return with M.Return x -> x
    (* with_return (fun r -> do_somthing; if return_condition then r.return (); *)

  let loop n f = for i = 0 to n - 1 do f i; done

  let find_nb f a =
    let res = ref 0 in
    Array.iteri (fun i x -> if f i x then incr res) a;
    !res

end

let () =
  let open Helper in
  let open Big in
  let t = read_int ~endl:() () in
  loop t (fun _ ->
      let n = read_long () in
      let s = read_long () in
      let t = read_long () in
      let x = s ++ t -- n in
      let s = s -- x in
      let t = t -- x in
      debug (Long ((max s t)++1L))
    )
;;


Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type). If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of friends.  Then follow n data blocks that describe each friend's phone books. Each block is presented in the following form: first goes the line that contains integer si and string namei (0 ≤ si ≤ 100) — the number of phone numbers in the phone book of the i-th friend and the name of the i-th friend. The name is a non-empty sequence of uppercase and lowercase Latin letters, containing no more than 20 characters. Next si lines contain numbers as "XX-XX-XX", where X is arbitrary digits from 0 to 9.

In the first line print the phrase "If you want to call a taxi, you should call: ". Then print names of all friends whose phone books contain maximal number of taxi phone numbers.  In the second line print the phrase "If you want to order a pizza, you should call: ". Then print names of all friends who have maximal number of pizza phone numbers.  In the third line print the phrase "If you want to go to a cafe with a wonderful girl, you should call: ". Then print names of all friends who have maximal number of girls' phone numbers.  Print the names in the order in which they are given in the input data. Separate two consecutive names with a comma and a space. Each line should end with exactly one point. For clarifications concerning the output form, see sample tests. It is necessary that you follow the output form strictly. Extra spaces are not allowed.

If you want to call a taxi, you should call: Rogulenko.
If you want to order a pizza, you should call: Fedorov, Rogulenko, Kaluzhin.
If you want to go to a cafe with a wonderful girl, you should call: Melnikov.

If you want to call a taxi, you should call: Gleb.
If you want to order a pizza, you should call: Gleb, Serega.
If you want to go to a cafe with a wonderful girl, you should call: Melnik.

If you want to call a taxi, you should call: Pachocki.
If you want to order a pizza, you should call: Kulczynski, Pachocki.
If you want to go to a cafe with a wonderful girl, you should call: Kulczynski.

NoteIn the first sample you are given four friends. Fedorov's phone book contains one taxi number and one pizza delivery number, Melnikov's phone book only has 3 numbers of girls, Rogulenko's one has 6 taxi numbers and one pizza delivery number, Kaluzhin's one contains 2 taxi numbers and one pizza delivery number.Thus, if you need to order a taxi, you should obviously call Rogulenko, if you need to order a pizza you should call anybody of the following: Rogulenko, Fedorov, Kaluzhin (each of them has one number). Melnikov has maximal number of phone numbers of girls.

let main () =
    let check a p =
        let rec loop i =
            i = 0 || p a.[i - 1] a.[i] && loop (i - 1)
        in
        loop (String.length a - 1)
    in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, [|taxi; pizza; girl |] else
                let a = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in
                if check a (=) then loop (r - 1) (taxi + 1) pizza girl else
                if check a (>) then loop (r - 1) taxi (pizza + 1) girl
                else loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc flag k pos = function
        | (name, target) :: tl ->
            if target.(pos) = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc false k pos tl
            ) else proc flag k pos tl
        | _ -> print_endline "."
    in

    let comp k = (fun (_, a1) (_, a2) -> compare a2.(k) a1.(k)) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort (comp 0) l with
    | (_, a) :: _ -> proc true a.(0) 0 l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort (comp 1) l with
    | (_, a) :: _ -> proc true a.(1) 1 l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort (comp 2) l with
    | (_, a) :: _ -> proc true a.(2) 2 l
    | _ -> ())
;;
main ()

let main () =
    let check a p =
        let rec loop i =
            i = 0 || p a.[i - 1] a.[i] && loop (i - 1)
        in
        loop (String.length a - 1)
    in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, [|taxi; pizza; girl |] else
                let a = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in
                if check a (=) then loop (r - 1) (taxi + 1) pizza girl else
                if check a (>) then loop (r - 1) taxi (pizza + 1) girl
                else loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc flag k pos = function
        | (name, target) :: tl ->
            if target.(pos) = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc false k pos tl
            ) else proc flag k pos tl
        | _ -> print_endline "."
    in

    let comp k = (fun (_, a1) (_, a2) -> compare a2.(k) a1.(k)) in

    let l = Array.to_list arr in
    for i = 0 to 2 do
        print_string [| "If you want to call a taxi, you should call: ";
                        "If you want to order a pizza, you should call: ";
                        "If you want to go to a cafe with a wonderful girl, you should call: " |].(i);
        match List.sort (comp i) l with
        | (_, a) :: _ -> proc true a.(i) i l
        | _ -> ()
    done
;;
main ()

let main () =
    let map n s =
        let s1 = 8 lsl (int_of_char s.[0] - 48) in
        let s2 = 8 lsl (int_of_char s.[1] - 48) in
        let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in
                if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let a = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in
                if a.[0] = a.[1] && a.[0] = a.[2] &&
                   a.[0] = a.[3] && a.[0] = a.[4] &&
                   a.[0] = a.[5] then loop (r - 1) (taxi + 1) pizza girl else
                if a.[0] > a.[1] && a.[1] > a.[2] &&
                   a.[2] > a.[3] && a.[3] > a.[4] &&
                   a.[4] > a.[5] then loop (r - 1) taxi (pizza + 1) girl
                else loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc1 flag k = function
        | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()

let main () =
    let check a p =
        let rec loop i =
            i = 0 || p a.[i - 1] a.[i] && loop (i - 1)
        in
        loop (String.length a - 1)
    in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let a = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in
                if check a (=) then loop (r - 1) (taxi + 1) pizza girl else
                if check a (>) then loop (r - 1) taxi (pizza + 1) girl
                else loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc1 flag k = function
        | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()

let main () =

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let a = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in
                if a.[0] = a.[1] && a.[0] = a.[2] &&
                   a.[0] = a.[3] && a.[0] = a.[4] &&
                   a.[0] = a.[5] then loop (r - 1) (taxi + 1) pizza girl else
                if a.[0] > a.[1] && a.[1] > a.[2] &&
                   a.[2] > a.[3] && a.[3] > a.[4] &&
                   a.[4] > a.[5] then loop (r - 1) taxi (pizza + 1) girl
                else loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc1 flag k = function
        | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()

let main () =
    let kolvo = int_of_string (read_line ()) in
	(* Заполняем массив значениями в формате Фамилия, телефоны такси, телефоны пиццы, телефоны девочек *)
    let my_array = Array.init kolvo (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let temp = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in
                if temp.[0] = temp.[1] && temp.[0] = temp.[2] &&
                   temp.[0] = temp.[3] && temp.[0] = temp.[4] &&
                   temp.[0] = temp.[5] then loop (r - 1) (taxi + 1) pizza girl else
                if temp.[0] > temp.[1] && temp.[1] > temp.[2] &&
                   temp.[2] > temp.[3] && temp.[3] > temp.[4] &&
                   temp.[4] > temp.[5] then loop (r - 1) taxi (pizza + 1) girl
                else loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc1 flag k = function | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list my_array in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()

let main () =

 let rec proc1 flag k = function
        | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let map n s =
        let s1 = 8 lsl (int_of_char s.[0] - 48) in
        let s2 = 8 lsl (int_of_char s.[1] - 48) in
        let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in
                if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let a = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1 ^ a2 ^ a3) in
                if a.[0] = a.[1] && a.[0] = a.[2] &&
                   a.[0] = a.[3] && a.[0] = a.[4] &&
                   a.[0] = a.[5] then loop (r - 1) (taxi + 1) pizza girl else
                if a.[0] > a.[1] && a.[1] > a.[2] &&
                   a.[2] > a.[3] && a.[3] > a.[4] &&
                   a.[4] > a.[5] then loop (r - 1) taxi (pizza + 1) girl
                else loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()

let main () =
    let map n s =
        let s1 = 8 lsl (int_of_char s.[0]) in
        let s2 = 8 lsl (int_of_char s.[1]) in
        let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in
                if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let a1, a2, a3 = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1, a2, a3) in
                if a1 = a2 && a2 = a3 then loop (r - 1) (taxi + 1) pizza girl else
                if a1 > a2 && a2 > a3 && (map (map (map 0 a1) a2) a3) land 7 = 6
                                       then loop (r - 1) taxi (pizza + 1) girl else
                                           loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc1 flag k = function
        | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()

let main () =
    let map n s =
        let s1 = 8 lsl (int_of_char s.[0] - 48) in
        let s2 = 8 lsl (int_of_char s.[1] - 48) in
        let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in
                if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let a1, a2, a3 = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1, a2, a3) in
                if a1 = a2 && a2 = a3 then loop (r - 1) (taxi + 1) pizza girl else
                if a1 > a2 && a2 > a3 && (map (map (map 0 a1) a2) a3) land 7 = 6
                                       then loop (r - 1) taxi (pizza + 1) girl else
                                           loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc1 flag k = function
        | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()

let main () =
    let map n s =
        let s1 = 8 lsl (int_of_char s.[0] - 48) in
        let s2 = 8 lsl (int_of_char s.[1] - 48) in
        let n = if n land s1 = 0 then (n lor s1) + 1 else n lor s1 in
                if n land s2 = 0 then (n lor s2) + 1 else n lor s2 in

    let n = int_of_string (read_line ()) in
    let arr = Array.init n (fun _ ->
        let (d, name) = Scanf.sscanf (read_line ()) "%d %s" (fun d name -> d, name) in
        let rec loop r taxi pizza girl =
            if r = 0 then name, taxi, pizza, girl else
                let a1, a2, a3 = Scanf.sscanf (read_line ()) "%2s-%2s-%2s" (fun a1 a2 a3 -> a1, a2, a3) in
                if a1 = a2 && a2 = a3 && int_of_string a1 mod 11 = 0 then loop (r - 1) (taxi + 1) pizza girl else
                if a1 > a2 && a2 > a3 && (map (map (map 0 a1) a2) a3) land 7 = 6
                                       then loop (r - 1) taxi (pizza + 1) girl else
                                           loop (r - 1) taxi pizza (girl + 1)
        in
        loop d 0 0 0
        )
    in

    let rec proc1 flag k = function
        | (name, taxi, _, _) :: tl ->
            if taxi = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc1 false k tl
            ) else proc1 flag k tl
        | _ -> print_endline "."
    in

    let rec proc2 flag k = function
        | (name, _, pizza, _) :: tl ->
            if pizza = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc2 false k tl
            ) else proc2 flag k tl
        | _ -> print_endline "."
    in

    let rec proc3 flag k = function
        | (name, _, _, girl) :: tl ->
            if girl = k then (
                Printf.printf "%s%s" (if flag then "" else ", ") name;
                proc3 false k tl
            ) else proc3 flag k tl
        | _ -> print_endline "."
    in

    let comp1 =(fun (_, k1, _, _) (_, k2, _, _) -> compare k2 k1) in
    let comp2 =(fun (_, _, k1, _) (_, _, k2, _) -> compare k2 k1) in
    let comp3 =(fun (_, _, _, k1) (_, _, _, k2) -> compare k2 k1) in

    let l = Array.to_list arr in
    print_string "If you want to call a taxi, you should call: ";
    (match List.sort comp1 l with
    | (_, k, _, _) :: _ -> proc1 true k l
    | _ -> ());

    print_string "If you want to order a pizza, you should call: ";
    (match List.sort comp2 l with
    | (_, _, k, _) :: _ -> proc2 true k l
    | _ -> ());

    print_string "If you want to go to a cafe with a wonderful girl, you should call: ";
    (match List.sort comp3 l with
    | (_, _, _, k) :: _ -> proc3 true k l
    | _ -> ())
;;
main ()


Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:  Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.  Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman. After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?

The first line contains a single integer n (1 ≤ n ≤ 3·105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the initial group that is given to Toastman.

Print a single integer — the largest possible score.

NoteConsider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.

(**D. The Child and Sequence*)

open Scanf;;
open Num;;
open Printf;;
open Array;;

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

let a = Array.create n 0;;

let total = ref (num_of_int 0);;
for i = 0 to n-1 do
  let ni = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  a.(i) <- ni; total:=!total +/ (num_of_int ni)
done
 ;;

if n=1 then
  printf "%s\n" (string_of_num !total)
else
  begin

    let () = Array.fast_sort (fun x y -> x-y) a in
    (*Array.iter(fun i -> printf "%d\n" i) a;*)
    let rec cal_score m pn score total_v =
      match m with
      | 2 -> total_v +/ score
      | _ ->cal_score (m-1) (pn+1) (score+/total_v) (total_v -/
                                                       (num_of_int
                                                          a.(pn)) )
    in
    let rslt = cal_score n 0 (num_of_int 0)  !total
    in
    print_string (string_of_num  (rslt +/  !total) );
                  print_endline "";
  end
;;

(**D. The Child and Sequence*)

open Scanf;;
open Num;;
open Printf;;
open Array;;

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

let a = Array.create n 0;;

let total = ref 0;;
for i = 0 to n-1 do
  let ni = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  a.(i) <- ni; total:=!total + ni
done
 ;;

if n=1 then
  printf "%d\n" !total
else
  begin

    let () = Array.fast_sort (fun x y -> x-y) a in
    (*Array.iter(fun i -> printf "%d\n" i) a;*)
    let rec cal_score m pn score total_v =
      match m with
      | 2 -> total_v +/ score
      | _ ->cal_score (m-1) (pn+1) (score+/total_v) (total_v -/
                                                       (num_of_int
                                                          a.(pn)) )
    in
    let rslt = cal_score n 0 (num_of_int 0) (num_of_int !total)
    in
    print_string (string_of_num  (rslt +/ (num_of_int !total)) );
                  print_endline "";
  end
;;

(**D. The Child and Sequence*)

open Scanf;;
open Num;;
open Printf;;
open Array;;

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

let a = Array.create n 0;;

let total = ref 0;;
for i = 0 to n-1 do
  let ni = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  a.(i) <- ni; total:=!total + ni
done
 ;;

if n=1 then
  printf "%d\n" !total
else
  begin

    let () = Array.fast_sort (fun x y -> x-y) a in
    (*Array.iter(fun i -> printf "%d\n" i) a;*)
    let rec cal_score m pn score total_v =
      match m with
      | 2 -> total_v + score
      | _ ->cal_score (m-1) (pn+1) (score+total_v) (total_v - a.(pn))
    in
    let rslt = cal_score n 0 0 !total
    in
    printf "%d\n" (rslt + !total)
  end
;;


A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not.The string t is called a substring of the string s if it can be read starting from some position in the string s. For example, the string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".You are given a string s, consisting of lowercase Latin letters and characters "?". You are also given a string p, consisting of lowercase Latin letters only. Let's assume that a string is good if you can obtain an anagram of the string p from it, replacing the "?" characters by Latin letters. Each "?" can be replaced by exactly one character of the Latin alphabet. For example, if the string p = «aba», then the string "a??" is good, and the string «?bc» is not. Your task is to find the number of good substrings of the string s (identical substrings must be counted in the answer several times).

The first line is non-empty string s, consisting of no more than 105 lowercase Latin letters and characters "?". The second line is non-empty string p, consisting of no more than 105 lowercase Latin letters. Please note that the length of the string p can exceed the length of the string s.

Print the single number representing the number of good substrings of string s. Two substrings are considered different in their positions of occurrence are different. Thus, if some string occurs several times, then it should be counted the same number of times.

NoteConsider the first sample test. Here the string s has two good substrings: "b??" (after we replace the question marks we get "baa"), "???" (after we replace the question marks we get "baa").Let's consider the second sample test. Here the string s has two good substrings: "ab?" ("?" can be replaced by "c"), "b?c" ("?" can be replaced by "a").

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

let () =
  let s = read_string() in
  let p = read_string() in
  let m = String.length s in
  let n = String.length p in
  let () = if m<n then (Printf.printf "0\n"; exit 0) in
  let histp = Array.make 26 0 in
  let hists = Array.make 26 0 in
  let ci c = (int_of_char c) - (int_of_char 'a') in

  let () =
    for i=0 to n-1 do
      let j = ci p.[i] in
      histp.(j)<-histp.(j)+1
    done
  in

  let () =
    for i = 0 to n-1 do
      let j = ci s.[i] in
      if s.[i]<> '?' then hists.(j) <- hists.(j)+1
    done
  in
  let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh(i+1)
  in
  let rec scan j ac =
    let inc = if goodh 0 then 1 else 0 in
    if j = m then inc + ac else (
      if s.[j]<> '?' then hists.(ci s.[j]) <- hists.(ci s.[j])+1;
      if s.[j-n] <> '?' then hists.(ci s.[j-n]) <- hists.(ci s.[j-n])-1;
      scan (j+1) (ac+inc)
    )
  in
  Printf.printf "%d\n" (scan n 0)

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

let () =
  let s = read_string() in
  let p = read_string() in

  let m = String.length s in
  let n = String.length p in

  let () = if m < n then (Printf.printf "0\n"; exit 1) in

  let histp = Array.make 26 0 in
  let hists = Array.make 26 0 in

  let ctoint c = (int_of_char c) - (int_of_char 'a') in

  let () =
    for i=0 to n-1 do
      let j = ctoint p.[i] in
      histp.(j) <- histp.(j) + 1
    done
  in

  let () =
    for i=0 to n-1 do
      let j = ctoint s.[i] in
      if s.[i] <> '?' then hists.(j) <- hists.(j) + 1
    done
  in

  let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh (i+1) in

  let rec scan j ac =
    let inc = if goodh 0 then 1 else 0 in
      if j=m then inc + ac else (
	if s.[j] <> '?' then hists.(ctoint s.[j]) <- hists.(ctoint s.[j]) + 1;
	if s.[j-n] <> '?' then hists.(ctoint s.[j-n]) <- hists.(ctoint s.[j-n]) - 1;
	scan (j+1) (ac+inc)
      )
  in

    Printf.printf "%d\n" (scan n 0)

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

let () =
  let s = read_string() in
  let p = read_string() in
  let m = String.length s in
  let n = String.length p in
  let () = if m<n then (Printf.printf "0\n"; exit 0) in
  let histp = Array.make 26 0 in
  let hists = Array.make 26 0 in
  let ci c = (int_of_char c) - (int_of_char 'a') in

  let () =
	for i=0 to n-1 do
	  let j = ci p.[i] in
	  histp.(j)<-histp.(j)+1
	done
  in

  let () =
	for i = 0 to n-1 do
	  let j = ci s.[i] in
	  if s.[i]<> '?' then hists.(j) <- hists.(j)+1
	done
  in
  let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh(i+1)
  in
  let rec scan j ac =
	let inc = if goodh 0 then 1 else 0 in
	if j = m then inc + ac else (
	  if s.[j]<> '?' then hists.(ci s.[j]) <- hists.(ci s.[j])+1;
	  if s.[j-n] <> '?' then hists.(ci s.[j-n]) <- hists.(ci s.[j-n])+1;
	  scan (j+1) (ac+inc)
	)
  in
  Printf.printf "%d\n" (scan n 0)

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

let () =
  let s = read_string() in
  let p = read_string() in

  let m = String.length s in
  let n = String.length p in

  let histp = Array.make 26 0 in
  let hists = Array.make 26 0 in

  let ctoint c = (int_of_char c) - (int_of_char 'a') in

  let () =
    for i=0 to n-1 do
      let j = ctoint p.[i] in
      histp.(j) <- histp.(j) + 1
    done
  in

  let () =
    for i=0 to n-1 do
      let j = ctoint s.[i] in
      if s.[i] <> '?' then hists.(j) <- hists.(j) + 1
    done
  in

  let rec goodh i = if i=26 then true else histp.(i) >= hists.(i) && goodh (i+1) in

  let rec scan j ac =
    let inc = if goodh 0 then 1 else 0 in
      if j=m then inc + ac else (
	if s.[j] <> '?' then hists.(ctoint s.[j]) <- hists.(ctoint s.[j]) + 1;
	if s.[j-n] <> '?' then hists.(ctoint s.[j-n]) <- hists.(ctoint s.[j-n]) - 1;
	scan (j+1) (ac+inc)
      )
  in

    Printf.printf "%d\n" (scan n 0)


You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible.A polyline defined by points p1, p2, p3, p4 consists of the line segments p1 p2, p2 p3, p3 p4, and its length is the sum of the lengths of the individual line segments.

The only line of the input contains two integers n and m (0 ≤ n, m ≤ 1000). It is guaranteed that grid contains at least 4 different points.

Print 4 lines with two integers per line separated by space — coordinates of points p1, p2, p3, p4 in order which represent the longest possible polyline. Judge program compares your answer and jury's answer with 10 - 6 precision.

let print xs =
  List.iter (fun (x, y) ->
    Printf.printf "%d %d\n" x y) xs
;;

let foi = float_of_int ;;
let sq x = x *. x ;;
let norm x y = sqrt (sq x +. sq y)

let f1 x y =
  let x, y = foi x, foi y in
  max x y +. 2. *. norm x y
;;

let f2 x y =
  let x, y = foi x, foi y in
  norm x y +. 2. *. norm (x -. 1.) y
;;

let f3 x y =
  let x, y = foi x, foi y in
  norm x y +. 2. *. norm x (y -. 1.)
;;

let () =
  Scanf.scanf "%d %d " (fun n m ->
    if n = 0 then
      print [(0, 1); (0, m); (0, 0); (0, m - 1)]
    else if m = 0 then
      print [(1, 0); (n, 0); (0, 0); (n - 1, 0)]
    else if f1 n m > max (f2 n m) (f3 n m) then
      if n >= m then
        print [(0, 0); (n, m); (0, m); (n, 0)]
      else
        print [(0, 0); (n, m); (n, 0); (0, m)]
    else if f2 n m > f3 n m then
      print [(n - 1, m); (0, 0); (n, m); (1, 0)]
    else
      print [(n, m - 1); (0, 0); (n, m); (0, 1)])
;;

let print xs =
  List.iter (fun (x, y) ->
    Printf.printf "%d %d\n" x y) xs
;;

let foi = float_of_int ;;
let sq x = x *. x ;;
let norm x y = sqrt (sq x +. sq y)

let f1 x y =
  let x, y = foi x, foi y in
  max x y +. 2. *. norm x y
;;

let f2 x y =
  let x, y = foi x, foi y in
  norm x y +. norm (x -. 1.) y +. norm x (y -. 1.)
;;

let () =
  Scanf.scanf "%d %d " (fun n m ->
    if n = 0 then
      print [(0, 1); (0, m); (0, 0); (0, m - 1)]
    else if m = 0 then
      print [(1, 0); (n, 0); (0, 0); (n - 1, 0)]
    else if f1 n m > f2 n m then
      if n >= m then
        print [(0, 0); (n, m); (0, m); (n, 0)]
      else
        print [(0, 0); (n, m); (n, 0); (0, m)]
    else
      print [(n - 1, m); (0, 0); (n, m); (1, 0)])
;


Vasya the Great Magician and Conjurer loves all kinds of miracles and wizardry. In one wave of a magic wand he can turn an object into something else. But, as you all know, there is no better magic in the Universe than the magic of numbers. That's why Vasya adores math and spends a lot of time turning some numbers into some other ones.This morning he has n cards with integers lined up in front of him. Each integer is not less than 1, but not greater than l. When Vasya waves his magic wand, two rightmost cards vanish from the line and a new card magically appears in their place. It contains the difference between the left and the right numbers on the two vanished cards. Vasya was very interested to know what would happen next, and so he waved with his magic wand on and on, until the table had a single card left.Suppose that Vasya originally had the following cards: 4, 1, 1, 3 (listed from left to right). Then after the first wave the line would be: 4, 1, -2, and after the second one: 4, 3, and after the third one the table would have a single card with number 1.Please note that in spite of the fact that initially all the numbers on the cards were not less than 1 and not greater than l, the numbers on the appearing cards can be anything, no restrictions are imposed on them.It is now evening. Vasya is very tired and wants to return everything back, but does not remember which cards he had in the morning. He only remembers that there were n cards, they contained integers from 1 to l, and after all magical actions he was left with a single card containing number d.Help Vasya to recover the initial set of cards with numbers.

The single line contains three space-separated integers: n (2 ≤ n ≤ 100) — the initial number of cards on the table, d (|d| ≤ 104) — the number on the card that was left on the table after all the magical actions, and l (1 ≤ l ≤ 100) — the limits for the initial integers.

If Vasya is mistaken, that is, if there doesn't exist a set that meets the requirements given in the statement, then print a single number -1, otherwise print the sought set containing n integers from 1 to l. Separate the integers by spaces. Print the integers in the order, in which they were written on the cards from left to right. If there are several suitable sets of numbers, you can print any of them.

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;

let rec loop n d l x a =
  if n <= 0 then Printf.printf("\n")
  else
    if d > x then
      if a = -1 then begin Printf.printf "1 "; loop (n-1) d l x (a*(-1)) end
      else let z = min (d-x) (l-1) in
      begin Printf.printf "%d " (z+1); loop (n-1) d l (x+z) (a*(-1)) end
    else if d < x then
      if a = 1 then begin Printf.printf "1 "; loop (n-1) d l x (a*(-1)) end
      else let z = min (x-d) (l-1) in
      begin Printf.printf "%d " (z+1); loop (n-1) d l (x-z) (a*(-1)) end
    else begin Printf.printf "1 "; loop (n-1) d l x (a*(-1)) end

let _ =
  let (n,d,l) = read3() in
  if (  (n+1)/2 - (n/2) - (l-1)*(n/2) > d || (n+1)/2 - (n/2) + (l-1)*((n+1)/2) < d )
  then Printf.printf "-1\n"
  else
  loop n d l ( (n+1)/2 - n/2 ) 1;;

let read_one () = Scanf.scanf " %d" (fun x -> x)
let read_two () = Scanf.scanf " %d %d" (fun x y -> (x,y))
let read_three () = Scanf.scanf "%d %d %d" (fun x y z -> (x,y,z))

let read_many n =
  let rec helper i acc =
    if i >= n then List.rev acc
    else Scanf.scanf " %d" (fun n -> helper (i+1) (n::acc)) in
  helper 0 []

let list_iteri f lst = List.fold_left (fun j b -> f j b; j+1) 0 lst

let even n = n mod 2 = 0

let rec solve cur tar left l =
  if left <= 0 then []
  else if cur = tar then
    if even left then
      1 :: 1 :: ( solve cur tar (left - 2) l)
    else
      1 :: 2 :: 1 :: (solve cur tar (left - 3) l)
  else if cur > tar then
    let sub = min (cur + 1 - tar) l in
    let new_cur = cur + 1 - sub in
    if new_cur = tar && left = 3 then
	let sub = sub + 1 in
	1 :: sub :: 1 :: []
    else
      1 :: sub :: (solve new_cur tar (left - 2) l)
  else (* cur > tar *)
    let add = min l (tar + 1 - cur) in
    let new_cur = cur + add - 1 in
    if new_cur = tar && left = 3 then
      let add = add - 1 in
      add :: 1 :: 1 :: []
    else if left = 1 then
      let add = tar - cur in
      add :: []
    else
      add :: 1 :: (solve new_cur tar (left - 2) l)

let main =
  let (n,d,l) = read_three() in
  let min_d = (n - n / 2) - (n / 2) * l in
  let max_d = (n - n / 2) * l - (n / 2) in
  if min_d > d || max_d < d then
    Printf.printf "-1\n"
  else
    let print j b =
      if j = n - 1 then Printf.printf "%d\n" b
      else Printf.printf "%d " b in
    ignore (list_iteri print (solve 0 d n l));

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;

let rec loop n d l x a =
  if n <= 0 then Printf.printf("\n")
  else
    if d > x then
      if a = -1 then begin Printf.printf "1 "; loop (n-1) d l x (a*(-1)) end
      else let z = min (d-x) (l-1) in
      begin Printf.printf "%d " (z+1); loop (n-1) d l (x+z) (a*(-1)) end
    else if d < x then
      if a = 1 then begin Printf.printf "1 "; loop (n-1) d l x (a*(-1)) end
      else let z = min (x-d) (l-1) in
      begin Printf.printf "%d " (z+1); loop (n-1) d l (x-z) (a*(-1)) end
    else begin Printf.printf "1 "; loop (n-1) d l x (a*(-1)) end

let _ =
  let (n,d,l) = read3() in
  Printf.printf "%d %d %d\n" n d l;
  if (  (n+1)/2 - (n/2) - (l-1)*(n/2) > d || (n+1)/2 - (n/2) + (l-1)*((n+1)/2) < d )
  then Printf.printf "-1\n"
  else
  loop n d l ( (n+1)/2 - n/2 ) 1;;


Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.  Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

let m = 1000000007L

let mmod n =
  let r = Int64.rem n m in
    if r >= 0L
    then r
    else Int64.add r m

let msquare a =
  let n = Array.length a in
  let r = Array.make_matrix n n 0L in
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	for k = 0 to n - 1 do
	  r.(i).(j) <-
	    mmod (Int64.add r.(i).(j) (Int64.mul a.(i).(k) a.(k).(j)))
	done;
      done
    done;
    r

let powermod r b n =
  let w = Array.length r in
  let r = ref r in
  let b = ref b in
  let n = ref n in
  let t = ref 0L in
    while !n > 0L do
      if Int64.rem !n 2L <> 0L then (
	let r2 = Array.make w 0L in
	  for i = 0 to w - 1 do
	    t := 0L;
	    for j = 0 to w - 1 do
	      t := mmod (Int64.add !t (Int64.mul !r.(j) !b.(j).(i)))
	    done;
	    r2.(i) <- !t;
	  done;
	  r := r2;
      );
      b := msquare !b;
      n := Int64.div !n 2L;
    done;
    !r

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let r = [| 1L; 0L|] in
  let b =
    [| [|3L;  1L|];
       [|1L;  3L|];
    |]
  in
  let res = powermod r b n in
    Printf.printf "%Ld\n" res.(0)


Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly.

Print the single number — the maximum number of points you can score in one round by the described rules.

NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.

let main () =
    let n = read_int () in
    let arr = Array.init n (fun _ -> Scanf.sscanf (read_line ()) "%d %d" (fun a b -> b, a)) in
    Array.sort (fun a b -> compare b a) arr;
    let list = Array.to_list arr in
    let rec loop r acc = function
        | [] -> acc
        | (a, b) :: tl -> if r = 0 then acc else loop (r - 1 + a) (b + acc) tl
    in
    let ans = loop 1 0 list in
    Printf.printf "%d\n" ans
;;
main ()

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

let sort_cards cards =
  let compare_cards a b =
    if a = b then 0
    else if (snd a) > (snd b) then -1
    else if (snd a) = (snd b) && (fst a) > (fst b) then -1
    else 1
  in
  List.sort compare_cards cards

let rec solve cards opportunity points =
  match cards with
    | [] -> points
    | h :: t ->
      if opportunity = 0 then points
      else solve t (opportunity + (snd h) - 1) (points + (fst h))

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let cards = input_cards n [] in
  Printf.printf "%d\n" (solve (sort_cards cards) 1 0)


Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$ — the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.

The first line contains one integer $$$n$$$ — the number of vertices in the tree ($$$2 \le n \le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \le s_v \le 10^9$$$), where erased values are replaced by $$$-1$$$.

Output one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.

let rec fix f x = f (fix f) x
let (++),(--),max_int = Int64.(add,sub,max_int);;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let edg = make n [] in
  ignore @@
    init (n-1) (fun i ->
      let j = scanf " %d" @@ fun v -> v in (
        let i,j = i+1,j-1 in
        edg.(i) <- j :: edg.(i);
        edg.(j) <- i :: edg.(j)));
  (* iteri (fun i ls ->
    Printf.printf "%d: " i;
    List.iter (Printf.printf "%d ") ls;
    print_newline ()
  ) edg; *)
  let s = init n @@ fun _ -> scanf " %Ld" @@ fun v -> v in
  let undef = -7L in
  let a = make n undef in
  let visited = make n false in
  fix (fun f i even par ->
    visited.(i) <- true;
    if not even then (
      if i=0 then (
        a.(i) <- s.(i)
      ) else (
        a.(i) <- s.(i) -- s.(par)
      );
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    ) else (
      let sh = s.(par) in
      let smin = List.fold_left (fun mn j ->
        if par=j then mn
        else min mn s.(j)
      ) max_int edg.(i) in
      let smin = if smin = max_int then sh else smin in
      let si = smin -- sh in
      if si < 0L then (print_string "-1"; exit 0);
      s.(i) <- smin;
      a.(i) <- smin -- s.(par);
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    )
  ) 0 false 0;
  (* iter (Printf.printf "%d ") a;
  print_newline ();
  iter (Printf.printf "%d ") s;
  print_newline (); *)
  Printf.printf "%Ld" @@ fold_left (++) 0L a
))

let rec fix f x = f (fix f) x;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let edg = make n [] in
  ignore @@
    init (n-1) (fun i ->
      let j = scanf " %d" @@ fun v -> v in (
        let i,j = i+1,j-1 in
        edg.(i) <- j :: edg.(i);
        edg.(j) <- i :: edg.(j)));
  (* iteri (fun i ls ->
    Printf.printf "%d: " i;
    List.iter (Printf.printf "%d ") ls;
    print_newline ()
  ) edg; *)
  let s = init n @@ fun _ -> scanf " %d" @@ fun v -> v in
  let undef = -7 in
  let a = make n undef in
  let visited = make n false in
  fix (fun f i even par ->
    visited.(i) <- true;
    if not even then (
      if i=0 then (
        a.(i) <- s.(i)
      ) else (
        a.(i) <- s.(i) - s.(par)
      );
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    ) else (
      let sh = s.(par) in
      let smin = List.fold_left (fun mn j ->
        if par=j then mn
        else min mn s.(j)
      ) max_int edg.(i) in
      let smin = if smin = max_int then sh else smin in
      let si = smin - sh in
      if si < 0 then (print_string "-1"; exit 0);
      s.(i) <- smin;
      a.(i) <- smin - s.(par);
      List.iter (fun j ->
        if not @@ visited.(j) then f j (not even) i
      ) edg.(i)
    )
  ) 0 false 0;
  (* iter (Printf.printf "%d ") a;
  print_newline ();
  iter (Printf.printf "%d ") s;
  print_newline (); *)
  print_int @@ fold_left (+) 0 a
))