open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = List.range n `To m
let (++-) n m = if n >= m then List.range n `Downto m else []
let (++^) n m = if n < m then List.range n `To (pred m) else []

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then []
  else List.map (fun _ -> scan fmt f) (1 ++ n)

let scan_list ?sep cnv =
  let line = read_line () in
  (match sep with
   | None -> List.map String.of_char @@ String.to_list line
   | Some sep -> String.split_on_char sep line)
  |> List.map cnv

let scan_array ?sep cnv = Array.of_list @@ scan_list ?sep cnv

let scan_matrix n m e ?sep conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (0 ++^ n)
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list ?sep conv);
  arr

let atoi c = Char.code c - Char.code '0'

let rec powerset = function
  | [] -> [[]]
  | hd::tl ->
    let pws =  powerset tl in
    pws @ ListL.map pws ~f:(fun pw -> hd::pw)

let permutations l =
  let rec interleave x = function
    | [] -> [[x]]
    | (hd::tl) as l ->
      (x::l) :: (interleave x tl |> ListL.map ~f:(fun l -> hd::l)) in
  let rec aux = function
    | [] -> [[]]
    | a::rest ->
      aux rest |> ListL.map ~f:(interleave a) |> List.concat in
  aux l

let intersection l =
  EnumL.filter ~f:(fun x -> EnumL.exists ~f:((=) x) @@ Enum.clone l)

let zip l m =
  let n = min (List.length l) (List.length m) in
  List.combine (List.take n l) (List.take n m)

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let between n x m = n <= x && x < m

let (n,k) = scan "%d %d" Tuple2.make
let arr = scan_array ~sep:' ' Int.of_string

let () =
  let sets = powerset (0++^n)
             |> ListL.filter ~f:(fun l -> List.length l = k)
             |> ListL.map ~f:(List.sort Int.compare) in
  ListL.map sets ~f:(fun set ->
      let hd = List.hd set in
      let height = Array.sub arr 0 hd |> ArrayL.fold_left ~init:0 ~f:max in
      ListL.fold_left set ~init:(height, 0)
        ~f:(fun (pred, n) i ->
            if pred < arr.(i) then (arr.(i), n) else (pred+1, n + pred+1 - arr.(i))))
  |> List.map Tuple2.second
  |> List.min
  |> Printf.printf "%d\n"

Max Score: 350 Points

Problem Statement

There are N buildings along the line. The i-th building from the left is colored in color i, and its height is currently a_i meters.

Chokudai is a mayor of the city, and he loves colorful thigs. And now he wants to see at least K buildings from the left.

You can increase height of buildings, but it costs 1 yens to increase 1 meters. It means you cannot make building that height is not integer.

You cannot decrease height of buildings.

Calculate the minimum cost of satisfying Chokudai's objective.

Note: "Building i can see from the left" means there are no j exists that (height of building j) ≥ (height of building i) and j < i.

Input Format

N K
a_1 a_2 a_3 ... a_N

Output Format

Print the minimum cost in one line. In the end put a line break.

Constraints

1 ≤ K ≤ N ≤ 15

1 ≤ a_i ≤ 10^9

Scoring

Subtask 1 [120 points]

N = K

Subtask 2 [90 points]

N ≤ 5

a_i ≤ 7

Subtask 3 [140 points]

There are no additional constraints.

Sample Input 1

5 5
3949 3774 3598 3469 3424

Sample Output 1

1541

The optimal solution is (height of buildings from the left) = [3949, 3950, 3951, 3952, 3953].

Sample Input 2

5 3
7 4 2 6 4

Sample Output 2

7

The optimal solution is (height of buildings from the left) = [7, 8, 2, 9, 4].


let _ =
  let nk = List.map int_of_string @@ Str.split (Str.regexp "[ \t]+") (read_line ()) in
  let hs = List.map int_of_string @@ Str.split (Str.regexp "[ \t]+") (read_line ()) in
  let rec f ph ls acc =
    match ls with
      [] -> acc
    | (h::t) -> if (ph + 1) <= h then f h t acc else f (ph + 1) t (acc + ph + 1 - h) in
  print_endline @@ string_of_int @@ f (List.hd hs) (List.tl hs) 0

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

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.sscanf (read_line ()) "%d %d %d" (fun a b c ->
  if b-a=c-b then print_string "YES"
  else print_string "NO"
);;

Score : 100 points

Problem Statement

Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right.
We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print YES if the arrangement of the poles is beautiful; print NO otherwise.

Sample Input 1

2 4 6

Sample Output 1

YES

Since 4-2 = 6-4, this arrangement of poles is beautiful.

Sample Input 2

2 5 6

Sample Output 2

NO

Since 5-2 \neq 6-5, this arrangement of poles is not beautiful.

Sample Input 3

3 2 1

Sample Output 3

YES

Since 1-2 = 2-3, this arrangement of poles is beautiful.


let () =
	let o = read_line () in
	let e = read_line () in
	let o_len = String.length o in
	let e_len = String.length e in
	for i = 0 to e_len - 1 do
		print_char o.[i];
		print_char e.[i]
	done;
	if o_len > e_len then begin
		print_char o.[o_len - 1];
		print_newline ()
	end else
		print_newline ()

Score : 200 points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

O and E consists of lowercase English letters (a - z).

1 \leq |O|,|E| \leq 50

|O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


let c = 1000000007

let ans n m =
  let rec sum i n s =
    if i = n then s
    else
      let x = Scanf.scanf " %d" (fun x -> x) in
      sum (i + 1) n ((s + (2 * i - n + 1) * x mod c) mod c)
  in
  sum 0 n 0 * sum 0 m 0 mod c

let () = Scanf.scanf "%d %d" (fun n m -> print_int (ans n m))

Score : 500 points

Problem Statement

On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.

For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.

That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.

Constraints

2 \leq n,m \leq 10^5

-10^9 \leq x_1 < ... < x_n \leq 10^9

-10^9 \leq y_1 < ... < y_m \leq 10^9

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m

Output

Print the total area of the rectangles, modulo 10^9+7.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


let n = 1000000007
let ( *^ ) x y = x * y mod n

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let xs = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let ys = Array.init m (fun _ -> Scanf.scanf "%d " (fun y -> y)) in
  Printf.printf "%d\n" @@ (xs.(n - 1) - xs.(0)) *^ (ys.(m - 1) - ys.(0)) *^ (n - 1) *^ (m - 1)


let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init (3 * n) (fun _ -> Scanf.scanf "%d " (fun n -> n)) in
  Array.sort (fun x y -> compare y x) as_;
  Printf.printf "%d\n" (Array.fold_left ( + ) 0 (Array.init n (fun i -> as_.(2 * i + 1))))

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


let fst3 (a,b,c) = a
let () = Scanf.scanf "%d %d" @@ fun n m ->
  let es = Array.init m (fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a-1, b-1) in
  Scanf.scanf " %d" @@ fun q ->

  let qa =
    let t = Array.init 11 (fun _ -> []) in
    for i = 0 to q-1 do
      Scanf.scanf " %d %d %d" @@ fun v d c ->
      t.(10-d) <- (i, v-1, c) :: t.(10-d)
    done;
    Array.map List.rev t
  in

  let cl = Array.make n (0, 0, 0) in
  qa.(0) |> List.iter (fun (i, v, c) -> cl.(v) <- i, c, 0);
  for r = 1 to 10 do
    Array.sort (fun (a,b) (c,d) ->
      min (fst3 cl.(a)) (fst3 cl.(b)) - min (fst3 cl.(c)) (fst3 cl.(d))) es;
    Array.iter (fun (u, v) ->
      let iu, cu, ru = cl.(u) in
      let iv, cv, rv = cl.(v) in
      if iu > iv && ru > -r then cl.(v) <- (iu, cu, ru-1);
      if iv > iu && rv > -r then cl.(u) <- (iv, cv, rv-1);
    ) es;
    qa.(r) |> List.iter (fun (i, v, c) -> cl.(v) <- max cl.(v) (i, c, -r));
  done;

  Array.iter (fun (_, c, _) -> Printf.printf "%d\n" c) cl

Score : 700 points

Problem Statement

Squid loves painting vertices in graphs.

There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges.
Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1.

Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i.

Find the color of each vertex after the Q operations.

Constraints

1 ≤ N,M,Q ≤ 10^5

1 ≤ a_i,b_i,v_i ≤ N

a_i ≠ b_i

0 ≤ d_i ≤ 10

1 ≤ c_i ≤10^5

d_i and c_i are all integers.

There are no self-loops or multiple edges in the given graph.

Partial Score

200 points will be awarded for passing the testset satisfying 1 ≤ N,M,Q ≤ 2{,}000.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_{M} b_{M}
Q
v_1 d_1 c_1
:
v_{Q} d_{Q} c_{Q}

Output

Print the answer in N lines.
In the i-th line, print the color of vertex i after the Q operations.

Sample Input 1

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

Sample Output 1

2
2
2
2
2
1
0

Initially, each vertex is painted in color 0.
In the first operation, vertices 5 and 6 are repainted in color 1.
In the second operation, vertices 1, 2, 3, 4 and 5 are repainted in color 2.

Sample Input 2

14 10
1 4
5 7
7 11
4 10
14 7
14 3
6 14
8 11
5 13
8 3
8
8 6 2
9 7 85
6 9 3
6 7 5
10 3 1
12 9 4
9 6 6
8 2 3

Sample Output 2

1
0
3
1
5
5
3
3
6
1
3
4
5
3

The given graph may not be connected.


Scanf.scanf "%d %d" (fun a b -> print_int ((a + b) mod 24))

Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

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

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


Scanf.scanf "%d %d" @@ fun a b -> Printf.printf "%d\n" @@ (a + b) mod 24


let () = Scanf.scanf "%d %d" (fun a b -> (a+b) mod 24) |> Printf.printf "%d\n"


Scanf.scanf "%d %d" (fun n m ->
    let ab = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun a b -> a, b)) in
    let cd = Array.init m (fun _ -> Scanf.scanf " %d %d" (fun a b -> a, b)) in
    for i = 0 to n - 1 do
        let x, y = ab.(i) in
        let rec loop j mip mid =
            if j = m then mip else
            let w, h = cd.(j) in
            let d = abs (x - w) + abs (y - h) in
            if d < mid then loop (j + 1) (j + 1) d
                       else loop (j + 1) mip mid
        in
        Printf.printf "%d\n" @@ loop 0 0 max_int
    done
)

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

Here, |x| denotes the absolute value of x.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

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

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

3 4
10 10
-10 -10
3 3
1 2
2 3
3 5
3 5

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let abs_ = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
  let cds = Array.init m @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun c d -> c, d in
  Array.iter (fun (a, b) ->
    Array.init m (fun i -> i)
    |> Array.fold_left (fun j i ->
        if abs (a - fst cds.(i)) + abs (b - snd cds.(i)) < abs (a - fst cds.(j)) + abs (b - snd cds.(j)) then i
        else j) 0
    |> ( + ) 1
    |> Printf.printf "%d\n") abs_


let dist a b c d = abs(a-c)+abs(b-d) in
Scanf.scanf "%d %d " @@ fun n m ->
  let a = Array.make n 0 in
  let b = Array.make n 0 in
  for i=0 to n-1 do
    Scanf.scanf "%d %d " @@ fun ai bi ->
      a.(i) <- ai;
      b.(i) <- bi
  done;
  let c = Array.make m 0 in
  let d = Array.make m 0 in
  for j=0 to m-1 do
    Scanf.scanf "%d %d " @@ fun cj dj ->
      c.(j) <- cj;
      d.(j) <- dj
  done;
  for i=0 to n-1 do
    let min = ref max_int in
    let index = ref 0 in
    for j=0 to m-1 do
      let distance = dist a.(i) b.(i) c.(j) d.(j) in
      if !min > distance then (
        min := distance; index := j
      )
    done;
    Printf.printf "%d\n" (!index+1)
  done


let () = Scanf.scanf "%d" @@ fun n ->
  Array.init (int_of_float (ceil @@ sqrt @@ float_of_int n)) (fun a ->
    if n mod (a + 1) = 0 then max (a + 1) (n / (a + 1))
    else max_int)
  |> Array.fold_left min max_int
  |> (fun a -> Printf.printf "%d\n" @@ succ @@ int_of_float @@ log (float_of_int a) /. log 10.)

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 f = Array.fold_left (fun c v -> if v = vs.(!k) then c + 1 else c) 0
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 = f 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 (f (sub vs 0 (!k + 1))))

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


let id x = x
let (a,b) = Scanf.scanf "%c %c" (fun a b -> (a,b))

let not_b = if b = 'H' then 'D' else 'H'

let ans = if a = 'H' then b else not_b

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

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


Scanf.scanf "%d %d %d" (fun w a b -> print_int (max 0 (abs (a - b) - 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


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


Scanf.scanf"%d %d %d"@@fun w a b->print_int@@max(abs(a-b)-w)0


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


let solve n =
  let rec aux i sum =
    if sum >= n then i else aux (succ i) (sum + i + 1) in
  aux 1 1

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

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 cnt =
  if x <= (i + cnt) then cnt else func x (i + cnt) (cnt + 1)

let ans = func x 0 1

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


open Printf open Scanf
open Array

let binary_search ng ok f = let d = if ng < ok then 1 else -1 in
  let rec f0 ng ok =
    if abs (ok - ng) <= 1 then ok
    else let mid = ng + (ok - ng) / 2 in if f mid then f0 ng mid else f0 mid ok
  in f0 (ng-d) (ok+d)

let () = scanf " %d %d" @@ fun n k ->
  let a = init n (fun _ -> scanf " %d" @@ fun v -> v) in
  sort compare a;
  print_int @@ binary_search 0 (n-1) (fun i ->
    let u = a.(i) in
    if u >= k then true
    else (
      let f = ref false in
      let dp = make (k+1) false in
      iteri (fun j v ->
        if j=i then ()
        else (
          for w=k downto 1 do
            if dp.(w) then (
              if k-u <= w+v && w+v < k then
                f := true
              else if w+v < k then
                dp.(w+v) <- true
            )
          done;
          if v<k then dp.(v) <- true
        );
      ) a; !f
    )
  )

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 rec upper_bound l r p =
  if r <= 1 + l
  then l
  else let m = (l + r) / 2 in
       if p m
       then upper_bound m r p
       else upper_bound l m p

let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let as_ = Array.init (n + 1) @@ function
    | 0 -> 0
    | _ -> Scanf.scanf "%d " @@ fun a -> a in
  Array.sort compare as_;
  let bs = Array.make k false in
  bs.(0) <- true;
  Printf.printf "%d\n" @@ upper_bound 0 (n + 1) @@ fun i ->
    if k <= as_.(i) then false
    else begin
      Array.fill bs 1 (k - 1) false;
      Array.iteri (fun j a ->
        if i <> j then
          for a' = k - 1 downto a do
            bs.(a') <- bs.(a') || bs.(a' - a)
          done) as_;
      try
        for a = k - as_.(i) to k - 1 do
          if bs.(a) then raise Not_found
        done; true
      with Not_found -> false
    end


let rec upper_bound l r p =
  if r <= 1 + l
  then l
  else let m = (l + r) / 2 in
       if p m
       then upper_bound m r p
       else upper_bound l m p

let () = Scanf.scanf "%d\n" @@ fun n ->
  let lrs = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun l r -> l, r in
  let f x = Array.fold_right (fun (l, r) -> ( + ) @@
    if x < l then l - x
    else if r < x then x - r
    else 0) lrs 0 in
  Printf.printf "%d\n" @@ f @@ upper_bound
    (Array.fold_right (fun (l, _) -> min l) lrs max_int)
    (Array.fold_right (fun (_, r) -> max r) lrs 0 + 1) @@ fun x -> f (x - 1) >= f x

Score : 1000 points

Problem Statement

AtCoDeer the deer found N rectangle lying on the table, each with height 1.
If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure:

AtCoDeer will move these rectangles horizontally so that all the rectangles are connected.
For each rectangle, the cost to move it horizontally by a distance of x, is x.
Find the minimum cost to achieve connectivity.
It can be proved that this value is always an integer under the constraints of the problem.

Constraints

All input values are integers.

1≤N≤10^5

1≤l_i<r_i≤10^9

Partial Score

300 points will be awarded for passing the test set satisfying 1≤N≤400 and 1≤l_i<r_i≤400.

Input

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

N
l_1 r_1
l_2 r_2
:
l_N r_N

Output

Print the minimum cost to achieve connectivity.

Sample Input 1

3
1 3
5 7
1 3

Sample Output 1

2

The second rectangle should be moved to the left by a distance of 2.

Sample Input 2

3
2 5
4 6
1 4

Sample Output 2

0

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

Sample Input 3

5
999999999 1000000000
1 2
314 315
500000 500001
999999999 1000000000

Sample Output 3

1999999680

Sample Input 4

5
123456 789012
123 456
12 345678901
123456 789012
1 23

Sample Output 4

246433

Sample Input 5

1
1 400

Sample Output 5

0


let () =
  let n, c, k = Scanf.scanf "%d %d %d\n" (fun n c k -> n, c, k) in
  let ts = Array.init n (fun _ -> Scanf.scanf "%d " (fun n -> n)) in
  Array.sort compare ts;
  Array.fold_left (fun (acc, i, j) t ->
    if ts.(i) + k < t then (acc + 1, j, j + 1)
    else if c <= j - i then (acc + 1, i + c, j + 1)
    else (acc, i, j + 1)) (0, 0, 0) ts
  |> (fun (acc, _, _) -> Printf.printf "%d\n" (1 + acc))

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


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

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n-1) in
  loop []

let alist = repeat (fun () -> Scanf.scanf "%d " id) n
let len = List.length alist

let rec del_i i l =
  match l with
  | [] -> []
  | h::t when i = 0 -> t
  | h::t -> h :: del_i (i-1) t

let rec del x l =
  match l with
  | [] -> []
  | h::t when h = x -> t
  | h::t -> h :: del x t

let check' alist =
  let rec check1 i ans =
    if i = len then ans else check2 (del_i i alist) (List.nth alist i) ans i

  and check2 alist' x ans i =
    match alist' with
    | [] -> check1 (i+1) (ans+1)
    | alist' ->
       if List.exists (fun y -> y <= 2*x) alist' then
	let x' = (List.find (fun y -> y <= 2*x) alist') in
	check2 (del x' alist') (x + x') ans i
       else check1 (i+1) ans
in check1 0 0

let ans = check' alist

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

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


open Scanf
open Printf

let () = scanf "%d" (fun n-> n * 800 - (n / 15) * 200
  ) |> printf "%d\n"

Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

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

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


let () = Scanf.scanf "%d" (fun n -> 800 * n - 200 * (n / 15)) |> Printf.printf "%d\n"


let rec f n a = if n <= 1 then a else f (n - 1) (n * a mod 1000000007)
let _ = Printf.printf "%d\n" @@ f (read_int ()) 1

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.


Scanf.scanf " %d %d"@@fun n m->print_int@@if n*2>m then m/2 else n+(m-n*2)/4

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 string_to_list str =
  let rec loop i limit =
    if i = limit then []
    else (String.get str i) :: (loop (i + 1) limit)
  in
  loop 0 (String.length str)

let fwd arr_length n = if n = (arr_length - 1) then 0 else n+1
let prev arr_length n = if n = 0 then arr_length - 1 else n-1
let flip c = if c = 'S' then 'W' else 'S'
let print_chars arr = Array.iter (fun x -> Printf.printf "%c" x) arr; Printf.printf "\n"

let fill arr arr_length n by =
  if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
    begin
      arr.(fwd arr_length n) <- arr.(prev arr_length n);
    end
  else
    begin
      arr.(fwd arr_length n) <- flip arr.(prev arr_length n);
    end

let rec extend answers ans_length cursor ret = match answers with
  | [] -> ret
  | 'o'::rest ->
     fill ret ans_length cursor 'o';
     extend rest ans_length (cursor+1) ret
  | 'x'::rest ->
     fill ret ans_length cursor 'x';
     extend rest ans_length (cursor+1) ret
  | _ -> ret

let check arr arr_length by n =
  if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
    arr.(fwd arr_length n) = arr.(prev arr_length n)
  else
    arr.(fwd arr_length n) <> arr.(prev arr_length n)

let make_list f t step =
  let rec make_list_inner c t lst =
    if c >= t then lst else make_list_inner (c+step) t (c::lst)
  in
  List.rev (make_list_inner f t [])

let check_all pos_ans length pairs =
  let checks = List.map (fun (x,y) -> check pos_ans length y x) pairs in
  List.fold_left (fun x y -> x && y) true checks

let array_make length a b =
  let ret = (Array.make length a) in
  ret.(length - 1) <- b;
  ret

let solve str =
  let str_list = (string_to_list str) in
  let length = List.length str_list in
  let pairs = List.combine (make_list 0 length 1) str_list in
  let pos_ans = extend str_list length 0 (array_make length 'S' 'S') in
  if check_all pos_ans length pairs then pos_ans else
    let pos_ans = extend str_list length 0 (array_make length 'S' 'W') in
    if check_all pos_ans length pairs then pos_ans else
      let pos_ans = extend str_list length 0 (array_make length 'W' 'W') in
      if check_all pos_ans length pairs then pos_ans else
        let pos_ans = extend str_list length 0 (array_make length 'W' 'S') in
        if check_all pos_ans length pairs then pos_ans else
          [||]

let () =
  let _ = read_int() in
  let str = read_line () in
  let ans = solve str in
  if ans = [||] then
    Printf.printf ("-1")
  else
    Array.iter (fun x -> Printf.printf "%c" x) ans;
  Printf.printf "\n"
;;

Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

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

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS


(* unihernandez22
 * https://atcoder.jp/contests/abc054/tasks/abc054_b
 * implementation
 * *)

Scanf.scanf "%d %d\n" @@ fun n m ->
    let a = Array.init n @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
    let b = Array.init m @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in

    let valid = ref true in
    let ans = ref "No\n" in
    for i = 0 to n-m do
        for j = 0 to n-m do
            valid := true;
            for y = 0 to m-1 do
                if String.sub a.(i+y) j m <> b.(y) then
                    valid := false;
            done;
            if !valid then
                ans := "Yes\n";
        done;
    done;
    print_string !ans;;

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

A_i is a string of length N consisting of # and ..

B_i is a string of length M consisting of # and ..

Input

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

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

4 1
....
....
....
....
#

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


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

    let o = n - m in
    let rec loop_oy oy =
        let rec loop_ox ox =
            let rec loop_y y =
                let rec loop_x x =
                    if x = m then true else
                        if a.(oy + y).[ox + x] <> b.(y).[x] then false
                            else loop_x (x + 1)
                in
                if y = m then true else
                    if loop_x 0 then loop_y (y + 1) else false
            in
            if ox > o then false else
                if loop_y 0 then true else loop_ox (ox + 1)
        in
        if oy > o then false else
            if loop_ox 0 then true else loop_oy (oy + 1)
    in
    print_endline @@ if loop_oy 0 then "Yes" else "No"
)


let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m)
let edge = Array.make (n + 1) []

let rec load_graph i =
  if i < m then
    Scanf.scanf "%d %d\n" (fun a b ->
      edge.(a) <- b :: edge.(a);
      edge.(b) <- a :: edge.(b);
      load_graph (i + 1)
    )

let rec ans v exists rest =
  if rest = 0 then 1
  else
    let rec f ret = function
        [] -> ret
      | u :: l ->
        if exists.(u) then (
          let copy = Array.init (n + 1) (fun i -> exists.(i)) in
          copy.(u) <- false;
          f (ret + ans u copy (rest - 1)) l
        ) else f ret l
    in f 0 edge.(v)

let () =
  load_graph 0;
  let exists = Array.make (n + 1) true in
  exists.(1) <- false;
  print_int (ans 1 exists (n - 1))

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 lim, inf = 400, 10101010101010
let () =
  Scanf.scanf "%d %d %d" @@ fun n ma mb ->
  let x = Array.init n (fun _ -> Scanf.scanf " %d %d %d" (fun a b c -> a,b,c)) in
  let dp = Array.make_matrix (lim+1) (lim+1) inf in
  dp.(0).(0) <- 0;
  x |> Array.iter (fun (a,b,c) ->
    for i = 400 downto a do
      for j = 400 downto b do
        dp.(i).(j) <- min dp.(i).(j) (dp.(i-a).(j-b) + c)
    done done);
  Array.init (lim / max ma mb) (fun i -> dp.((i+1)*ma).((i+1)*mb))
  |> Array.fold_left min inf
  |> fun c -> Printf.printf "%d\n" (if c = inf then -1 else c)

Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

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

N M_a M_b
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

3 1 1
1 2 1
2 1 2
3 3 10

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.


Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    print_endline @@ if Array.fold_left (fun acc v -> acc + v mod 2) 0 a mod 2 = 0 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


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


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

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

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n - 1) in
  loop []

let r = repeat (fun () -> Scanf.scanf "%d " id) n

let rec check = function
  | [a] -> true
  | a :: rest ->
     match rest with
     | [b] -> if (a mod 2) = (b mod 2) then true else false
     | b :: rest2 ->
	match rest2 with
	| c :: rest3 -> if (a mod 2) = (b mod 2) then check ((a+b) :: rest2) else
	    if (a mod 2) = (c mod 2) then check ((a+c) :: b :: rest3) else check ((b+c) :: a :: rest3)

let ansbool = check r

let ans = if ansbool = true then "YES" else "NO"

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


open Printf open Scanf
let ident v = v
let max_listi ls =
	let rec f0 i l v vi = match l with
	| [] -> (v,vi)
	| h::t ->
		if (h > v)
			then f0 (i+1) t h i
			else f0 (i+1) t v vi
	in f0 0 ls min_int (-1)
let () =
	let n = scanf " %d" ident
	in let ar = Array.init n (fun _ -> Scanf.scanf " %d" (fun v -> v))
	in
	let f = ref true
	in
	while !f do
		let (vmax,imax) = max_listi (Array.to_list ar)
		in
		(* printf "%d,%d\n" vmax imax; *)
		for i=0 to n-1 do
			let r =
				if i=imax then ar.(i) - n
				else ar.(i) - ((i - imax + 2*n) mod n)
			in ar.(i) <- r;
			if r<=0 then f := false;
		done;
	done;
	Array.fold_left (fun u v -> (
		(* printf "%d," v; *)
		(u && v=0))) true ar
	|> (fun v -> if v then "YES" else "NO")
	|> printf "%s\n"

Score : 500 points

Problem Statement

There are N boxes arranged in a circle. The i-th box contains A_i stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-th box. Here, the (N+k)-th box is identified with the k-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

1 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

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 remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO


let () =
  let x = Scanf.scanf "%d " (fun a -> a) in
  Printf.printf "%s\n" (if x < 1200 then "ABC" else "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 n = read_int ()

let arr = Array.make 100001 0

let rec f i odd even =
  if i = n then (odd, even)
  else
    let j = Scanf.scanf " %d" (fun a -> a) in
    if 0 = arr.(j) then (ignore (arr.(j) <- 1); f (i+1) (odd + 1) even)
    else if 1 = arr.(j) then (ignore (arr.(j) <- 2); f (i + 1) (odd - 1) (even + 1))
    else (ignore (arr.(j) <- 1); f (i + 1) (odd + 1) (even - 1))

let odd, even = f 0 0 0

let () = print_int (odd + even / 2 * 2)

Score : 400 points

Problem Statement

Snuke has decided to play a game using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.

He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.

Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

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

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 7.

Sample Input 2

15
1 3 5 2 1 3 2 8 8 6 2 6 11 1 1

Sample Output 2

7


let () = Scanf.scanf "%d" (fun x ->
  Printf.printf "%d\n" @@ x / 11 * 2 + if 6 < x mod 11 then 2 else 1)

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


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

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

Score : 300 points

Problem Statement

There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons.
When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1.

There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so that for every i, A_i will be a multiple of B_i.

Find the minimum number of times Takahashi will press the buttons.

Constraints

All input values are integers.

1 ≦ N ≦ 10^5

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

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

Input

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

N
A_1 B_1
:
A_N B_N

Output

Print an integer representing the minimum number of times Takahashi will press the buttons.

Sample Input 1

3
3 5
2 7
9 4

Sample Output 1

7

Press the first button twice, the second button twice and the third button three times.

Sample Input 2

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

Sample Output 2

22


module type OrderedType =
  sig
    type t
    val compare: t -> t -> int
  end

type z = Z_
type 'n s = S_ : 'n -> 'n s
type _ nat =
  | Z : z nat
  | S : 'n nat -> 'n s nat

type (_, _) le =
  | LeEq : ('n, 'n) le
  | LeS : ('n, 'm) le -> ('n, 'm s) le

let rec le_n_s : type n m. (n, m) le -> (n s, m s) le = function
  | LeEq -> LeEq
  | LeS hle -> LeS (le_n_s hle)

let rec le_0_n : type n. n nat -> (z, n) le = function
  | Z -> LeEq
  | S n -> LeS (le_0_n n)

let rec le_ge_dec : type n m. n nat -> m nat -> [ `InL of (n, m) le | `InR of (m, n) le ] =
  fun n m ->
    match n, m with
    | Z, _ -> `InL (le_0_n m)
    | _, Z -> `InR (le_0_n n)
    | S n', S m' ->
        begin match le_ge_dec n' m' with
        | `InL hle -> `InL (le_n_s hle)
        | `InR hge -> `InR (le_n_s hge)
        end

module type HEAP = sig
  type elt
  type t

  val empty : t
  val singleton : elt -> t
  val merge : t -> t -> t
  val insert : elt -> t -> t
  val find_min : t -> elt option
  val delete_min : t -> t option
end

module BinomialHeap (O : OrderedType) : HEAP with type elt = O.t = struct
  type elt = O.t

  type 'n tree = Node of elt * 'n tree_vector
  and _ tree_vector =
    | TNil : z tree_vector
    | TCons : 'n tree * 'n tree_vector -> 'n s tree_vector

  type _ tree_opt_vector =
    | TONil : z tree_opt_vector
    | TOCons : 'n tree option * 'n tree_opt_vector -> 'n s tree_opt_vector

  type t = T : 'n nat * 'n tree_opt_vector -> t

  let rec tree_opt_vector_of_tree_vector : type n. n tree_vector -> n tree_opt_vector = function
    | TNil -> TONil
    | TCons (t, tv) -> TOCons (Some t, tree_opt_vector_of_tree_vector tv)

  let merge_tree (Node (e1, ts1) as t1) (Node (e2, ts2) as t2) =
    if O.compare e1 e2 < 0 then Node (e1, TCons (t2, ts1))
    else Node (e2, TCons (t1, ts2))

  let rec merge_tree_opt_vector : type n. n tree_opt_vector -> n tree_opt_vector -> n tree_opt_vector * n tree option = fun tov1 tov2 ->
    match tov1, tov2 with
    | TONil, TONil -> (TONil, None)
    | TOCons (to1, tov1'), TOCons (to2, tov2') ->
        let (tov12, to3) = merge_tree_opt_vector tov1' tov2' in
        begin match to1, to2, to3 with
        | _, None, None -> (TOCons (to1, tov12), None)
        | None, _, None -> (TOCons (to2, tov12), None)
        | None, None, _ -> (TOCons (to3, tov12), None)
        | _, Some t2, Some t3 -> (TOCons (to1, tov12), Some (merge_tree t2 t3))
        | Some t1, _, Some t3 -> (TOCons (to2, tov12), Some (merge_tree t1 t3))
        | Some t1, Some t2, _ -> (TOCons (to3, tov12), Some (merge_tree t1 t2))
        end

  let delete_min_tree_opt_vector_aux1 tov = function
    | None -> None
    | Some (Node (e, tv)) ->
        Some (e, fun () ->
          let (tov', to0) = merge_tree_opt_vector tov (tree_opt_vector_of_tree_vector tv) in
          TOCons (to0, tov'))

  let delete_min_tree_opt_vector_aux2 to0 = function
    | None -> None
    | Some (e, tov) -> Some (e, fun () -> TOCons (to0, tov ()))

  let rec delete_min_tree_opt_vector : type n. n tree_opt_vector -> (elt * (unit -> n tree_opt_vector)) option = function
    | TONil -> None
    | TOCons (to0, tov) ->
        begin match delete_min_tree_opt_vector_aux1 tov to0, delete_min_tree_opt_vector_aux2 to0 (delete_min_tree_opt_vector tov) with
        | None, None -> None
        | (Some _ as result1), None -> result1
        | None, (Some _ as result2) -> result2
        | (Some (e1, _) as result1), (Some (e2, _) as result2) ->
            if O.compare e1 e2 < 0 then result1
            else result2
        end

  let rec padding : type n m. n tree_opt_vector -> (n, m) le -> m tree_opt_vector = fun t hle ->
    match hle with
    | LeEq -> t
    | LeS hle' -> TOCons (None, padding t hle')

  let empty = T (Z, TONil)
  let singleton e = T (S Z, TOCons (Some (Node (e, TNil)), TONil))

  let merge (T (n1, tov1)) (T (n2, tov2)) =
    match le_ge_dec n1 n2 with
    | `InL hle ->
        begin match merge_tree_opt_vector (padding tov1 hle) tov2 with
        | tov', None -> T (n2, tov')
        | tov', (Some _ as to0) -> T (S n2, TOCons (to0, tov'))
        end
    | `InR hgt ->
        begin match merge_tree_opt_vector tov1 (padding tov2 hgt) with
        | tov', None -> T (n1, tov')
        | tov', (Some _ as to0) -> T (S n1, TOCons (to0, tov'))
        end

  let insert e t = merge (singleton e) t

  let find_min (T (_, tov)) =
    match delete_min_tree_opt_vector tov with
    | None -> None
    | Some (e, _) -> Some e

  let delete_min (T (n, tov)) =
    match delete_min_tree_opt_vector tov with
    | None -> None
    | Some (_, tov') ->
        begin match n, tov' () with
        | S n', TOCons (None, tov'') -> Some (T (n', tov''))
        | _, tov'' -> Some (T (n, tov''))
        end
end

module IntHeap = BinomialHeap (struct
  type t = int
  let compare = compare
end)

let rec balance ts =
  let Some d = IntHeap.find_min ts in
  let Some ts' = IntHeap.delete_min ts in
  match IntHeap.find_min ts' with
  | None -> d
  | Some d' ->
      let Some ts'' = IntHeap.delete_min ts' in
      balance (IntHeap.insert (1 + max d d') ts'')

let rec make_tournament losers winner =
  List.map (make_tournament losers) (losers winner)
    |> List.fold_left (fun s d -> IntHeap.insert d s) (IntHeap.singleton 0)
    |> balance

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init (n - 1) (fun _ -> Scanf.scanf "%d\n" (fun a -> a)) in
  let losers = Array.make n [] in
  Array.iteri (fun i a ->
    losers.(a - 1) <- i + 1 :: losers.(a - 1)) as_;
  Printf.printf "%d\n" (make_tournament (fun i -> losers.(i)) 0)

Score : 800 points

Problem Statement

N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament.
For some reasons, the tournament may not be "fair" for all the contestants.
That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The structure of the tournament is formally described at the end of this statement.

After each match, there were always one winner and one loser. The last contestant standing was declared the champion.

Figure: an example of a tournament

For convenience, the contestants were numbered 1 through N. The contestant numbered 1 was the champion, and the contestant numbered i(2 ≦ i ≦ N) was defeated in a match against the contestant numbered a_i.

We will define the depth of the tournament as the maximum number of the matches that must be played in order to win the championship over all the contestants.

Find the minimum possible depth of the tournament.

The formal description of the structure of the tournament is as follows. In the i-th match, one of the following played against each other:

Two predetermined contestants

One predetermined contestant and the winner of the j-th match, where j(j<i) was predetermined

The winner of the j-th match and the winner of the k-th match, where j and k (j,k<i, j ≠ k) were predetermined

Such structure is valid structure of the tournament, if and only if no contestant who has already been defeated in a match will never play in a match, regardless of the outcome of the matches.

Constraints

2 ≦ N ≦ 10^5

1 ≦ a_i ≦ N(2 ≦ i ≦ N)

It is guaranteed that the input is consistent (that is, there exists at least one tournament that matches the given information).

Input

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

N
a_2
:
a_N

Output

Print the minimum possible depth of the tournament.

Sample Input 1

5
1
1
2
4

Sample Output 1

3

The following tournament and the result of the matches are consistent with the given information:

In the first match, contestants 4 and 5 played against each other, and contestant 4 won.

In the second match, contestants 2 and 4 played against each other, and contestant 2 won.

In the third match, contestants 1 and 3 played against each other, and contestant 1 won.

In the fourth match, contestants 1 and 2 played against each other, and contestant 1 won.

The depth of this tournament is 3, since contestant 5 must play three matches in order to win the championship.
There is no tournament with depth 2 or less that is consistent with the given information, thus the output should be 3.

Sample Input 2

7
1
2
1
3
1
4

Sample Output 2

3

Sample Input 3

4
4
4
1

Sample Output 3

3


type t = Node of t * t | Leaf of int

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

let rec balance ts =
  let d, t, ts' =
    match IntMap.min_binding ts with
    | (d, [t]) -> (d, t, IntMap.remove d ts)
    | (d, t :: tt) -> (d, t, IntMap.add d tt ts) in
  match IntMap.min_binding ts' with
  | d', [t'] ->
      let ts'' = IntMap.remove d' ts' in
      let d'' = 1 + max d d' in
      balance (IntMap.add d'' (Node (t, t') :: try IntMap.find d'' ts'' with Not_found -> []) ts'')
  | d', t' :: tt ->
      let ts'' = IntMap.add d' tt ts' in
      let d'' = 1 + max d d' in
      balance (IntMap.add d'' (Node (t, t') :: try IntMap.find d'' ts'' with Not_found -> []) ts'')
  | exception Not_found -> (d, t)

let rec make_tournament losers winner =
  List.map (make_tournament losers) (losers winner)
    |> List.fold_left (fun s (d, t) ->
        IntMap.add d (t :: try IntMap.find d s with Not_found -> []) s)
          (IntMap.singleton 0 [Leaf winner])
    |> balance

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init (n - 1) (fun _ -> Scanf.scanf "%d\n" (fun a -> a)) in
  let losers = Array.make n [] in
  Array.iteri (fun i a ->
    losers.(a - 1) <- i + 1 :: losers.(a - 1)) as_;
  Printf.printf "%d\n" @@ fst @@ make_tournament (fun i -> losers.(i)) 0


Scanf.scanf "%d %d %d %d" (fun a b c d ->
    Printf.printf "%d\n" @@ max (a * b) (c * d)
)

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

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

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


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

let string_to_list str =
  let id_to_int c =
    if c = 'I' then 1
    else -1
  in
  let rec loop idx arr=
    if idx = -1 then arr
    else loop (idx-1) ((id_to_int (String.get str idx))::arr)
  in
  loop (n-1) []
;;

let solve arr =
  let rec sim ma v arr =
    match arr with
    | [] -> ma
    | h::t ->
      let w = v + h in
      let new_max = max ma w in
      sim new_max w t
  in
  sim 0 0 arr
;;

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

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 n = read_int ()
let s = read_line ()

let rec f maxim now str =
  let len = String.length str in
  if len = 0 then maxim
  else if str.[0] = 'I' then
    f (max maxim (now + 1)) (now + 1) (String.sub str 1 (len - 1))
  else f maxim (now - 1) (String.sub str 1 (len - 1))

let () = f 0 0 s |> Printf.printf "%d\n"


let id a = a
let n = Scanf.scanf "%d\n" id
let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n-1) in
  loop []

let r = repeat (fun () -> Scanf.scanf "%c" id) n

let rec ans x list = function
  | [] -> list
  | a :: rest ->
     match a with
     | 'I' -> ans (x+1) ((x+1) :: list) rest
     | 'D' -> ans (x-1) ((x-1) :: list) rest
     | _   -> ans x (x :: list) rest

let anslist = ans 0 [] r

let rec maxlist l x =
  match l with
  | [] -> x
  | a :: rest -> if a > x then maxlist rest a else maxlist rest x

let saidai = maxlist anslist 0

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


(* O(n^2 log n) *)
let n = read_int ()
let is_prime n =
  if n <= 1 then false
  else
    let rec loop i =
      if i * i > n then true
      else if n mod i = 0 then false
      else loop @@ i + 1 in
    loop 2
let rec div_count n i = if n mod i <> 0 then 0 else 1 + div_count (n / i) i
let ans = ref 1
let _ =
  for i = 2 to n do
    if is_prime i then
      let c = ref 0 in
      for j = 2 to n do c := !c + div_count j i done;
      ans := !ans * (!c + 1) mod 1_000_000_007 done;
  Printf.printf "%d\n" @@ !ans

Score : 300 points

Problem Statement

You are given an integer N.
Find the number of the positive divisors of N!, modulo 10^9+7.

Constraints

1≤N≤10^3

Input

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

N

Output

Print the number of the positive divisors of N!, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

4

There are four divisors of 3! =6: 1, 2, 3 and 6. Thus, the output should be 4.

Sample Input 2

6

Sample Output 2

30

Sample Input 3

1000

Sample Output 3

972926972


let () =
  let n, a, b = Scanf.scanf "%d %d %d\n" (fun n a b -> n, a, b) in
  let xs = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  Array.init (n - 1) (fun i -> min b (a * (xs.(i + 1) - xs.(i))))
  |> Array.fold_left ( + ) 0
  |> Printf.printf "%d\n"

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.


Scanf.scanf"%5s,%7s,%5s"@@Printf.printf "%s %s %s\n"

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 () =
    let s = Scanf.scanf "%s\n" (fun x -> x) in
    let a = String.sub s 0 5 in
    let b = String.sub s 6 7 in
    let c = String.sub s 13 5 in
    Printf.printf "%s\n" (a ^ " " ^ b ^ " " ^ c)


let s = read_line ()
let _ = String.map (function ',' -> ' ' | c -> c) s |> print_endline


let s = Scanf.scanf "%s " (fun a -> a) in
Printf.printf "%s\n" (Str.global_replace (Str.regexp ",") " " s)


let dx, dy = Scanf.scanf "%d %d %d %d" (fun w x y z -> y-w, z-x)
let p n c = Array.init n (fun _ -> Printf.printf "%c" c) |> ignore
let () =
  p dx 'R';
  p dy 'U';
  p dx 'L';
  p (dy+1) 'D';
  p (dx+1) 'R';
  p (dy+1) 'U';
  p 1 'L';
  p 1 'U';
  p (dx+1) 'L';
  p (dy+1) 'D';
  p 1 'R';
  print_newline ()

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


type 'a set =
  | Empty
  | Singleton of 'a
  | Union of 'a set * 'a set

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

let rec make_intset acc = function
  | Empty -> acc
  | Singleton x -> IntSet.add x acc
  | Union (s, t) -> make_intset (make_intset acc s) t

let warshall_floyd ( + ) min n d =
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      for k = 0 to n - 1 do
        d.(j).(k) <- min d.(j).(k) (d.(j).(i) + d.(i).(k))
      done
    done
  done

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let dp = Array.make_matrix n n (infinity, Empty) in
  for i = 0 to n - 1 do
    dp.(i).(i) <- (0., Empty)
  done;
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d %d\n" (fun a b c ->
      dp.(a - 1).(b - 1) <- (float_of_int c, Singleton i);
      dp.(b - 1).(a - 1) <- (float_of_int c, Singleton i))
  done;
  warshall_floyd
    (fun (d, es) (d', es') -> (d +. d', Union (es, es')))
    (fun (d, es) (d', es') ->
      match compare d d' with
      | -1 -> (d, es)
      | 0  -> (d, Union (es, es'))
      | 1  -> (d', es')) n dp;
  Array.map (fun dp ->
    Array.map snd dp
    |> Array.fold_left (fun s t -> Union (s, t)) Empty) dp
  |> Array.fold_left (fun s t -> Union (s, t)) Empty
  |> make_intset IntSet.empty
  |> IntSet.cardinal
  |> (fun n -> Printf.printf "%d\n" (m - n))

Score : 400 points

Problem Statement

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

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

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).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

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

The given graph is connected.

Input

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

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


let () =
  Scanf.scanf "%d %d" (fun x y ->
    [ if x <= y then y - x else max_int;
      if -x <= y then 1 + x + y else max_int;
      if x <= -y then 1 - x - y else max_int;
      if -x <= -y then 2 + x - y else max_int ])
  |> List.fold_left min max_int
  |> Printf.printf "%d\n"

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.


open Printf
open Scanf

let solve a op b =
  if op = '+' then a + b else a - b

let () =
  scanf "%d %c %d" solve |> 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


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


let a, op, b = Scanf.scanf "%d %s %d\n" (fun a b c -> a, b, c)
let calc = function
  | "+" -> (+)
  | "-" -> (-)
  | _ -> failwith "hoge"

let () =
  let op = calc op in
  print_endline @@ string_of_int (op a b)


let () =
  let xs = Scanf.scanf "%d" (fun n -> Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))) in
  let total = Array.fold_left (+) 0 xs in
  Scanf.scanf " %d" (fun m -> Array.init m (fun _ -> Scanf.scanf " %d %d" (fun p u -> (p, u))))
  |> Array.iter (fun (p, u) -> Printf.printf "%d\n" (total + (u-xs.(p-1))))

Score : 200 points

Problem Statement

Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are N problems, numbered 1 through N.
Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).

Also, there are M kinds of drinks offered to the contestants, numbered 1 through M.
If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds.
It does not affect the time to solve the other problems.

A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink.
Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems.
Your task is to write a program to calculate it instead of her.

Constraints

All input values are integers.

1≦N≦100

1≦T_i≦10^5

1≦M≦100

1≦P_i≦N

1≦X_i≦10^5

Input

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

N
T_1 T_2 ... T_N
M
P_1 X_1
P_2 X_2
:
P_M X_M

Output

For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line.

Sample Input 1

3
2 1 4
2
1 1
2 3

Sample Output 1

6
9

If Joisino takes drink 1, the time it takes her to solve each problem will be 1, 1 and 4 seconds, respectively, totaling 6 seconds.

If Joisino takes drink 2, the time it takes her to solve each problem will be 2, 3 and 4 seconds, respectively, totaling 9 seconds.

Sample Input 2

5
7 2 3 8 5
3
4 2
1 7
4 13

Sample Output 2

19
25
30


let id x = x

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

let px =
  Array.init (Scanf.scanf "%d " id) (fun _ ->
      Scanf.scanf "%d %d " (fun p x -> (p, x)) )

let sum = Array.fold_left ( + ) 0 t

let () =
  Array.iter (fun (p, x) -> sum - (t.(p - 1) - x) |> Printf.printf "%d\n") px


let n = read_int ()
let cs, ds = Array.(make n 0, make n 0)
let rec f n a = if n <= 0 then a else f (n - 1) (2 * a mod 1000000007)
let _ = for _ = 1 to n do Scanf.scanf " %d" @@ fun a -> cs.(a) <- cs.(a) + 1 done; for i = 1 to n / 2 do ds.(n mod 2 + 2 * i - 1) <- 2 done; ds.(0) <- n mod 2; Printf.printf "%d\n" @@ if cs = ds then f (n / 2) 1 else 0

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

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 orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


let rec power ( * ) one m = function
  | 0 -> one
  | n when n mod 2 = 0 ->
      power ( * ) one (m * m) (n / 2)
  | n ->
      m * power ( * ) one m (n - 1)

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  Array.sort compare as_;
  if
    n mod 2 = 0 && as_ = Array.init n (fun i -> (i + 1) - i mod 2) ||
    n mod 2 = 1 && as_ = Array.init n (fun i -> (i + 1) - (i + 1) mod 2)
  then Printf.printf "%d\n" @@ power (fun n m -> n * m mod 1000000007) 1 2 (n / 2)
  else print_endline "0"


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

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 () = Scanf.scanf "%c" (fun c -> if String.contains "aeiou" c then "vowel" else "consonant")
|> print_endline


let h, w = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = Array.init h @@ fun _ -> Scanf.scanf " %s" @@ fun s -> Printf.printf "%s\n%s\n" s s


Scanf.scanf "%d %d %d" (fun n k l ->
    let rec root arr x =
        if x = arr.(x) then x else (
            let r = root arr arr.(x) in
            arr.(x) <- r;
            r
        )
    in

    let merge arr count x y =
        if root arr x <> root arr y then (
            count.(arr.(x)) <- count.(arr.(x)) + count.(arr.(y));
            arr.(arr.(y)) <- arr.(x);
        )
    in

    let road        = Array.init n (fun i -> i) in
    let train       = Array.init n (fun i -> i) in
    let road_count  = Array.make n 1 in
    let train_count = Array.make n 1 in

    for i = 1 to k do
        Scanf.scanf " %d %d" (fun p q ->
            let p = p - 1 in
            let q = q - 1 in
            merge road road_count p q
        )
    done;
    for i = 1 to l do
        Scanf.scanf " %d %d" (fun p q ->
            let p = p - 1 in
            let q = q - 1 in
            merge train train_count p q
        )
    done;
    let module M = Map.Make (struct type t = int let compare = compare end) in
    let rec loop i map =
        if i = n then map else
            let r = root road  i in
            let t = root train i in
            let key = r * n + t in
            let map = M.add key (1 + try M.find key map with _ -> 0) map in
            loop (i + 1) map
    in
    let map = loop 0 M.empty in

    for i = 0 to n - 1 do
        let r = root road  i in
        let t = root train i in
        let key = r * n + t in
        Printf.printf "%d " @@ M.find key map
    done;
    print_newline ()
)

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


let _, s = Scanf.scanf " %s %s" @@ fun a b -> a, b
let _ = Printf.printf "A%cC\n" @@ Char.uppercase s.[0]

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


let f n x = match n with
	| -1 -> 0
	| n -> n / x + 1

let _ =
	Scanf.scanf "%d %d %d" (fun a b x -> f b x - f (a - 1) x) |> Printf.printf "%d"

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 rec eat x lst = match lst with
	| a::b::xs -> if a + b > x
					then
						let dcl = a + b - x in
						dcl + eat x (a::b-dcl::xs)
					else
						eat x (b::xs)
	| _::xs -> 0
	| [] -> 0

let _ =
	let f = Scanf.scanf "%d %d\n" (fun x y -> eat y) in
	read_line () |> Str.split (Str.regexp " ") |> List.map(fun x -> int_of_string x)|> f |> Printf.printf "%d"

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.