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

let divisors v =
	let rec f0 i a =
		if i*i > v then a
		else if i*i = v && v mod i = 0L then i::a
		else if v mod i = 0L then f0 (i+1L) (i::(v/i)::a)
		else f0 (i+1L) a in f0 1L []
let rec len_i64 v =
	let rec f0 v = if v=0L then 0L else if v<=9L then 1L else 1L+f0 (v/10L)
	in f0 (labs v)
let () =
	let n = get_i64 0 in
	let d = divisors n in
	printf "%Ld\n" @@ List.fold_left (fun u v ->
		let w = n / v in
		let p = max (len_i64 v) (len_i64 w) in min u p
	) Int64.max_int d

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

The input is given from Standard Input in the following format:

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


let dp = Array.make_matrix (50 + 1) (50 + 1) ~-1
let rec c n k = if dp.(n).(k) > -1 then dp.(n).(k) else (dp.(n).(k) <- if n < k then 0 else if n = k then 1 else if k = 0 then 1 else c (n - 1) (k - 1) + c (n - 1) k; dp.(n).(k))
let n, a, b = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b - 1, c - 1
let vs = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let m = Array.(sort (fun x y -> y - x) vs; vs.(0))
let k = ref (b + 1)
let _ = Array.(iteri (fun i v -> if a <= i && i < !k && v < m then k := i) vs; if a < !k then decr k; let t = fold_left (fun c v -> if v = vs.(!k) then c + 1 else c) 0 vs in
  Printf.printf "%.6f\n%d\n" (float (sub vs 0 (!k + 1) |> fold_left (+) 0) /. (float !k +. 1.)) @@ if vs.(!k) = m then let s = ref 0 in for i = a + 1 to b + 1 do s := !s + c t i done; !s else c t (sub vs a (b - a + 1) |> fold_left (fun a v -> if v = vs.(!k) then a + 1 else a) 0))

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 400 points

Problem Statement

You are given N items.

The value of the i-th item (1 \leq i \leq N) is v_i.

Your have to select at least A and at most B of these items.

Under this condition, find the maximum possible arithmetic mean of the values of selected items.

Additionally, find the number of ways to select items so that the mean of the values of selected items is maximized.

Constraints

1 \leq N \leq 50

1 \leq A,B \leq N

1 \leq v_i \leq 10^{15}

Each v_i is an integer.

Input

The input is given from Standard Input in the following format:

N A B
v_1
v_2
...
v_N

Output

Print two lines.

The first line should contain the maximum possible arithmetic mean of the values of selected items. The output should be considered correct if the absolute or relative error is at most 10^{-6}.

The second line should contain the number of ways to select items so that the mean of the values of selected items is maximized.

Sample Input 1

5 2 2
1 2 3 4 5

Sample Output 1

4.500000
1

The mean of the values of selected items will be maximized when selecting the fourth and fifth items. Hence, the first line of the output should contain 4.5.

There is no other way to select items so that the mean of the values will be 4.5, and thus the second line of the output should contain 1.

Sample Input 2

4 2 3
10 20 10 10

Sample Output 2

15.000000
3

There can be multiple ways to select items so that the mean of the values will be maximized.

Sample Input 3

5 1 5
1000000000000000 999999999999999 999999999999998 999999999999997 999999999999996

Sample Output 3

1000000000000000.000000
1

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


Scanf.scanf "%c %c" @@ fun a b -> Printf.printf "%c\n" @@ if a = 'H' then b else if b = 'H' then 'D' else 'H'

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

The input is given from Standard Input in the following format:

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


let () =
  let s1, s2 = Scanf.scanf "%s %s " (fun a b -> a, b) in
  Printf.printf "%s\n" (if s1 = s2 then "H" else "D")


let () =
  Scanf.scanf "%c %c" (fun a b ->
      match a with
      | 'H' -> b
      | _ -> if b = 'H' then 'D' else 'H')
  |> Printf.printf "%c\n"


Scanf.scanf "%d %d %d" (fun w a b ->
    let a, b = min a b, max a b in
    Printf.printf "%d\n" @@ max 0 (b - a - w)
)

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

The input is given from Standard Input in the following format:

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


let w, a, b = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = Printf.printf "%d\n" @@ if a + w < b then b - a - w else if b + w < a then a - b - w else 0


let x = read_int ()
let s, i = ref 0, ref 1
let _ = while !s < x do s := !s + !i; incr i done; Printf.printf "%d\n" @@ !i - 1

Score : 200 points

Problem Statement

There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0.
During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right.
That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i.
The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible.
Find the earliest possible time to reach coordinate X.

Constraints

X is an integer.

1≤X≤10^9

Input

The input is given from Standard Input in the following format:

X

Output

Print the earliest possible time for the kangaroo to reach coordinate X.

Sample Input 1

6

Sample Output 1

3

The kangaroo can reach his nest at time 3 by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2

He can reach his nest at time 2 by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5


let id x = x
let x = Scanf.scanf "%d" id

let rec func x i =
  if i = x then i else
    if x - i > i then func (x-i) (i+1) else x

let ans = func x 1

let () = Printf.printf "%d\n" ans


let id x = x
let xa = Scanf.scanf "%d\n" id

let x = if xa < 0 then xa * (-1) else xa

let rec func x i =
  if i = x then i else
    if x - i > i then func (x-i) (i+1) else x

let ans = func x 1

let () = Printf.printf "%d\n" ans


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

let ans n k a =
  let rec solve i sum ret =
    if i = n then ret
    else if sum + a.(i) < k then solve (i + 1) (sum + a.(i)) (ret + 1)
    else solve (i + 1) sum 0
  in solve 0 0 0

let () =
  let n, k = Scanf.scanf "%d %d" (fun n k -> n, k) in
  let a = read_int_array n in
  Array.sort (fun x y -> - x + y) a;
  print_int (ans n k a)

Score : 600 points

Problem Statement

AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i.
Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater.

Then, for each card i, he judges whether it is unnecessary or not, as follows:

If, for any good subset of the cards containing card i, the set that can be obtained by eliminating card i from the subset is also good, card i is unnecessary.

Otherwise, card i is NOT unnecessary.

Find the number of the unnecessary cards. Here, he judges each card independently, and he does not throw away cards that turn out to be unnecessary.

Constraints

All input values are integers.

1≤N≤5000

1≤K≤5000

1≤a_i≤10^9 (1≤i≤N)

Partial Score

300 points will be awarded for passing the test set satisfying N,K≤400.

Input

The input is given from Standard Input in the following format:

N K
a_1 a_2 ... a_N

Output

Print the number of the unnecessary cards.

Sample Input 1

3 6
1 4 3

Sample Output 1

1

There are two good sets: {2,3} and {1,2,3}.

Card 1 is only contained in {1,2,3}, and this set without card 1, {2,3}, is also good. Thus, card 1 is unnecessary.

For card 2, a good set {2,3} without card 2, {3}, is not good. Thus, card 2 is NOT unnecessary.

Neither is card 3 for a similar reason, hence the answer is 1.

Sample Input 2

5 400
3 1 4 1 5

Sample Output 2

5

In this case, there is no good set. Therefore, all the cards are unnecessary.

Sample Input 3

6 20
10 4 3 10 25 2

Sample Output 3

3


let () =
  Scanf.scanf "%d %d" @@ fun n k ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  Array.sort (-) a;

  let dp = Array.make k false in
  let rec loop l r =
    if l >= r then r else
    let m = (l+r) / 2 in
    let x = a.(m) in
    Array.fill dp 0 k false; dp.(0) <- true;

    a |> Array.iteri (fun i v ->
      if i = m then () else
      for j = k-1 downto v do
        dp.(j) <- dp.(j) || dp.(j-v)
      done);

    Array.init (min k x) (fun i -> dp.(k-1-i))
    |> Array.fold_left (||) false
    |> fun b -> if b then loop l m else loop (m+1) r
  in

  loop 0 n |> Printf.printf "%d\n"


Scanf.scanf "%d %d %d" (fun n c k ->
    let t = Array.init n (fun _ -> Scanf.scanf " %d" (fun t -> t )) in
    Array.sort compare t;

    let rec loop i cur pop buses =
        if i = n then (if pop > 0 then buses + 1 else buses) else
            let tt = t.(i) in
            if tt <= cur + k then (
                if pop < c then loop (i + 1) cur (pop + 1) buses else
                                loop (i + 1) tt  1 (buses + 1)
            ) else (
                let buses = if pop > 0 then buses + 1 else buses in
                loop (i + 1) tt 1 buses
            )
    in
    loop 0 0 0 0 |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

Every day, N passengers arrive at Takahashi Airport.
The i-th passenger arrives at time T_i.

Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers.
Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport.
Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane.
For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).

When setting the departure times for buses under this condition, find the minimum required number of buses.
Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.

Constraints

2 \leq N \leq 100000

1 \leq C \leq 10^9

1 \leq K \leq 10^9

1 \leq T_i \leq 10^9

C, K and T_i are integers.

Input

The input is given from Standard Input in the following format:

N C K
T_1
T_2
:
T_N

Output

Print the minimum required number of buses.

Sample Input 1

5 3 5
1
2
3
6
12

Sample Output 1

3

For example, the following three buses are enough:

A bus departing at time 4.5, that carries the passengers arriving at time 2 and 3.

A bus departing at time 6, that carries the passengers arriving at time 1 and 6.

A bus departing at time 12, that carries the passenger arriving at time 12.

Sample Input 2

6 3 3
7
6
2
8
10
6

Sample Output 2

3


(* O(n log n) *)
let n, c, k = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let ts = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let rec loop acc i r m =
  if i >= n then acc
  else if m >= c || r <= ts.(i) then loop (acc + 1) (i + 1) (ts.(i) + k) 1
  else loop acc (i + 1) r (m + 1)
let _ =
  Array.sort (-) ts;
  loop 1 1 (ts.(0) + k) 1 |> Printf.printf "%d\n"


let n, s, l = read_int (), ref 0, ref 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let _ = Array.sort (-) a_s; for i = 0 to n - 2 do s := !s + a_s.(i); if a_s.(i + 1) > 2 * !s then l := i + 1 done; Printf.printf "%d\n" @@ n - !l

Score : 400 points

Problem Statement

Snuke found N strange creatures.
Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively.

Every creature can absorb another creature whose size is at most twice the size of itself.
When a creature of size A and color B absorbs another creature of size C and color D (C \leq 2 \times A), they will merge into one creature of size A+C and color B.
Here, depending on the sizes of two creatures, it is possible that both of them can absorb the other.

Snuke has been watching these creatures merge over and over and ultimately become one creature.
Find the number of the possible colors of this creature.

Constraints

2 \leq N \leq 100000

1 \leq A_i \leq 10^9

A_i is an integer.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

Print the number of the possible colors of the last remaining creature after the N creatures repeatedly merge and ultimately become one creature.

Sample Input 1

3
3 1 4

Sample Output 1

2

The possible colors of the last remaining creature are colors 1 and 3.
For example, when the creature of color 3 absorbs the creature of color 2, then the creature of color 1 absorbs the creature of color 3, the color of the last remaining creature will be color 1.

Sample Input 2

5
1 1 1 1 1

Sample Output 2

5

There may be multiple creatures of the same size.

Sample Input 3

6
40 1 30 2 7 20

Sample Output 3

4


let n, ans, s = read_int (), ref 0, ref 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let _ = Array.(sort (-) a_s; iteri (fun i a -> s := !s + a; if i = n - 1 || a_s.(i + 1) <= 2 * !s then incr ans else ans := 0) a_s); Printf.printf "%d\n" !ans


Array.(init (read_int ()) succ |> fold_left (fun p n -> p * n mod 1000000007) 1) |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

The input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


let n = read_int ()
let ans = ref 1
let _ = for i = 1 to n do ans := !ans * i mod 1000000007 done; Printf.printf "%d\n" !ans


let n = read_int () in
let p = ref 1 in
let ( * ) a b = a * b mod 1_000_000_007 in
for i = 1 to n do
  p := !p * i
done;
Printf.printf "%d\n" !p


let rec solve n =
    match n with
    1 -> 1
    | n -> (n * (solve (n - 1))) mod 1000000007;;

let () =
    let n = read_int () in
    print_int (solve n);
    print_newline ();;


let n = read_int ()
let m = int_of_float (10. ** 9. +. 7.)

let fact n =
  let rec f i n' =
    if i = 1 then n' mod m else f (i - 1) (i mod m * n' mod m)
  in
  f n 1

let () = Printf.printf "%d\n" (fact n)


let get_2_ints () = Scanf.scanf "%d %d " (fun u v -> u,v)

let () =
  let (s,c) = get_2_ints ()
  in
  (
    let c_left = c-s*2 in
    if c_left >= 0 then (
      s + c_left / 4
    )else(
      let s_true = c / 2
      in s_true
    )
  )
  |> string_of_int |> print_endline

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

The input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


let n, m = Scanf.scanf "%d %d" (fun x y -> x, y)
let () =
  let a = min n (m / 2) in
  let b = (m - 2 * a) / 4 in
  Printf.printf "%d\n" (a+b)


let () = Scanf.scanf "%d %d" (fun n m ->
  Printf.printf "%d\n"
    (if m < 2 * n then m / 2 else (2 * n + m) / 4))


let split_on_char sep (s : string) =
    let rec rindex (i: int) =
        if i < 0 then
            None
        else
            if s.[i] = sep then
                Some i
            else
                rindex (i - 1) in
    let rec loop i result =
        match rindex (i - 1) with
          Some ii -> loop ii (String.sub s (ii + 1) (i - 1 - ii) :: result)
        | None -> (String.sub s 0 i) :: result in
    loop (String.length s) []

let ord s =
    match int_of_string s with
            1 -> 14
        |   n -> n

let main =
    let a = read_line () in
    let x = split_on_char ' ' a in
      let v = match x with
        [a; b] ->
      (match compare (ord a) (ord b) with
        1 -> "Alice"
        | 0 -> "Draw"
        | -1 -> "Bob" )
        | _ -> "" in
        print_endline v

Score : 100 points

Problem Statement

Alice and Bob are playing One Card Poker.

One Card Poker is a two-player game using playing cards.

Each card in this game shows an integer between 1 and 13, inclusive.

The strength of a card is determined by the number written on it, as follows:

Weak 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10 < 11 < 12 < 13 < 1 Strong

One Card Poker is played as follows:

Each player picks one card from the deck. The chosen card becomes the player's hand.

The players reveal their hands to each other. The player with the stronger card wins the game.

If their cards are equally strong, the game is drawn.

You are watching Alice and Bob playing the game, and can see their hands.

The number written on Alice's card is A, and the number written on Bob's card is B.

Write a program to determine the outcome of the game.

Constraints

1≦A≦13

1≦B≦13

A and B are integers.

Input

The input is given from Standard Input in the following format:

A B

Output

Print Alice if Alice will win. Print Bob if Bob will win. Print Draw if the game will be drawn.

Sample Input 1

8 6

Sample Output 1

Alice

8 is written on Alice's card, and 6 is written on Bob's card.
Alice has the stronger card, and thus the output should be Alice.

Sample Input 2

1 1

Sample Output 2

Draw

Since their cards have the same number, the game will be drawn.

Sample Input 3

13 1

Sample Output 3

Bob


let () =
  let a, b = Scanf.scanf "%d %d " (fun a b -> a, b) in
  let a = if (a = 1) then 14 else a in
  let b = if (b = 1) then 14 else b in
  Printf.printf "%s\n"
  (if a > b then "Bob" else (if a = b then "Draw" else "Alice")
  )


let () =
  let a, b = Scanf.scanf "%d %d " (fun a b -> a, b) in
  Printf.printf "%s\n"
  (if a > b then "Bob" else (if a = b then "Draw" else "Alice")
  )


let n, m = Scanf.scanf "%d %d" (fun x y -> x, y)
let graph = Array.init n (fun _ -> [])
let _ = Array.init m (fun _ -> Scanf.scanf " %d %d" (fun a b ->
  graph.(a-1) <- b-1 :: graph.(a-1);
  graph.(b-1) <- a-1 :: graph.(b-1)))
let visited = Array.make n false
let rec dfs i d =
  if d >= n then 1 else
    graph.(i) |> List.map (fun j ->
      if visited.(j) then 0 else (
        visited.(j) <- true;
        let v = dfs j (d+1) in
        visited.(j) <- false;
        v
      )
    ) |> List.fold_left (+) 0

let () =
  visited.(0) <- true;
  dfs 0 1 |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

The given graph contains neither self-loops nor double edges.

Input

The input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

7 7
1 3
2 7
3 4
4 5
4 6
5 6
6 7

Sample Output 2

1

This test case is the same as the one described in the problem statement.


let scan_words () = Scanf.scanf "%d %d\n" (fun a b -> (a, b))
let n, m = scan_words ()
let h = Hashtbl.create m
let ans = ref 0

let rec search found visited now =
  if List.exists ((=) now) visited then ()
  else if found = n then incr ans
  else
    let () = Printf.printf "now: %d, found: %d\n" now found in
    let found' = found + 1 in
    let visited' = now :: visited in
    match Hashtbl.find_all h now with
    | [] -> ()
    | next_nodes -> List.iter (search found' visited') next_nodes

let () =
  for i = 1 to m do
    let a, b = scan_words () in
    Hashtbl.add h a b ;
    Hashtbl.add h b a
  done ;
  search 1 [] 1 ;
  Printf.printf "%d\n" !ans


(* O(n) *)
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let ps = Array.make 2 0
let _ =
  Array.iter (fun a -> ps.(a mod 2) <- ps.(a mod 2) + 1) a_s;
  if ps.(1) >= 2 then (ps.(0) <- ps.(0) + 1; ps.(1) <- ps.(1) mod 2);
  if ps.(0) >= 1 then ps.(0) <- 1;
  print_endline @@ if ps.(0) + ps.(1) = 1 then "YES" else "NO"

Score : 300 points

Problem Statement

There are N integers written on a blackboard. The i-th integer is A_i.

Takahashi will repeatedly perform the following operation on these numbers:

Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.

Then, write a new integer on the blackboard that is equal to the sum of those integers, A_i+A_j.

Determine whether it is possible to have only one integer on the blackboard.

Constraints

2 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

A_i is an integer.

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

If it is possible to have only one integer on the blackboard, print YES. Otherwise, print NO.

Sample Input 1

3
1 2 3

Sample Output 1

YES

It is possible to have only one integer on the blackboard, as follows:

Erase 1 and 3 from the blackboard, then write 4. Now, there are two integers on the blackboard: 2 and 4.

Erase 2 and 4 from the blackboard, then write 6. Now, there is only one integer on the blackboard: 6.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

NO


let () =
	let x = read_int () in
	if x < 1200 then
		print_endline "ABC"
	else
		print_endline "ARC"

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


let x = read_int () in
let n = (x - 1) / 11 + 1 in
print_int (if n * 11 - 5 >= x then 2 * n - 1 else 2 * n)

Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

The input is given from Standard Input in the following format:

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


let solve n = if n < 7 then 1 else
  max ((n / 11) * 2 + (if n mod 11 = 0 then 0 else 1)) 2

let () =
  let rec read () =
    try let ans = (Scanf.scanf "%d\n" solve) in
        Printf.printf "%d\n" ans
    with End_of_file -> ()
  in
  read ()
;;


let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let s = Scanf.scanf "%s " (fun a -> a) in
  let cs = Batteries.String.to_list s in
  let is = List.map (fun x -> if x = 'I' then 1 else -1) cs in

  let rec f last res = function
    | [] -> res
    | hd :: tl ->
      f (last+hd) ((last+hd)::res) tl
  in
  let max = (f 0 [] (0::is) |> List.sort compare |> List.rev |> List.hd) in
  Printf.printf "%d\n" max

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

The input is given from Standard Input in the following format:

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


let ans, p = ref 0, ref 0
let _ = Scanf.scanf "%d %d %d" @@ fun n a b -> for i = 1 to n do Scanf.scanf " %d" @@ fun x -> if i > 1 then ans := !ans + min b (a * (x - !p)); p := x done; Printf.printf "%d\n" !ans

Score : 500 points

Problem Statement

There are N towns on a line running east-west.
The towns are numbered 1 through N, in order from west to east.
Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value.
The coordinate of town i is X_i.

You are now at town 1, and you want to visit all the other towns.
You have two ways to travel:

Walk on the line.
Your fatigue level increases by A each time you travel a distance of 1, regardless of direction.

Teleport to any location of your choice.
Your fatigue level increases by B, regardless of the distance covered.

Find the minimum possible total increase of your fatigue level when you visit all the towns in these two ways.

Constraints

All input values are integers.

2≤N≤10^5

1≤X_i≤10^9

For all i(1≤i≤N-1), X_i<X_{i+1}.

1≤A≤10^9

1≤B≤10^9

Input

The input is given from Standard Input in the following format:

N A B
X_1 X_2 ... X_N

Output

Print the minimum possible total increase of your fatigue level when you visit all the towns.

Sample Input 1

4 2 5
1 2 5 7

Sample Output 1

11

From town 1, walk a distance of 1 to town 2, then teleport to town 3, then walk a distance of 2 to town 4.
The total increase of your fatigue level in this case is 2×1+5+2×2=11, which is the minimum possible value.

Sample Input 2

7 1 100
40 43 45 105 108 115 124

Sample Output 2

84

From town 1, walk all the way to town 7.
The total increase of your fatigue level in this case is 84, which is the minimum possible value.

Sample Input 3

7 1 2
24 35 40 68 72 99 103

Sample Output 3

12

Visit all the towns in any order by teleporting six times.
The total increase of your fatigue level in this case is 12, which is the minimum possible value.


let () =
  String.iter
    (fun c -> if c = ',' then print_string " " else print_char c)
    (read_line ());
  print_newline ();

Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


let dx, dy = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> c - a, d - b
let f n c = print_string @@ String.make n c
let _ = f dy 'U'; f dx 'R'; f dy 'D'; f dx 'L';
  f 1 'L'; f (dy + 1) 'U'; f (dx + 1) 'R'; f 1 'D'; f 1 'R'; f (dy + 1) 'D'; f (dx + 1) 'L'; f 1 'U'

Score : 300 points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.

Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.

Here, both the x- and y-coordinates before and after each movement must be integers.

He will first visit the point (tx,ty) where sx < tx and sy < ty, then go back to the point (sx,sy), then visit the point (tx,ty) again, and lastly go back to the point (sx,sy).

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points (sx,sy) and (tx,ty).

Under this condition, find a shortest path for him.

Constraints

-1000 ≤ sx < tx ≤ 1000

-1000 ≤ sy < ty ≤ 1000

sx,sy,tx and ty are integers.

Input

The input is given from Standard Input in the following format:

sx sy tx ty

Output

Print a string S that represents a shortest path for Dolphin.

The i-th character in S should correspond to his i-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from (sx,sy) to (tx,ty) for the first time: (0,0) → (0,1) → (0,2) → (1,2)

Going from (tx,ty) to (sx,sy) for the first time: (1,2) → (1,1) → (1,0) → (0,0)

Going from (sx,sy) to (tx,ty) for the second time: (0,0) → (-1,0) → (-1,1) → (-1,2) → (-1,3) → (0,3) → (1,3) → (1,2)

Going from (tx,ty) to (sx,sy) for the second time: (1,2) → (2,2) → (2,1) → (2,0) → (2,-1) → (1,-1) → (0,-1) → (0,0)

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL


Printf.printf "%d\n" @@ Scanf.scanf "%d %d" @@ fun x y ->
  [x,y,0; -x,y,1; x,-y,1; -x,-y,2] |> List.fold_left (fun z (x,y,s) ->
    if x > y then z else min z (y-x+s)) 101010101010

Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

The input is given from Standard Input in the following format:

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


let rec calc x y =
  if x <= y then
    if x * y <= 0 then min (y-x) (y+x+1) else y-x
  else if x * y >= 0 then 1 + calc (-x) y
  else 1 + abs (abs x - abs y)

let _ = Scanf.scanf "%d %d" @@ calc |> Printf.printf "%d\n"


let rec calc x y =
  if x <= y then
    if x * y < 0 && -x <= y then y - (-x) + 1
    else y - x
  else if abs y <= abs x then 1 + calc (-x) y
  else if x < 0 then 1 + calc (-x) y
  else - y - x + 1

let _ = Scanf.scanf "%d %d" @@ calc |> Printf.printf "%d\n"


Scanf.scanf "%d %d %d %d %d %d %d" (fun ai ao at aj al as_ az ->
    let k = ao               in let ao = ao - ao in
    let k = k + (ai / 2) * 2 in let ai = ai - (ai / 2) * 2 in
    let k = k + (aj / 2) * 2 in let aj = aj - (aj / 2) * 2 in
    let k = k + (al / 2) * 2 in let al = al - (al / 2) * 2 in
    let k = if ai * aj * al = 1 then k + 3 else k in
    Printf.printf "%d\n" k
)

Score : 600 points

Problem Statement

A tetromino is a figure formed by joining four squares edge to edge.
We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively:

Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession are a_I, a_O, a_T, a_J, a_L, a_S and a_Z, respectively.
Snuke will join K of his tetrominos to form a rectangle that is two squares tall and 2K squares wide.
Here, the following rules must be followed:

When placing each tetromino, rotation is allowed, but reflection is not.

Each square in the rectangle must be covered by exactly one tetromino.

No part of each tetromino may be outside the rectangle.

Snuke wants to form as large a rectangle as possible.
Find the maximum possible value of K.

Constraints

0≤a_I,a_O,a_T,a_J,a_L,a_S,a_Z≤10^9

a_I+a_O+a_T+a_J+a_L+a_S+a_Z≥1

Input

The input is given from Standard Input in the following format:

a_I a_O a_T a_J a_L a_S a_Z

Output

Print the maximum possible value of K. If no rectangle can be formed, print 0.

Sample Input 1

2 1 1 0 0 0 0

Sample Output 1

3

One possible way to form the largest rectangle is shown in the following figure:

Sample Input 2

0 0 10 0 0 0 0

Sample Output 2

0

No rectangle can be formed.


let () = Scanf.scanf "%d %d %d %d %d %d %d" @@ fun ai ao at aj al as_ az ->
  Printf.printf "%d\n" @@ ao + max
    ((ai land (-2)) + (aj land (-2)) + (al land (-2)))
    ( if ai <= 0 || aj <= 0 || al <= 0
      then min_int
      else ((ai - 1) land (-2)) + ((aj - 1) land (-2)) + ((al - 1) land (-2)) + 3 )


let () =
  Scanf.scanf "%d %c %d" (fun a op b ->
      if op = '+' then a + b else a - b)
  |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

The input is given from Standard Input in the following format:

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


open Printf
open Scanf

let solve c =
  let ls = ['a'; 'e'; 'i'; 'o'; 'u'] in
  if List.mem c ls then "vowel" else "consonant"

let () =
  scanf "%c " solve |> printf "%s\n"

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

The input is given from Standard Input in the following format:

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


let c = read_line ()
let _ = print_endline @@ if String.contains "aeiou" c.[0] then "vowel" else "consonant"


let () =
  (match read_line () with
   | "a" | "e" | "i" | "o" | "u" -> "vowel"
   | _ -> "consonant")
  |> print_endline


let _ =
	read_line ()
	|> (fun n -> ["a";"i";"u";"e";"o"]
			|> List.map (fun x -> x = n)
			|> List.fold_left (fun x y -> x || y) false)
	|> (fun p ->
		if p
		then print_string "vowel"
		else print_string "constant"
		)


let () =
  Scanf.scanf "%d %d" (fun h _ -> Array.init h (fun _ -> Scanf.scanf " %s" (fun s -> s)))
  |> Array.iter (fun r -> Printf.printf "%s\n%s\n" r r)


let h, w = Scanf.scanf "%d %d\n" (fun a b -> a, b)
let () =
  for i = 1 to h do
    let s = Scanf.scanf "%s\n" (fun a -> a) in
    print_endline s; print_endline s
  done


(* persistent array *)
module PArray : sig
  type 'a t

  val init : int -> (int -> 'a) -> 'a t
  val make : int -> 'a -> 'a t
  val of_list : 'a list -> 'a t
  val get : 'a t -> int -> 'a
  val set : 'a t -> int -> 'a -> 'a t
  (** [set a n x] returns a persistent array replacing element number [n] of [a] with [x].
     [a] is *not* modified. *)
  val length : 'a t -> int
  val to_list : 'a t -> 'a list
  val iter : ('a -> unit) -> 'a t -> unit
  val iteri : (int -> 'a -> unit) -> 'a t -> unit
  val fold_left : ('a -> 'b -> 'a) -> 'a -> 'b t -> 'a
  val fold_right : ('b -> 'a -> 'a) -> 'b t -> 'a -> 'a
end = struct
  type 'a t = 'a data ref
  and 'a data = Arr of 'a array | Diff of int * 'a * 'a t

  let init n f = ref (Arr (Array.init n f))
  let make n v = ref (Arr (Array.make n v))
  let of_list l = ref (Arr (Array.of_list l))

  let rec reroot k = function
    | { contents = Arr a } -> k a
    | { contents = Diff (i, v, t') } as t ->
        reroot (fun a ->
          t' := Diff (i, a.(i), t);
          a.(i) <- v;
          k a) t'
  let reroot k = function
    | { contents = Arr a } -> k a
    | { contents = Diff (_, _, _) } as t ->
        reroot (fun a -> t := Arr a; k a) t

  let rec get t i = reroot (fun a -> a.(i)) t

  let set t i v =
    reroot (fun a ->
      if v = a.(i) then t
      else begin
        let result = ref (Arr a) in
        t := Diff (i, a.(i), result);
        a.(i) <- v;
        result
      end) t

  let length t = reroot Array.length t
  let to_list t = reroot Array.to_list t
  let iter f = reroot (Array.iter f)
  let iteri f = reroot (Array.iteri f)
  let fold_left f x = reroot (Array.fold_left f x)
  let fold_right f t x = reroot (fun a -> Array.fold_right f a x) t
end

(* persistent union-find data structure *)
module PUnionFind : sig
  type t
  type class_

  val make : int -> t
  val find : t -> int -> class_
  val union : t -> int -> int -> t
end = struct
  type t = { rank : int PArray.t; mutable parent : int PArray.t }
  type class_ = int

  let make n = { rank = PArray.make n 0; parent = PArray.init n (fun i -> i) }

  let rec find parent i k =
    let j = PArray.get parent i in
    if i = j then k parent i
    else find parent j (fun parent r -> k (PArray.set parent i r) r)
  let find ({ parent } as h) i = find parent i (fun parent r ->
    h.parent <- parent;
    r)

  let union uf x y =
    let cx = find uf x in
    let cy = find uf y in
    if cx = cy then uf
    else begin
      let rx = PArray.get uf.rank x in
      let ry = PArray.get uf.rank y in
      match compare rx ry with
      | -1 -> { uf with parent = PArray.set uf.parent cx cy }
      | 1 -> { uf with parent = PArray.set uf.parent cy cx }
      | 0 -> { rank = PArray.set uf.rank cx (cx + 1); parent = PArray.set uf.parent cy cx }
    end
end

module SqClassMap = Map.Make (struct
  type t = PUnionFind.class_ * PUnionFind.class_
  let compare = compare
end)

let () =
  let n, k, l = Scanf.scanf "%d %d %d\n" (fun n k l -> n, k, l) in
  let pqs = Array.init k (fun _ -> Scanf.scanf "%d %d\n" (fun p q -> p - 1, q - 1)) in
  let rss = Array.init l (fun _ -> Scanf.scanf "%d %d\n" (fun r s -> r - 1, s - 1)) in
  let ufpq = Array.fold_left (fun u (p, q) -> PUnionFind.union u p q) (PUnionFind.make n) pqs in
  let ufrs = Array.fold_left (fun u (r, s) -> PUnionFind.union u r s) (PUnionFind.make n) rss in
  Array.init n (fun i -> (i, (PUnionFind.find ufpq i, PUnionFind.find ufrs i)))
  |> Array.fold_left (fun m (i, key) ->
      SqClassMap.add key (i :: try SqClassMap.find key m with Not_found -> []) m) SqClassMap.empty
  |> SqClassMap.bindings
  |> List.map (fun (_, xs) -> let n = List.length xs in List.map (fun x -> (x, n)) xs)
  |> List.concat
  |> List.sort (fun (i, _) (j, _) -> compare i j)
  |> List.map snd
  |> List.iter (Printf.printf "%d ")

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

The input is given from Standard Input in the following format:

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

7 4 4
1 2
2 3
2 5
6 7
3 5
4 5
3 4
6 7

Sample Output 3

1 1 2 1 2 2 2


open Scanf
open Printf

let () = scanf "%s %s %s" (fun s1 s2 s3 ->
  "A" ^ String.sub s2 0 1 ^ "C"
  ) |> printf "%s\n"

Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

The input is given from Standard Input in the following format:

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


open Batteries
(* charのlistをstringに *)
let string_of_chars chars =
  let buf = Buffer.create 16 in
  List.iter (Buffer.add_char buf) chars;
  Buffer.contents buf
let _ = Scanf.sscanf (read_line()) "%s %s %s" (fun s1 s2 s3 ->
  [s1.[0]; s2.[0]; s3.[0]]
) |> string_of_chars |> String.uppercase_ascii |> print_endline


let () = Scanf.scanf "AtCoder %s Contest" @@ fun s ->
  Printf.printf "A%cC\n" s.[0]


open Batteries

let solve a b x = Enum.filter (fun i -> i mod x = 0) (a---b) |> Enum.count
let () =
  let [a; b; x] = read_line ()
                  |> String.nsplit ~by:" "
                  |> List.map int_of_string in
  solve a b x |> Printf.printf "%d\n"


Scanf.scanf "%d %d %d" (fun a b x ->
    let ans = if a = 0 then b / x + 1 else b / x - (a - 1) / x in
    Printf.printf "%d\n" ans
)

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

The input is given from Standard Input in the following format:

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


let solve a b x =
	(b / x + 1) - ((a - 1) / x + 1)

let () =
	let [a; b; x] =
		read_line ()
		|> Str.split (Str.regexp " ")
		|> List.map int_of_string
	in
	solve a b x
	|> print_int
	|> print_newline


let () =
  let n, x = Scanf.scanf "%d %d\n" (fun n x -> n, x) in
  let a :: as_ = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  List.fold_left (fun (prev, acc) a ->
    let cost = max 0 (prev + a - x) in
    (max 0 (a - cost), cost + acc)) (a, 0) as_
  |> snd
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

There are N boxes arranged in a row.
Initially, the i-th box from the left contains a_i candies.

Snuke can perform the following operation any number of times:

Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

Any two neighboring boxes contain at most x candies in total.

Find the minimum number of operations required to achieve the objective.

Constraints

2 ≤ N ≤ 10^5

0 ≤ a_i ≤ 10^9

0 ≤ x ≤ 10^9

Input

The input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3 3
2 2 2

Sample Output 1

1

Eat one candy in the second box.
Then, the number of candies in each box becomes (2, 1, 2).

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11

For example, eat six candies in the second box, two in the fourth box, and three in the sixth box.
Then, the number of candies in each box becomes (1, 0, 1, 0, 0, 1).

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0

The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10

All the candies need to be eaten.


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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d\n" @@ fun a -> a in
  Array.to_list as_
  |> List.map (fun a -> a lxor (a - 1))
  |> List.sort_uniq compare
  |> List.fold_left (fun m a ->
      IntMap.fold (fun x n m ->
        IntMap.add (x lxor a)
          (min (1 + n) @@
            try IntMap.find (x lxor a) m
            with Not_found -> max_int) m) m m)
    (IntMap.singleton (Array.fold_left ( lxor ) 0 as_) 0)
  |> fun m ->
      Printf.printf "%d\n" @@
        try IntMap.find 0 m with Not_found -> -1

Score : 500 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

A cheetah and a cheater are going to play the game of Nim.
In this game they use N piles of stones.
Initially the i-th pile contains a_i stones.
The players take turns alternately, and the cheetah plays first.
In each turn, the player chooses one of the piles, and takes one or more stones from the pile.
The player who can't make a move loses.

However, before the game starts, the cheater wants to cheat a bit to make sure that he can win regardless of the moves by the cheetah.
From each pile, the cheater takes zero or one stone and eats it before the game.
In case there are multiple ways to guarantee his winning, he wants to minimize the number of stones he eats.

Compute the number of stones the cheater will eat.
In case there is no way for the cheater to win the game even with the cheating, print -1 instead.

Constraints

1 ≤ N ≤ 10^5

2 ≤ a_i ≤ 10^9

Input

The input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the answer.

Sample Input 1

3
2
3
4

Sample Output 1

3

The only way for the cheater to win the game is to take stones from all piles and eat them.

Sample Input 2

3
100
100
100

Sample Output 2

-1


open Printf
open Scanf

let solve r1 r2 = r1 *. r2 /. (r1 +. r2)

let () =
  scanf "%f %f " solve |> printf "%.10f\n"

Score : 100 points

Problem Statement

In an electric circuit, when two resistors R_1 and R_2 are connected in parallel, the equivalent resistance R_3 can be derived from the following formula:

\frac{1}{R_1} + \frac{1}{R_2} = \frac{1}{R_3}

Given R_1 and R_2, find R_3.

Constraints

1 \leq R_1, R_2 \leq 100

R_1 and R_2 are integers.

Input

The input is given from Standard Input in the following format:

R_1 R_2

Output

Print the value of R_3.

The output is considered correct if the absolute or relative error is at most 10^{-6}.

Sample Input 1

2 3

Sample Output 1

1.2000000000

Sample Input 2

100 99

Sample Output 2

49.7487437186


let r1, r2 = Scanf.scanf " %f %f" @@ fun a b -> a, b
let _ = Printf.printf "%.10f\n" @@ r1 *. r2 /. (r1 +. r2)


Scanf.(scanf "%d %d" @@ fun h w -> print_endline @@ if Array.(fold_left (+) 0 @@ init (h * w) @@ fun _ -> scanf " %c" @@ function '#' -> 1 | _ -> 0) = h + w - 1 then "Possible" else "Impossible")

Score : 200 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).

You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is # if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is .. Please determine whether it is possible that Shik only uses right and down moves in all steps.

Constraints

2 \leq H, W \leq 8

a_{i,j} is either # or ..

There exists a valid sequence of moves for Shik to generate the map a.

Input

The input is given from Standard Input in the following format:

H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}

Output

If it is possible that Shik only uses right and down moves, print Possible. Otherwise, print Impossible.

Sample Input 1

4 5
##...
.##..
..##.
...##

Sample Output 1

Possible

The matrix can be generated by a 7-move sequence: right, down, right, down, right, down, and right.

Sample Input 2

5 3
###
..#
###
#..
###

Sample Output 2

Impossible

Sample Input 3

4 5
##...
.###.
.###.
...##

Sample Output 3

Impossible


open Printf
open Scanf

let () =
  let (a,b,c) = scanf " %d %d %d" (fun x y z -> (x,y,z)) in
  if a + b == c || b + c == a || c + a == b
  then print_endline "Yes"
  else print_endline "No"

Score : 100 points

Problem Statement

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

1 ≦ a, b, c ≦ 100

Input

The input is given from Standard Input in the following format:

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.

Sample Input 1

10 30 20

Sample Output 1

Yes

Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.

Sample Input 2

30 30 100

Sample Output 2

No

In this case, the student who gets the pack with 100 candies always has more candies than the other.

Note that every pack must be given to one of them.

Sample Input 3

56 25 31

Sample Output 3

Yes


let a, b, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = print_endline @@ if a + b = c || b + c = a || c + a = b then "Yes" else "No"


let () = Scanf.scanf "%d %d %d"
(fun a b c -> a+b==c || a==b+c || c+a==b)
|> (fun a -> if a then "Yes" else "No")
|> Printf.printf "%s\n"


(* O(n) *)
Scanf.scanf " %d %d %d" @@ fun w h n ->
  let left = ref 0 in
  let right = ref w in
  let down = ref 0 in
  let up = ref h in
  for i = 1 to n do
    Scanf.scanf " %d %d %d" @@ fun x y -> function
    | 1 -> left := max !left x
    | 2 -> right := min !right x
    | 3 -> down := max !down y
    | 4 -> up := min !up y
    | _ -> assert false
  done;
  let w2 = max 0 @@ !right - !left in
  let h2 = max 0 @@ !up - !down in
  Printf.printf "%d\n" @@ w2 * h2

Score : 200 points

Problem Statement

There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white.

Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) point was (x_i, y_i).

Then, he created an integer sequence a of length N, and for each 1 ≦ i ≦ N, he painted some region within the rectangle black, as follows:

If a_i = 1, he painted the region satisfying x < x_i within the rectangle.

If a_i = 2, he painted the region satisfying x > x_i within the rectangle.

If a_i = 3, he painted the region satisfying y < y_i within the rectangle.

If a_i = 4, he painted the region satisfying y > y_i within the rectangle.

Find the area of the white region within the rectangle after he finished painting.

Constraints

1 ≦ W, H ≦ 100

1 ≦ N ≦ 100

0 ≦ x_i ≦ W (1 ≦ i ≦ N)

0 ≦ y_i ≦ H (1 ≦ i ≦ N)

W, H (21:32, added), x_i and y_i are integers.

a_i (1 ≦ i ≦ N) is 1, 2, 3 or 4.

Input

The input is given from Standard Input in the following format:

W H N
x_1 y_1 a_1
x_2 y_2 a_2
:
x_N y_N a_N

Output

Print the area of the white region within the rectangle after Snuke finished painting.

Sample Input 1

5 4 2
2 1 1
3 3 4

Sample Output 1

9

The figure below shows the rectangle before Snuke starts painting.

First, as (x_1, y_1) = (2, 1) and a_1 = 1, he paints the region satisfying x < 2 within the rectangle:

Then, as (x_2, y_2) = (3, 3) and a_2 = 4, he paints the region satisfying y > 3 within the rectangle:

Now, the area of the white region within the rectangle is 9.

Sample Input 2

5 4 3
2 1 1
3 3 4
1 4 2

Sample Output 2

0

It is possible that the whole region within the rectangle is painted black.

Sample Input 3

10 10 5
1 6 1
4 1 3
6 9 4
9 4 2
3 1 3

Sample Output 3

64


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

    let rec loop i mi ma best count =
        if i = n then count else
            if a.(i) < mi then loop (i + 1) a.(i) ma best count else
                if a.(i) - mi = best then loop (i + 1) mi ma best (count + 1) else
                    if a.(i) > ma then loop (i + 1) mi a.(i) (a.(i) - mi) 1 else
                        loop (i + 1) mi ma best count
    in
    loop 0 1_000_000_000 0 (-1) 0 |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

There are N towns located in a line, conveniently numbered 1 through N. Takahashi the merchant is going on a travel from town 1 to town N, buying and selling apples.

Takahashi will begin the travel at town 1, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town i (i < N), move to town i + 1.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for A_i yen (the currency of Japan) at town i (1 ≦ i ≦ N), where A_i are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most T. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change A_i into another arbitrary non-negative integer A_i' for any town i, any number of times. The cost of performing this operation is |A_i - A_i'|. After performing this operation, different towns may have equal values of A_i.

Aoki's objective is to decrease Takahashi's expected profit by at least 1 yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least 1 yen.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

A_i are distinct.

2 ≦ T ≦ 10^9

In the initial state, Takahashi's expected profit is at least 1 yen.

Input

The input is given from Standard Input in the following format:

N T
A_1 A_2 ... A_N

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least 1 yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of 150 yen as follows:

Move from town 1 to town 2.

Buy one apple for 50 yen at town 2.

Move from town 2 to town 3.

Sell one apple for 200 yen at town 3.

If, for example, Aoki changes the price of an apple at town 2 from 50 yen to 51 yen, Takahashi will not be able to achieve the profit of 150 yen. The cost of performing this operation is 1, thus the answer is 1.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town 3 from 200 yen to 199 yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

10 100
7 10 4 5 9 3 6 8 2 1

Sample Output 3

2


module M = Map.Make(struct type t = int let compare = (-) end)
let find_default k m v = try M.find k m with Not_found -> v

let () =
  Scanf.scanf "%d %d" @@ fun n t ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x)) in
  let d = Array.fold_left (fun (d, l) e -> (max d (e-l), min e l)) (0, a.(0)) a |> fst in
  a |> Array.fold_left (fun (z, m) v ->
    let p = find_default (v-d) m 0 in
    let c = find_default v m 0 in
    (z+p, M.add v (c+1) m)) (0, M.empty)
  |> fst |> Printf.printf "%d\n"


let () = Scanf.scanf "%d %d\n" @@ fun n t ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let maximum = Array.make n (as_.(n - 1), n - 1) in
  for i = n - 2 downto 0 do
    maximum.(i) <-
      if as_.(i) < fst maximum.(i + 1) then maximum.(i + 1)
      else (as_.(i), i)
  done;
  Array.to_list as_
  |> List.mapi (fun i a -> (fst maximum.(i) - a, snd maximum.(i)))
  |> List.fold_left (fun (maximum, is) (d, i) ->
      match compare d maximum with
      | -1 -> (maximum, is)
      | 0 ->  (d, i :: is)
      | 1 ->  (d, [i])) (min_int, [])
  |> snd
  |> List.sort_uniq compare
  |> List.length
  |> Printf.printf "%d\n"


let rec tabulate n f =
  let rec loop acc m =
    if m < n then loop (f m :: acc) (m + 1)
    else List.rev acc in
  loop [] 0

let () =
  let n, _ = Scanf.scanf "%d %d\n" (fun n t -> n, t) in
  tabulate n (fun _ -> Scanf.scanf "%d " (fun a -> a))
    |> List.fold_left (fun (acc, min, mins, maxs, pred) a ->
        if a < pred then ((min, pred, mins, maxs) :: acc, a, 0, 0, a)
        else (acc, min, (if a = min then mins + 1 else mins), (if a = pred then maxs + 1 else 0) , a)) ([], max_int, 0, 0, max_int)
    |> (fun (acc, min, mins, maxs, pred) -> (min, pred, mins, maxs) :: acc)
    |> (fun ranges ->
        let max = List.fold_left max 0 (List.map (fun (min, pred, _, _) -> pred - min) ranges) in
        List.filter (fun (min, pred, _, _) -> pred - min = max) ranges)
    |> List.map (fun (_, _, mins, maxs) -> min mins maxs + 1)
    |> List.fold_left ( + ) 0
    |> Printf.printf "%d\n"


let s = read_line ();;

let c = ref 0 in
  for i = 1 to String.length s - 1 do
    if s.[i] != s.[i-1] then c := !c +1
  done;
  print_int !c

Score : 300 points

Problem Statement

Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones between the new white stone and another white stone, turn into white stones, and vice versa.

In the middle of a game, something came up and Saburo has to leave the game. The state of the board at this point is described by a string S. There are |S| (the length of S) stones on the board, and each character in S represents the color of the i-th (1 ≦ i ≦ |S|) stone from the left. If the i-th character in S is B, it means that the color of the corresponding stone on the board is black. Similarly, if the i-th character in S is W, it means that the color of the corresponding stone is white.

Jiro wants all stones on the board to be of the same color. For this purpose, he will place new stones on the board according to the rules. Find the minimum number of new stones that he needs to place.

Constraints

1 ≦ |S| ≦ 10^5

Each character in S is B or W.

Input

The input is given from Standard Input in the following format:

S

Output

Print the minimum number of new stones that Jiro needs to place for his purpose.

Sample Input 1

BBBWW

Sample Output 1

1

By placing a new black stone to the right end of the row of stones, all white stones will become black. Also, by placing a new white stone to the left end of the row of stones, all black stones will become white.

In either way, Jiro's purpose can be achieved by placing one stone.

Sample Input 2

WWWWWW

Sample Output 2

0

If all stones are already of the same color, no new stone is necessary.

Sample Input 3

WBWBWBWBWB

Sample Output 3

9


Scanf.scanf "%d %d" (fun n x ->
    let d = 2 * n - 1 in
    let prt a b = for i = a to b do Printf.printf "%d\n" i done in
    if x = 1 || x = d then print_endline "No" else (
        print_endline "Yes";
        if x = n then prt 1 d else
        if x < n then (
            prt 1 (x - 2);
            prt (x + 1) n;
            prt (x - 1) x;
            prt (n + 1) d;
        ) else (
            prt 1 (n - 1);
            prt x (x + 1);
            prt n (x - 1);
            prt (x + 2) d;
        )
    )
)

Score : 400 points

Problem Statement

We have a pyramid with N steps, built with blocks.
The steps are numbered 1 through N from top to bottom.
For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally.
The pyramid is built so that the blocks at the centers of the steps are aligned vertically.

A pyramid with N=4 steps

Snuke wrote a permutation of (1, 2, ..., 2N-1) into the blocks of step N.
Then, he wrote integers into all remaining blocks, under the following rule:

The integer written into a block b must be equal to the median of the three integers written into the three blocks directly under b, or to the lower left or lower right of b.

Writing integers into the blocks

Afterwards, he erased all integers written into the blocks.
Now, he only remembers that the integer written into the block of step 1 was x.

Construct a permutation of (1, 2, ..., 2N-1) that could have been written into the blocks of step N, or declare that Snuke's memory is incorrect and such a permutation does not exist.

Constraints

2≤N≤10^5

1≤x≤2N-1

Input

The input is given from Standard Input in the following format:

N x

Output

If no permutation of (1, 2, ..., 2N-1) could have been written into the blocks of step N, print No.

Otherwise, print Yes in the first line, then print 2N-1 lines in addition.

The i-th of these 2N-1 lines should contain the i-th element of a possible permutation.

Sample Input 1

4 4

Sample Output 1

Yes
1
6
3
7
4
5
2

This case corresponds to the figure in the problem statement.

Sample Input 2

2 1

Sample Output 2

No

No matter what permutation was written into the blocks of step N, the integer written into the block of step 1 would be 2.


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

let () = print_string (if x < 3 || x > 2*n - 3 then "No" else "Yes")


let head3 lst =
	match lst with
	| e1 :: e2 :: e3 :: _ -> [e1; e2; e3]
	| _ -> []

let median [a; b; c] =
	let [_; m; _] = List.sort compare [a; b; c] in m

let upstairs step =
	let rec loop lst acc =
		match head3 lst with
		| [] -> acc
		| xs -> loop (List.tl lst) (xs :: acc)
	in
	loop step []
	|> List.map median

let solve step =
	let rec loop step =
		(* step is never [] *)
		match step with
		| [_] -> step
		| _ -> loop (upstairs step)
	in
	List.hd (loop step)

let () =
	let n = read_int () in
	let a =
		read_line ()
		|> Str.split (Str.regexp " ")
		|> List.map int_of_string
	in
	solve a
	|> print_int
	|> print_newline

Score : 1300 points

Problem Statement

We have a pyramid with N steps, built with blocks.
The steps are numbered 1 through N from top to bottom.
For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally.
The pyramid is built so that the blocks at the centers of the steps are aligned vertically.

A pyramid with N=4 steps

Snuke wrote a permutation of (1, 2, ..., 2N-1) into the blocks of step N.
Then, he wrote integers into all remaining blocks, under the following rule:

The integer written into a block b must be equal to the median of the three integers written into the three blocks directly under b, or to the lower left or lower right of b.

Writing integers into the blocks

Afterwards, he erased all integers written into the blocks.
Now, he only remembers that the permutation written into the blocks of step N was (a_1, a_2, ..., a_{2N-1}).

Find the integer written into the block of step 1.

Constraints

2≤N≤10^5

(a_1, a_2, ..., a_{2N-1}) is a permutation of (1, 2, ..., 2N-1).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{2N-1}

Output

Print the integer written into the block of step 1.

Sample Input 1

4
1 6 3 7 4 5 2

Sample Output 1

4

This case corresponds to the figure in the problem statement.

Sample Input 2

2
1 2 3

Sample Output 2

2


open Scanf
open Printf

let () = scanf "%d %d %d" (fun a b c ->
  if a = b && b = c then 1
  else if a = b || a = c || b = c then 2
  else 3
  ) |> printf "%d\n"

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

The input is given from Standard Input in the following format:

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


Scanf.scanf "%d %d %d" (fun a b c ->
    Printf.printf "%d\n" @@
    if a = b then (
        if b = c then 1 else 2
    ) else if a = c || b = c then 2 else 3
)


open Batteries
module SS = Set.Make(Int)
let s = SS.empty
let s = Scanf.sscanf (read_line()) "%d %d %d" (fun a b c ->
  List.fold_right SS.add [a;b;c] s
)
let _ = Printf.printf "%d\n" (List.length @@ SS.elements s)


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = Printf.printf "%d\n" @@ Array.fold_left ( * ) k @@ Array.make (n - 1) @@ k - 1

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

The input is given from Standard Input in the following format:

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


Scanf.scanf " %d %d" @@ fun n k ->
  let ans = ref k in
  for i = 2 to n do
    ans := !ans * (k - 1)
  done;
  Printf.printf "%d\n" !ans


let () =
  let n,k = Scanf.scanf "%d %d " (fun a b -> a,b) in
  let pow a n =
    let rec aux res a n =
      if n = 0 then res else aux (res*a) a (n-1)
    in
    aux 1 a n
  in
  Printf.printf "%d\n" @@
  pow (k-1) (n-1) * k


let rec power m n = match n with
	| 0 -> 1
	| 1 -> m
	| x -> m * power m (n - 1)

let solve n k = k * power (k - 1) (n - 1)

let _ =
	Scanf.scanf "%d %d" (fun x y -> solve x y) |> Printf.printf "%d"


let () = Scanf.scanf "%d\n" @@ fun n ->
  let tas = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun t a -> t, a in
  let x, y =
    Array.fold_left (fun (x, y) (t, a) ->
      let i = (x + t - 1) / t in
      let j = (y + a - 1) / a in
      (t * max i j, a * max i j)) tas.(0) tas in
  Printf.printf "%d\n" @@ x + y

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

The input is given from Standard Input in the following format:

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


let step (a, b) (r1, r2) =
  let ta = (a + r1 - 1) / r1 * r1 in
  let tb = ta / r1 * r2 in
  let m = (b + tb - 1) / tb in
  (m * ta, m * tb)
let n = Scanf.scanf "%d" (fun x -> x)
let () =
  Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y))
  |> Array.fold_left step (1, 1)
  |> (fun (a, b) -> Printf.printf "%d\n" (a+b))


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

let rec solve i sumt suma =
  if i = 0 then (sumt + suma)
  else
    let t, a = Scanf.scanf "%d %d\n" (fun x y -> x, y) in
    let x =
      if (suma / a) < (sumt / t) then
        (if sumt mod t = 0 then sumt / t else (sumt / t) + 1)
      else
        (if suma mod a = 0 then suma / a else (suma / a) + 1)
    in
    solve (i - 1) (t * x) (a * x)

let () = solve n 1 1 |> Printf.printf "%d\n"


let ans s =
  let n = String.length s in
  let rec count i ret =
    if i = n then ret
    else if s.[i] = 'p' then count (i+1) (ret+1)
    else count (i+1) ret in
  let p = count 0 0
  in n/2 - p;;

Scanf.scanf "%s" (fun s -> print_int (ans s))

Score : 300 points

Problem Statement

AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:

(※) After each turn, (the number of times the player has played Paper)≦(the number of times the player has played Rock).

Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.

(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)

With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.

The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1≦i≦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1≦i≦N) character of s in p, TopCoDeer will play Paper in the i-th turn.

Constraints

1≦N≦10^5

N=|s|

Each character in s is g or p.

The gestures represented by s satisfy the condition (※).

Input

The input is given from Standard Input in the following format:

s

Output

Print the AtCoDeer's maximum possible score.

Sample Input 1

gpg

Sample Output 1

0

Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.

Sample Input 2

ggppgggpgg

Sample Output 2

2

For example, consider playing gestures in the following order: Rock, Paper, Rock, Paper, Rock, Rock, Paper, Paper, Rock, Paper. This strategy earns three victories and suffers one defeat, resulting in the score of 2, which is the maximum possible score.


let s = read_line ()
let f s x = let n = ref 0 in String.iter (fun c -> if c = x then incr n) s; !n
let _ = Printf.printf "%d\n" @@ String.length s / 2 - f s 'p'


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

    let rec loop i cur acc =
        if i = n then acc else
            if a.(i) = cur then loop (i + 1) (cur + 1) acc  else
            if a.(i) < cur then loop (i + 1) cur acc else
                loop (i + 1) cur (acc + (a.(i) - 1) / cur)
    in
    loop 1 2 (a.(0) - 1) |> Printf.printf "%d\n"
)

Score : 700 points

Problem Statement

N people are waiting in a single line in front of the Takahashi Store. The cash on hand of the i-th person from the front of the line is a positive integer A_i.

Mr. Takahashi, the shop owner, has decided on the following scheme: He picks a product, sets a positive integer P indicating its price, and shows this product to customers in order, starting from the front of the line. This step is repeated as described below.

At each step, when a product is shown to a customer, if price P is equal to or less than the cash held by that customer at the time, the customer buys the product and Mr. Takahashi ends the current step. That is, the cash held by the first customer in line with cash equal to or greater than P decreases by P, and the next step begins.

Mr. Takahashi can set the value of positive integer P independently at each step.

He would like to sell as many products as possible. However, if a customer were to end up with 0 cash on hand after a purchase, that person would not have the fare to go home. Customers not being able to go home would be a problem for Mr. Takahashi, so he does not want anyone to end up with 0 cash.

Help out Mr. Takahashi by writing a program that determines the maximum number of products he can sell, when the initial cash in possession of each customer is given.

Constraints

1 ≦ | N | ≦ 100000

1 ≦ A_i ≦ 10^9(1 ≦ i ≦ N)

All inputs are integers.

Input

Inputs are provided from Standard Inputs in the following form.

N
A_1
:
A_N

Output

Output an integer representing the maximum number of products Mr. Takahashi can sell.

Sample Input 1

3
3
2
5

Sample Output 1

3

As values of P, select in order 1, 4, 1.

Sample Input 2

15
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9

Sample Output 2

18


Scanf.scanf "%s" (fun s ->
    let n = String.length s in

    let rec loop i tame acc =
        if i = n then acc else
            if s.[i] = 'S' then loop (i + 1) (tame + 1) (acc + 1) else
                if tame > 0 then loop (i + 1) (tame - 1) (acc - 1) else
                    loop (i + 1) tame (acc + 1)
    in
    loop 0 0 0 |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

The input is given from Standard Input in the following format:

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let d = Array.fold_left max min_int as_ in
  let count_as = Array.make n 0 in
  Array.iter (fun a -> count_as.(a) <- 1 + count_as.(a)) as_;
  print_endline @@
  if
    2 <= count_as.(d) &&
    Array.fold_right (fun n -> ( && ) (n = 0))
      (Array.sub count_as 0 ((d + 1) / 2)) true &&
    count_as.((d + 1) / 2) = 1 + d mod 2 &&
    Array.fold_left ( && ) true
      (Array.init (d / 2)
        (fun i -> count_as.((d + 1) / 2 + i) <= count_as.((d + 1) / 2 + i + 1)))
  then "Possible"
  else "Impossible"

Score : 700 points

Problem Statement

Aoki loves numerical sequences and trees.

One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree.

Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1.

Determine whether such a tree exists.

Constraints

2 ≦ N ≦ 100

1 ≦ a_i ≦ N-1

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If there exists a tree that satisfies the condition, print Possible. Otherwise, print Impossible.

Sample Input 1

5
3 2 2 3 3

Sample Output 1

Possible

The diagram above shows an example of a tree that satisfies the conditions. The red arrows show paths from each vertex to the farthest vertex from it.

Sample Input 2

3
1 1 2

Sample Output 2

Impossible

Sample Input 3

10
1 2 2 2 2 2 2 2 2 2

Sample Output 3

Possible

Sample Input 4

10
1 1 2 2 2 2 2 2 2 2

Sample Output 4

Impossible

Sample Input 5

6
1 1 1 1 1 5

Sample Output 5

Impossible

Sample Input 6

5
4 3 2 3 4

Sample Output 6

Possible


open Hashtbl
let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun i -> Scanf.scanf " %d" @@ fun a -> min i @@ a - 1, max i @@ a - 1
let h = create n
let _ = Array.iteri (fun i a -> replace h a @@ try find h a + 1 with _ -> 1) a_s; fold (fun _ c s -> s + if c = 2 then 1 else 0) h 0 |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the number of the friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


let s = read_line ()
let k = ref @@ read_int ()
let f c = Char.(chr @@ (code c - 97 + !k) mod 26 + 97)
let _ = String.(mapi (fun i c -> let d = 123 - Char.code c in if i = length s - 1 then f c else if d <= min 25 !k then (k := !k - d; 'a') else c) s) |> print_endline

Score : 400 points

Problem Statement

Mr. Takahashi has a string s consisting of lowercase English letters.
He repeats the following operation on s exactly K times.

Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly K operations on s.
Find the such string.

Constraints

1≤|s|≤10^5

All letters in s are lowercase English letters.

1≤K≤10^9

Input

The input is given from Standard Input in the following format:

s
K

Output

Print the lexicographically smallest string after performing exactly K operations on s.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly K operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap


let s = read_line ()
let k = ref @@ read_int ()
let f c = Char.(chr @@ (code c - 97 + !k) mod 26 + 97)
let _ = String.(mapi (fun i c -> let d = (123 - Char.code c) mod 26 in if i = length s - 1 then f c else if d < !k then (k := !k - d; 'a') else c) s) |> print_endline


open Scanf
open Printf

let () = scanf "%d %d %d" (fun a b h -> (a + b) * h / 2
  ) |> printf "%d\n"

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

The input is given from Standard Input in the following format:

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


let a = read_int ()
let b = read_int ()
let h = read_int ()
let () =
  print_int ((a + b) * h / 2);
  print_newline()


Scanf.scanf "%s %s %s" (fun sa sb sc ->
    let rec loop cur ai bi ci =
        match cur with
        | 'a' -> if ai = String.length sa then "A" else loop sa.[ai] (ai + 1) bi ci
        | 'b' -> if bi = String.length sb then "B" else loop sb.[bi] ai (bi + 1) ci
        | 'c' -> if ci = String.length sc then "C" else loop sc.[ci] ai bi (ci + 1)
        | _ -> failwith "??"
    in
    loop 'a' 0 0 0 |> print_endline
)

Score : 200 points

Problem Statement

Alice, Bob and Charlie are playing Card Game for Three, as below:

At first, each of the three players has a deck consisting of some number of cards. Each card has a letter a, b or c written on it. The orders of the cards in the decks cannot be rearranged.

The players take turns. Alice goes first.

If the current player's deck contains at least one card, discard the top card in the deck. Then, the player whose name begins with the letter on the discarded card, takes the next turn. (For example, if the card says a, Alice takes the next turn.)

If the current player's deck is empty, the game ends and the current player wins the game.

You are given the initial decks of the players.
More specifically, you are given three strings S_A, S_B and S_C. The i-th (1≦i≦|S_A|) letter in S_A is the letter on the i-th card in Alice's initial deck. S_B and S_C describes Bob's and Charlie's initial decks in the same way.

Determine the winner of the game.

Constraints

1≦|S_A|≦100

1≦|S_B|≦100

1≦|S_C|≦100

Each letter in S_A, S_B, S_C is a, b or c.

Input

The input is given from Standard Input in the following format:

S_A
S_B
S_C

Output

If Alice will win, print A. If Bob will win, print B. If Charlie will win, print C.

Sample Input 1

aca
accc
ca

Sample Output 1

A

The game will progress as below:

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice discards the top card in her deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, c. Charlie takes the next turn.

Charlie discards the top card in his deck, a. Alice takes the next turn.

Alice discards the top card in her deck, a. Alice takes the next turn.

Alice's deck is empty. The game ends and Alice wins the game.

Sample Input 2

abcb
aacb
bccc

Sample Output 2

C


let ans sa sb sc =
  let na = String.length sa
  and nb = String.length sb
  and nc = String.length sc
  in
  let rec f ia ib ic = function
    'a' -> if ia = na then "A"  else f (ia+1) ib ic sa.[ia]
  | 'b' -> if ib = nb then "B" else f ia (ib+1) ic sb.[ib]
  | _ -> if ic = nc then "C" else f ia ib (ic+1) sc.[ic]
  in f 0 0 0 'a';;

Scanf.scanf "%s\n%s\n%s" (fun sa sb sc -> print_string (ans sa sb sc))


let ss = Array.init 3 @@ fun _ -> read_line ()
let i_s = Array.make 3 0
let rec f c = String.(let j = index "abc" c in if i_s.(j) >= length ss.(j) then Printf.printf "%c\n" "ABC".[j] else (i_s.(j) <- i_s.(j) + 1; f ss.(j).[i_s.(j) - 1]))
let _ = i_s.(0) <- 1; f ss.(0).[0]


(* O(2^|s|) *)
let s = read_line () in
let ds = Array.to_list @@ Array.init (String.length s) @@ fun i -> int_of_char s.[i] - 48 in
let rec calc sum n = function
| [] -> sum + n
| d :: ds2 -> calc (sum + n) d ds2 + calc sum (10 * n + d) ds2 in
calc 0 (List.hd ds) (List.tl ds) |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

The input is given from Standard Input in the following format:

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944