let rec solve i n = function
  | [] | [_] -> n
  | p :: p' :: ps ->
      if i = p then
        solve (i + 1) (n + 1) (p :: ps)
      else
        solve (i + 1) n (p' :: ps)
let solve = solve 1 0

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let ps = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%d " (fun p -> p)) in
  Printf.printf "%d\n" @@ solve ps

Score : 400 points

Problem Statement

You are given a permutation p_1,p_2,...,p_N consisting of 1,2,..,N.
You can perform the following operation any number of times (possibly zero):

Operation: Swap two adjacent elements in the permutation.

You want to have p_i ≠ i for all 1≤i≤N.
Find the minimum required number of operations to achieve this.

Constraints

2≤N≤10^5

p_1,p_2,..,p_N is a permutation of 1,2,..,N.

Input

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

N
p_1 p_2 .. p_N

Output

Print the minimum required number of operations

Sample Input 1

5
1 4 3 5 2

Sample Output 1

2

Swap 1 and 4, then swap 1 and 3. p is now 4,3,1,5,2 and satisfies the condition.
This is the minimum possible number, so the answer is 2.

Sample Input 2

2
1 2

Sample Output 2

1

Swapping 1 and 2 satisfies the condition.

Sample Input 3

2
2 1

Sample Output 3

0

The condition is already satisfied initially.

Sample Input 4

9
1 2 4 9 5 8 7 3 6

Sample Output 4

3


Scanf.scanf "%d %d %d %d %d" (fun q h s d n ->
    let best1 = min s (min (q * 4) (h * 2)) in
    let best2 = min d (best1 * 2) in

    Printf.printf "%d\n" @@ (n / 2) * best2 + (n mod 2) * best1
)

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

Score : 300 points

Problem Statement

You've come to your favorite store Infinitesco to buy some ice tea.

The store sells ice tea in bottles of different volumes at different costs.
Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen.
The store has an infinite supply of bottles of each type.

You want to buy exactly N liters of ice tea. How many yen do you have to spend?

Constraints

1 \leq Q, H, S, D \leq 10^8

1 \leq N \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

Q H S D
N

Output

Print the smallest number of yen you have to spend to buy exactly N liters of ice tea.

Sample Input 1

20 30 70 90
3

Sample Output 1

150

Buy one 2-liter bottle and two 0.5-liter bottles. You'll get 3 liters for 90 + 30 + 30 = 150 yen.

Sample Input 2

10000 1000 100 10
1

Sample Output 2

100

Even though a 2-liter bottle costs just 10 yen, you need only 1 liter.
Thus, you have to buy a 1-liter bottle for 100 yen.

Sample Input 3

10 100 1000 10000
1

Sample Output 3

40

Now it's better to buy four 0.25-liter bottles for 10 + 10 + 10 + 10 = 40 yen.

Sample Input 4

12345678 87654321 12345678 87654321
123456789

Sample Output 4

1524157763907942

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.


open Scanf
open Printf

let flip f x y = f y x

let rec range a b = if a >= b then [] else a :: range (a+1) b

let read_int () = scanf " %d" (fun x -> x)
let rec read_ints n = if n = 0 then [] else let i = read_int () in i :: read_ints (n-1)

let rec for_iter a b f = if a >= b then [] else let x = f a in x :: for_iter (a+1) b f
let rec for_iter_ a b f = if a >= b then () else (f a; for_iter_ (a+1) b f)

let () =
  let [x; a; b] = read_ints 3 in
  printf "%s\n" @@ if (abs (x-a)) < (abs (x-b)) then "A" else "B"

Score : 100 points

Problem Statement

Snuke lives at position x on a number line.
On this line, there are two stores A and B, respectively at position a and b, that offer food for delivery.

Snuke decided to get food delivery from the closer of stores A and B.
Find out which store is closer to Snuke's residence.

Here, the distance between two points s and t on a number line is represented by |s-t|.

Constraints

1 \leq x \leq 1000

1 \leq a \leq 1000

1 \leq b \leq 1000

x, a and b are pairwise distinct.

The distances between Snuke's residence and stores A and B are different.

Input

Input is given from Standard Input in the following format:

x a b

Output

If store A is closer, print A; if store B is closer, print B.

Sample Input 1

5 2 7

Sample Output 1

B

The distances between Snuke's residence and stores A and B are 3 and 2, respectively.
Since store B is closer, print B.

Sample Input 2

1 999 1000

Sample Output 2

A


let () =
  let x, a, b = Scanf.scanf "%d %d %d" (fun x a b -> x, a, b) in
  print_endline (if abs (x - a) < abs (x - b) then "A" else "B")


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let c, p, m, i = ref 0, ref a_s.(0), ref 0, ref 0
let f d = Printf.printf "%d\n" d; exit 0
let g i a = if i = 1 then f @@ !m * a else m := a
let _ = Array.(sort (fun x y -> y - x) a_s; iter (fun a -> if a = !p then (incr c; if !c >= 4 then f @@ a * a) else (if !c >= 2 then (g !i !p; incr i); c := 1; p := a)) a_s); if !c >= 2 then g !i !p; f 0

Score : 300 points

Problem Statement

We have N sticks with negligible thickness.
The length of the i-th stick is A_i.

Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides.
Find the maximum possible area of the rectangle.

Constraints

4 \leq N \leq 10^5

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

6
3 1 2 4 2 1

Sample Output 1

2

1 \times 2 rectangle can be formed.

Sample Input 2

4
1 2 3 4

Sample Output 2

0

No rectangle can be formed.

Sample Input 3

10
3 3 3 3 4 4 4 5 5 5

Sample Output 3

20


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

let () =
  let n = read () in
  let a = Array.init n (fun _ -> read ()) in
  Array.fast_sort (fun x y -> y - x) a;
  let rec doit i pre =
    if i = n then 0
    else if a.(i-1) = a.(i) then begin
      if pre <> (-1) then pre * a.(i)
      else doit (i + 2) a.(i)
    end else doit (i + 1) pre in
  doit 1 (-1) |> Printf.printf "%d\n"


open Scanf
open Printf

let flip f x y = f y x

let rec range a b = if a >= b then [] else a :: range (a+1) b

let read_int () = scanf " %d" (fun x -> x)
let rec read_ints n = if n = 0 then [] else let i = read_int () in i :: read_ints (n-1)

let rec for_iter a b f = if a >= b then [] else let x = f a in x :: for_iter (a+1) b f
let rec for_iter_ a b f = if a >= b then () else (f a; for_iter_ (a+1) b f)

let list_of_string str = range 0 (String.length str) |> List.map (fun i -> str.[i])

type domino = H | V

let m = 1000000007

let mm x y = (x * y) mod m

let parse s =
  let rec f str = match str with
  | [] -> []
  | [_] -> [V]
  | (x::y::ys) -> if x = y then H :: f ys else V :: f (y::ys) in
  f (list_of_string s)

let calc xs =
  let f (p, a) x =
    match p, x with
    | H, H -> (H, mm 3 a)
    | H, V -> (V, a)
    | V, _ -> (x, mm 2 a) in
  match xs with
  | [] -> 1
  | (x::xs') -> List.fold_left f (x, 3) xs' |> snd

let () =
  let _ = read_line () in
  let _ = read_line () in
  read_line () |> parse |> calc |> printf "%d\n"

Score : 400 points

Problem Statement

We have a board with a 2 \times N grid.
Snuke covered the board with N dominoes without overlaps.
Here, a domino can cover a 1 \times 2 or 2 \times 1 square.

Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.

Find the number of such ways to paint the dominoes, modulo 1000000007.

The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:

Each domino is represented by a different English letter (lowercase or uppercase).

The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.

Constraints

1 \leq N \leq 52

|S_1| = |S_2| = N

S_1 and S_2 consist of lowercase and uppercase English letters.

S_1 and S_2 represent a valid arrangement of dominoes.

Input

Input is given from Standard Input in the following format:

N
S_1
S_2

Output

Print the number of such ways to paint the dominoes, modulo 1000000007.

Sample Input 1

3
aab
ccb

Sample Output 1

6

There are six ways as shown below:

Sample Input 2

1
Z
Z

Sample Output 2

3

Note that it is not always necessary to use all the colors.

Sample Input 3

52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn

Sample Output 3

958681902


exception Solved of string

module CharMap = Map.Make (Char)

let alphabet =
  [ 'a'; 'b'; 'c'; 'd'; 'e'; 'f'; 'g'; 'h'; 'i'; 'j'; 'k'; 'l'; 'm';
    'n'; 'o'; 'p'; 'q'; 'r'; 's'; 't'; 'u'; 'v'; 'w'; 'x'; 'y'; 'z']

let () =
  let a = read_line () in
  let trie = Array.make (String.length a + 1) CharMap.empty in
  for i = String.length a - 1 downto 0 do
    trie.(i) <- CharMap.add a.[i] (i + 1) trie.(i + 1)
  done;
  let dp = Array.make (String.length a + 1) (0, []) in
  for i = String.length a downto 0 do
    dp.(i) <-
      List.fold_left min (max_int, []) @@
      List.map (fun c ->
        match dp.(CharMap.find c trie.(i)) with
        | exception Not_found -> (1, [c])
        | (n, s) -> (1 + n, c :: s)) alphabet
  done;
  List.iter print_char (snd dp.(0));
  print_newline ()

Score : 600 points

Problem Statement

A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters.
For example, arc, artistic and (an empty string) are all subsequences of artistic; abc and ci are not.

You are given a string A consisting of lowercase English letters.
Find the shortest string among the strings consisting of lowercase English letters that are not subsequences of A.
If there are more than one such string, find the lexicographically smallest one among them.

Constraints

1 \leq |A| \leq 2 \times 10^5

A consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

A

Output

Print the lexicographically smallest string among the shortest strings consisting of lowercase English letters that are not subsequences of A.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a as a subsequence, but not b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

aa

Sample Input 3

frqnvhydscshfcgdemurlfrutcpzhopfotpifgepnqjxupnskapziurswqazdwnwbgdhyktfyhqqxpoidfhjdakoxraiedxskywuepzfniuyskxiyjpjlxuqnfgmnjcvtlpnclfkpervxmdbvrbrdn

Sample Output 3

aca


open Batteries
open Printf
let () =
  let a,b,c,d = Scanf.scanf "%d %d %d %d " (fun a b c d -> a,b,c,d) in
  let ans = (min b d) - (max a c) in
  Printf.printf "%d\n" @@
  if ans > 0 then ans else 0

Score : 200 points

Problem Statement

Alice and Bob are controlling a robot. They each have one switch that controls the robot.

Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up.

Bob started holding down his button C second after the start-up, and released his button D second after the start-up.

For how many seconds both Alice and Bob were holding down their buttons?

Constraints

0≤A<B≤100

0≤C<D≤100

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Sample Input 1

0 75 25 100

Sample Output 1

50

Alice started holding down her button 0 second after the start-up of the robot, and released her button 75 second after the start-up.

Bob started holding down his button 25 second after the start-up, and released his button 100 second after the start-up.

Therefore, the time when both of them were holding down their buttons, is the 50 seconds from 25 seconds after the start-up to 75 seconds after the start-up.

Sample Input 2

0 33 66 99

Sample Output 2

0

Alice and Bob were not holding their buttons at the same time, so the answer is zero seconds.

Sample Input 3

10 90 20 80

Sample Output 3

60


let gcd x y =
  let rec doit x y =
    if y = 0 then x
    else doit y (x mod y) in
  doit (max x y) (min x y)

let lcm x y = x / (gcd x y) * y

let () =
  let n = read_int () in
  Array.init n (fun _ -> read_int ())
  |> Array.fold_left lcm 1
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly T_i seconds.

Initially, the hand of every clock stands still, pointing directly upward.

Now, Dolphin starts all the clocks simultaneously.

In how many seconds will the hand of every clock point directly upward again?

Constraints

1≤N≤100

1≤T_i≤10^{18}

All input values are integers.

The correct answer is at most 10^{18} seconds.

Input

Input is given from Standard Input in the following format:

N
T_1
:
T_N

Output

Print the number of seconds after which the hand of every clock point directly upward again.

Sample Input 1

2
2
3

Sample Output 1

6

We have two clocks. The time when the hand of each clock points upward is as follows:

Clock 1: 2, 4, 6, ... seconds after the beginning

Clock 2: 3, 6, 9, ... seconds after the beginning

Therefore, it takes 6 seconds until the hands of both clocks point directly upward.

Sample Input 2

5
2
5
10
1000000000000000000
1000000000000000000

Sample Output 2

1000000000000000000


let n = read_int ()
let g, ds = Array.(make n [], make n 0)
let rec f v p s = ds.(v) <- s; List.iter (fun (u, d) -> if u <> p then f u v (s + d)) g.(v)
let _ = for _ = 1 to n - 1 do Scanf.scanf " %d %d %d" @@ fun a b c -> g.(a - 1) <- (b - 1, c) :: g.(a - 1); g.(b - 1) <- (a - 1, c) :: g.(b - 1) done;
  Scanf.scanf " %d %d" @@ fun q k -> f (k - 1) ~-1 0; for _ = 1 to q do Scanf.scanf " %d %d" @@ fun x y -> Printf.printf "%d\n" @@ ds.(x - 1) + ds.(y - 1) done

Score : 400 points

Problem Statement

You are given a tree with N vertices.

Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.

The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.

You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):

find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.

Constraints

3≤N≤10^5

1≤a_i,b_i≤N (1≤i≤N-1)

1≤c_i≤10^9 (1≤i≤N-1)

The given graph is a tree.

1≤Q≤10^5

1≤K≤N

1≤x_j,y_j≤N (1≤j≤Q)

x_j≠y_j (1≤j≤Q)

x_j≠K,y_j≠K (1≤j≤Q)

Input

Input is given from Standard Input in the following format:

N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}

Output

Print the responses to the queries in Q lines.

In the j-th line j(1≤j≤Q), print the response to the j-th query.

Sample Input 1

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

Sample Output 1

3
2
4

The shortest paths for the three queries are as follows:

Query 1: Vertex 2 → Vertex 1 → Vertex 2 → Vertex 4 : Length 1+1+1=3

Query 2: Vertex 2 → Vertex 1 → Vertex 3 : Length 1+1=2

Query 3: Vertex 4 → Vertex 2 → Vertex 1 → Vertex 3 → Vertex 5 : Length 1+1+1+1=4

Sample Input 2

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

Sample Output 2

5
14
22

The path for each query must pass Vertex K=2.

Sample Input 3

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

Sample Output 3

17000000000


open Printf
open Scanf

let () =
  let n, m = scanf "%d %d " (fun x y -> (x-1, y-1)) in
  printf "%d\n" (n * m)

Score : 100 points

Problem Statement

In K-city, there are n streets running east-west, and m streets running north-south. Each street running east-west and each street running north-south cross each other. We will call the smallest area that is surrounded by four streets a block. How many blocks there are in K-city?

Constraints

2 ≤ n, m ≤ 100

Input

Input is given from Standard Input in the following format:

n m

Output

Print the number of blocks in K-city.

Sample Input 1

3 4

Sample Output 1

6

There are six blocks, as shown below:

Sample Input 2

2 2

Sample Output 2

1

There are one block, as shown below:


let () =
  Scanf.scanf "%s\n" @@ fun s ->
  let len = String.length s in
  Printf.printf "%c%s%c\n" s.[0] (string_of_int (len-2)) s.[len-1]

Score : 200 points

Problem Statement

The word internationalization is sometimes abbreviated to i18n.
This comes from the fact that there are 18 letters between the first i and the last n.

You are given a string s of length at least 3 consisting of lowercase English letters.
Abbreviate s in the same way.

Constraints

3 ≤ |s| ≤ 100 (|s| denotes the length of s.)

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the abbreviation of s.

Sample Input 1

internationalization

Sample Output 1

i18n

Sample Input 2

smiles

Sample Output 2

s4s

Sample Input 3

xyz

Sample Output 3

x1z


let () =
  let s = read_line () in
  let n = String.length s in
  Printf.printf "%c%d%c\n" s.[0] (n - 2) s.[n-1]


let () =
  let n = Scanf.scanf "%d " (fun n -> n) in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun i -> i)) in
  let (e, o) = Array.fold_left (fun (x, y) e -> if e mod 2 = 0 then (x + 1, y) else (x, y + 1)) (0, 0) a in
  print_endline (if e = 0 || e = o || e <= o + 2 then "No" else "Yes")

Score : 400 points

Problem Statement

We have a sequence of length N, a = (a_1, a_2, ..., a_N).
Each a_i is a positive integer.

Snuke's objective is to permute the element in a so that the following condition is satisfied:

For each 1 ≤ i ≤ N - 1, the product of a_i and a_{i + 1} is a multiple of 4.

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute a so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


open Scanf
open Printf
open String;;

(* sscanf (read_line ()) "%d %d"
   (fun x y -> printf "%d" ((x-1)*(y-1)));; *)

(* let abb s = (sub s 0 1)
            ^ (string_of_int (length s - 2))
            ^ (sub s (length s - 1) 1);;

sscanf (read_line ()) "%s"
          (fun s -> printf "%s" (abb s));; *)

(*

let judge l =
  let len = List.length l in
  let f l = List.fold_left
              (fun (x,l') y -> if y mod 4==0 then (x+1,l') else (x,y::l')) (0,[]) l in
  let g l = List.fold_left (fun x y -> x + if y mod 2!=0 then 1 else 0) 0 l in
  let (four, fourl) = f l in
  four >= len/2 || g fourl <= four

let usage n =
  let list = ref [] in
  for i = 1 to n do
    list := (scanf (if i < n then "%d " else "%d") (fun x -> x))::!list
  done; !list;;

sscanf (read_line ()) "%d"
   (fun x -> printf "%s" (if judge (usage x) then "Yes" else "No"));;

*)

let usage n =
  let list = ref [] in
  for i = 1 to n do
    list := (scanf (if i < n then "%d " else "%d") (fun x -> x))::!list
  done; List.rev !list;;

let rec print_list = function
    [x] -> print_endline (string_of_int x)
  | x::xs -> print_string ((string_of_int x) ^ " "); print_list xs

and print_ll = function
    [] -> ()
  | x::xs -> print_list x; print_ll xs;;

let rec make_list ini = function
    0 -> []
  | n -> ini :: make_list ini (n-1);;

let make_line l =
  let rec make col = function
      [] -> []
    | x::xs -> make_list col x :: make (col+1) xs
  in List.concat (make 1 l);;

let rec take n = function
    [] -> []
  | x :: rest when n = 0  -> []
  | x :: rest -> x :: take (n-1) rest;;

let rec drop n = function
    [] -> []
  | x :: rest when n <= 0 -> x :: drop (n-1) rest
  | x :: rest -> drop (n-1) rest;;

let rec proc m n = function
  _ when n <= 0 || m <= 0 -> []
  | [] -> []
  | l when m mod 2 = 0 -> List.rev (take n l) :: proc (m-1) n (drop n l)
  | l when m mod 2 = 1 -> take n l :: proc (m-1) n (drop n l);;

sscanf (read_line ()) "%d %d" (fun m n ->
         scanf "%d" (fun x -> print_ll (proc m n (usage x))));;

Score : 400 points

Problem Statement

We have a grid with H rows and W columns of squares.
Snuke is painting these squares in colors 1, 2, ..., N.
Here, the following conditions should be satisfied:

For each i (1 ≤ i ≤ N), there are exactly a_i squares painted in Color i. Here, a_1 + a_2 + ... + a_N = H W.

For each i (1 ≤ i ≤ N), the squares painted in Color i are 4-connected. That is, every square painted in Color i can be reached from every square painted in Color i by repeatedly traveling to a horizontally or vertically adjacent square painted in Color i.

Find a way to paint the squares so that the conditions are satisfied.
It can be shown that a solution always exists.

Constraints

1 ≤ H, W ≤ 100

1 ≤ N ≤ H W

a_i ≥ 1

a_1 + a_2 + ... + a_N = H W

Input

Input is given from Standard Input in the following format:

H W
N
a_1 a_2 ... a_N

Output

Print one way to paint the squares that satisfies the conditions.
Output in the following format:

c_{1 1} ... c_{1 W}
:
c_{H 1} ... c_{H W}

Here, c_{i j} is the color of the square at the i-th row from the top and j-th column from the left.

Sample Input 1

2 2
3
2 1 1

Sample Output 1

1 1
2 3

Below is an example of an invalid solution:

1 2
3 1

This is because the squares painted in Color 1 are not 4-connected.

Sample Input 2

3 5
5
1 2 3 4 5

Sample Output 2

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

Sample Input 3

1 1
1
1

Sample Output 3

1


let rec foldn f a = function
  | 0 -> a
  | n -> foldn f (f a) (n - 1)

let () =
  let h, w = Scanf.scanf "%d %d\n" (fun h w -> h, w) in
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init n (fun i -> Scanf.scanf "%d " (fun a -> (i + 1, a))) in
  Array.fold_left (fun (acc, current, current_sum) (i, a) ->
    let c = Char.chr (i + Char.code '0') in
    if w <= current_sum + a then
      foldn (fun xs -> [String.make w c] :: xs)
        ((String.make (w - current_sum) c :: current) :: acc)
        ((current_sum + a) / w - 1), [String.make (current_sum + a - w) c], (current_sum + a - w) mod w
    else (acc, String.make a c :: current, a + current_sum)) ([], [], 0) as_
  |> (fun (acc, _, _) -> acc)
  |> List.fold_left (fun (acc, b) a -> ((if b then List.rev a else a) :: acc, not b)) ([], true)
  |> fst
  |> List.map (String.concat "")
  |> List.iter print_endline


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

Score : 100 points

Problem Statement

This contest, AtCoder Beginner Contest, is abbreviated as ABC.

When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.

What is the abbreviation for the N-th round of ABC? Write a program to output the answer.

Constraints

100 ≤ N ≤ 999

Input

Input is given from Standard Input in the following format:

N

Output

Print the abbreviation for the N-th round of ABC.

Sample Input 1

100

Sample Output 1

ABC100

The 100th round of ABC is ABC100.

Sample Input 2

425

Sample Output 2

ABC425

Sample Input 3

999

Sample Output 3

ABC999


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


let () =
  let n = read_int () in
  let rec doit x =
    let y = 2 * x in
    if y > n then x
    else doit y in
  doit 1 |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

Takahashi loves numbers divisible by 2.

You are given a positive integer N. Among the integers between 1 and N (inclusive), find the one that can be divisible by 2 for the most number of times. The solution is always unique.

Here, the number of times an integer can be divisible by 2, is how many times the integer can be divided by 2 without remainder.

For example,

6 can be divided by 2 once: 6 -> 3.

8 can be divided by 2 three times: 8 -> 4 -> 2 -> 1.

3 can be divided by 2 zero times.

Constraints

1 ≤ N ≤ 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

7

Sample Output 1

4

4 can be divided by 2 twice, which is the most number of times among 1, 2, ..., 7.

Sample Input 2

32

Sample Output 2

32

Sample Input 3

1

Sample Output 3

1

Sample Input 4

100

Sample Output 4

64


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

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

let () =
  let (n, m) = read_ns () in
  let g = Array.make n IntSet.empty in
  for _ = 1 to m do
    let (a, b) = read_ns () in
    let (a, b) = (a - 1, b - 1) in
    g.(a) <- IntSet.add b g.(a);
    g.(b) <- IntSet.add a g.(b);
  done;
  print_endline
    (if IntSet.is_empty (IntSet.inter g.(0) g.(n - 1)) then "IMPOSSIBLE"
     else "POSSIBLE")

Score : 300 points

Problem Statement

In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands.
For convenience, we will call them Island 1, Island 2, ..., Island N.

There are M kinds of regular boat services between these islands.
Each service connects two islands. The i-th service connects Island a_i and Island b_i.

Cat Snuke is on Island 1 now, and wants to go to Island N.
However, it turned out that there is no boat service from Island 1 to Island N, so he wants to know whether it is possible to go to Island N by using two boat services.

Help him.

Constraints

3 ≤ N ≤ 200 000

1 ≤ M ≤ 200 000

1 ≤ a_i < b_i ≤ N

(a_i, b_i) \neq (1, N)

If i \neq j, (a_i, b_i) \neq (a_j, b_j).

Input

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

If it is possible to go to Island N by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

You have to use three boat services to get to Island 4.

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

You can get to Island 5 by using two boat services: Island 1 -> Island 4 -> Island 5.


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

let bfs g goal =
  let que = Queue.create () in
  Queue.push 0 que;
  let rec doit depth reach_p =
    if reach_p && (depth = 2 || depth = 0) then "POSSIBLE"
    else if Queue.is_empty que || depth > 2 then "IMPOSSIBLE"
    else begin
      let n = Queue.pop que in
      let p = ref false in
      List.iter (fun e ->
        Queue.push e que; if e = goal then p := true)
        g.(n);
      doit (depth + 1) !p
    end in
  doit 0 false

let () =
  let (n, m) = read_ns () in
  let g = Array.make n [] in
  for _ = 0 to m - 1 do
    let (a, b) = read_ns () in
    let (a, b) = (a - 1, b - 1) in
    g.(a) <- b :: g.(a);
    g.(b) <- a :: g.(b);
  done;
  bfs g (n - 1) |> print_endline


Scanf.scanf "%d %d" (fun n m ->
    let s = Array.make 210000 0 in
    for i = 1 to m do
        Scanf.scanf " %d %d" (fun a b ->
            if a = 1 then s.(b) <- s.(b) lor 1;
            if b = 1 then s.(a) <- s.(a) lor 1;
            if a = n then s.(b) <- s.(b) lor 2;
            if b = n then s.(a) <- s.(a) lor 2;
        )
    done;
    let a = Array.fold_left (fun acc v -> if v = 3 then true else acc) false s in
    print_endline @@ if a then "POSSIBLE" else "IMPOSSIBLE"
)


let a, b = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> (a, b))

let () = if a mod 3 = 0 || b mod 3 = 0 || (a+b) mod 3 = 0 then
  print_endline "Possible"
else
  print_endline "Impossible"

Score : 100 points

Problem Statement

Snuke is giving cookies to his three goats.

He has two cookie tins. One contains A cookies, and the other contains B cookies. He can thus give A cookies, B cookies or A+B cookies to his goats (he cannot open the tins).

Your task is to determine whether Snuke can give cookies to his three goats so that each of them can have the same number of cookies.

Constraints

1 \leq A,B \leq 100

Both A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

If it is possible to give cookies so that each of the three goats can have the same number of cookies, print Possible; otherwise, print Impossible.

Sample Input 1

4 5

Sample Output 1

Possible

If Snuke gives nine cookies, each of the three goats can have three cookies.

Sample Input 2

1 1

Sample Output 2

Impossible

Since there are only two cookies, the three goats cannot have the same number of cookies no matter what Snuke gives to them.


let _ = Scanf.sscanf (read_line ()) "%d %d" (fun a b ->
  if a mod 3 = 0 || b mod 3 = 0 || a+b mod 3 = 0 then "Possible" else "Impossible"
) |> print_endline


let () =
  let (a, b) = Scanf.scanf "%d %d" (fun a b -> (a, b)) in
  print_endline
    (if List.exists (fun e -> e mod 3 = 0) [a; b; a + b] then "Possible"
     else "Impossible")


let () =
  let n, k = Scanf.scanf "%d %d" (fun n k -> n, k) in
  let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x)) in
  Array.sort (fun x y -> y - x) a;
  Array.sub a 0 k |> Array.fold_left (+) 0
  |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

Snuke has N sticks.
The length of the i-th stick is l_i.

Snuke is making a snake toy by joining K of the sticks together.

The length of the toy is represented by the sum of the individual sticks that compose it.
Find the maximum possible length of the toy.

Constraints

1 \leq K \leq N \leq 50

1 \leq l_i \leq 50

l_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
l_1 l_2 l_3 ... l_{N}

Output

Print the answer.

Sample Input 1

5 3
1 2 3 4 5

Sample Output 1

12

You can make a toy of length 12 by joining the sticks of lengths 3, 4 and 5, which is the maximum possible length.

Sample Input 2

15 14
50 26 27 21 41 7 42 35 7 5 5 36 39 1 45

Sample Output 2

386


Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let total = Array.fold_left (+) 0 a in
    let rec loop i acc best =
        if i = n - 1 then best else
            let acc = acc + a.(i) in
            loop (i + 1) acc (min best (abs (total - acc * 2)))
    in
    loop 0 0 max_int |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be x and y, respectively.
They would like to minimize |x-y|.
Find the minimum possible value of |x-y|.

Constraints

2 \leq N \leq 2 \times 10^5

-10^{9} \leq a_i \leq 10^{9}

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, x=10, y=11, and thus |x-y|=1. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, x=10, y=-10, and thus |x-y|=20.


let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun i -> i)) in
  let z = Array.fold_left (+) 0 a in
  let ans = ref max_int in
  for i = 0 to n - 2 do
    let t = abs (z - 2 * a.(i)) in
    if t < !ans then ans := t;
  done;
  Printf.printf "%d\n" !ans


module DirectedGraph
  (* 道の表現 *)
  (Path : sig
    type t
    (* 辺の名前 *)
    type edge
    (* 長さ0の道 *)
    val nil : t
    (* 道の後ろに辺を付け足した道 *)
    val snoc : t -> edge -> t
  end) :
sig
  (* BFSにより，重みのないグラフの最短経路を求める *)
  val bfs :
    (* 頂点数（Hashtblを用いるので目安程度） *)
    int ->
    (* 辺の名前が付いた隣接リスト *)
    ('v -> ('v * Path.edge) list) ->
    (* 始点 *)
    'v ->
    (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
    ('v -> Path.t option)
end = struct
  let rec bfs_aux es d frontier t =
    try Some (Hashtbl.find d t) with
    | Not_found ->
        match !frontier with
        | [] -> None
        | _ :: _ ->
            frontier := List.fold_right (fun u ->
              List.fold_right (fun (v, e) frontier ->
                if Hashtbl.mem d v
                then frontier
                else (Hashtbl.add d v (Path.snoc (Hashtbl.find d u) e); v :: frontier))
              (es u)) !frontier [];
            bfs_aux es d frontier t

  (*
   * 終点に辿り着いた時点で探索を切り上げるが，
   * 戻り値の関数を覚えておくと，途中まで探索した結果が再利用される
   * （#trace bfs_aux すると分かりやすい）
   *)
  let bfs n es s =
    let d = Hashtbl.create n in
    Hashtbl.add d s Path.nil;
    let frontier = ref [s] in
    bfs_aux es d frontier
end

(* 配列版素集合データ構造 *)
module RawUnionFind : sig
  type t
  type class_

  (* n要素の素集合データ構造を作る *)
  val make : int -> t
  (* 要素がどの集合に属するか調べる *)
  (* 要素は0からn-1の整数である必要がある *)
  val find : t -> int -> class_
  (* 与えられた要素が属する集合同士を合併する *)
  val unite : t -> int -> int -> unit

  val compare_class : class_ -> class_ -> int
end = struct
  type t = { rank : int array; parent : int array }
  type class_ = int

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

  let rec find uf x =
    if x = uf.parent.(x) then x
    else begin
      let y = find uf uf.parent.(x) in
      uf.parent.(x) <- y; y
    end

  let unite uf i j =
    let x = find uf i in
    let y = find uf j in
    if x <> y then begin
      if uf.rank.(x) < uf.rank.(y) then uf.parent.(x) <- y
      else begin
        uf.parent.(y) <- x;
        if uf.rank.(x) = uf.rank.(y) then
          uf.rank.(x) <- 1 + uf.rank.(x)
      end
    end

  let compare_class = compare
end

module G = DirectedGraph (struct
  type t = int list
  type edge = int
  let nil = []
  let snoc t e = e :: t
end)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let abs = Array.init (n - 1) @@ fun _ ->
    Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
  let es = Array.make n [] in
  Array.iteri (fun i (a, b) ->
    es.(a - 1) <- (b - 1, i) :: es.(a - 1);
    es.(b - 1) <- (a - 1, i) :: es.(b - 1)) abs;
  let (Some route) = G.bfs n (fun v -> es.(v)) 0 (n - 1) in
  let i = List.nth route (List.length route / 2) in
  let uf = RawUnionFind.make n in
  Array.iteri (fun j (a, b) ->
    if i <> j then RawUnionFind.unite uf (a - 1) (b - 1)) abs;
  print_endline @@
    if
      List.length (List.filter (fun i ->
        RawUnionFind.compare_class (RawUnionFind.find uf 0) (RawUnionFind.find uf i) = 0)
      @@ Array.to_list @@ Array.init n @@ fun i -> i)
      < List.length (List.filter (fun i ->
          RawUnionFind.compare_class (RawUnionFind.find uf (n - 1)) (RawUnionFind.find uf i) = 0)
        @@ Array.to_list @@ Array.init n @@ fun i -> i)
    then "Snuke" else "Fennec"

Score : 400 points

Problem Statement

Fennec and Snuke are playing a board game.

On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.

Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored.
Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell.
More specifically, each player performs the following action in her/his turn:

Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.

Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.

A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.

Constraints

2 \leq N \leq 10^5

1 \leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

If Fennec wins, print Fennec; if Snuke wins, print Snuke.

Sample Input 1

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

Sample Output 1

Fennec

For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves.

Sample Input 2

4
1 4
4 2
2 3

Sample Output 2

Snuke


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

let rec solve e us vs =
  IntSet.exists (fun v ->
    List.exists (fun v' ->
      not (IntSet.mem v' vs) &&
      not (IntSet.mem v' us) &&
      not (solve e (IntSet.add v' vs) us)) (e v)) vs

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let abs = Array.init (n - 1)
    (fun _ -> Scanf.scanf "%d %d\n" (fun a b -> a, b)) in
  solve
    (let e = Array.make n [] in
     Array.iter (fun (a, b) ->
       e.(a - 1) <- b - 1 :: e.(a - 1);
       e.(b - 1) <- a - 1 :: e.(b - 1)) abs;
     fun v -> e.(v))
    (IntSet.singleton (n - 1))
    (IntSet.singleton 0)
  |> (function true -> "Fennec" | false -> "Snuke")
  |> print_endline


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

Score : 100 points

Problem Statement

Snuke is buying a bicycle.
The bicycle of his choice does not come with a bell, so he has to buy one separately.

He has very high awareness of safety, and decides to buy two bells, one for each hand.

The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively.
Find the minimum total price of two different bells.

Constraints

1 \leq a,b,c \leq 10000

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print the minimum total price of two different bells.

Sample Input 1

700 600 780

Sample Output 1

1300

Buying a 700-yen bell and a 600-yen bell costs 1300 yen.

Buying a 700-yen bell and a 780-yen bell costs 1480 yen.

Buying a 600-yen bell and a 780-yen bell costs 1380 yen.

The minimum among these is 1300 yen.

Sample Input 2

10000 10000 10000

Sample Output 2

20000

Buying any two bells costs 20000 yen.


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let ps = [|[]; []|]
let _ = Array.iteri (fun i a -> ps.(i mod 2) <- a :: ps.(i mod 2)) a_s;
  List.(ps.(1 - n mod 2) @ rev @@ ps.(n mod 2) |> iteri (fun i n -> Printf.printf (if i = 0 then "%d" else " %d") n)); print_newline ()

Score : 300 points

Problem Statement

You are given an integer sequence of length n, a_1, ..., a_n.
Let us consider performing the following n operations on an empty sequence b.

The i-th operation is as follows:

Append a_i to the end of b.

Reverse the order of the elements in b.

Find the sequence b obtained after these n operations.

Constraints

1 \leq n \leq 2\times 10^5

0 \leq a_i \leq 10^9

n and a_i are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print n integers in a line with spaces in between.
The i-th integer should be b_i.

Sample Input 1

4
1 2 3 4

Sample Output 1

4 2 1 3

After step 1 of the first operation, b becomes: 1.

After step 2 of the first operation, b becomes: 1.

After step 1 of the second operation, b becomes: 1, 2.

After step 2 of the second operation, b becomes: 2, 1.

After step 1 of the third operation, b becomes: 2, 1, 3.

After step 2 of the third operation, b becomes: 3, 1, 2.

After step 1 of the fourth operation, b becomes: 3, 1, 2, 4.

After step 2 of the fourth operation, b becomes: 4, 2, 1, 3.

Thus, the answer is 4 2 1 3.

Sample Input 2

3
1 2 3

Sample Output 2

3 1 2

As shown above in Sample Output 1, b becomes 3, 1, 2 after step 2 of the third operation. Thus, the answer is 3 1 2.

Sample Input 3

1
1000000000

Sample Output 3

1000000000

Sample Input 4

6
0 6 7 6 7 0

Sample Output 4

0 6 6 0 7 7


let n = Scanf.scanf "%d" (fun x -> x)
let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))
let () =
  for i = 0 to (n-1)/2 do
    Printf.printf "%d " a.(n-1-2*i)
  done;
  let o = n mod 2 in
  for i = 0 to n/2-1 do
    Printf.printf "%d " a.(2*i + o)
  done;
  print_newline ()


let x, a, b = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = print_endline @@ if a >= b then "delicious" else if b - a <= x then "safe" else "dangerous"

Score : 100 points

Problem Statement

Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier.
He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.

Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Otherwise, he does not find it delicious.

Takahashi bought some food A days before the "best-by" date, and ate it B days after he bought it.

Write a program that outputs delicious if he found it delicious, safe if he did not found it delicious but did not get a stomachache either, and dangerous if he got a stomachache.

Constraints

1 ≤ X,A,B ≤ 10^9

Input

Input is given from Standard Input in the following format:

X A B

Output

Print delicious if Takahashi found the food delicious; print safe if he neither found it delicious nor got a stomachache; print dangerous if he got a stomachache.

Sample Input 1

4 3 6

Sample Output 1

safe

He ate the food three days after the "best-by" date. It was not delicious or harmful for him.

Sample Input 2

6 5 1

Sample Output 2

delicious

He ate the food by the "best-by" date. It was delicious for him.

Sample Input 3

3 7 12

Sample Output 3

dangerous

He ate the food five days after the "best-by" date. It was harmful for him.


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" pred
let j = ref 0
let _ = for i = 1 to n do j := a_s.(!j); if !j = 1 then (Printf.printf "%d\n" i; exit 0) done; print_endline "-1"

Score : 200 points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up.
These buttons are numbered 1 through N.
When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It is possible that i=a_i.
When Button i is not lighten up, nothing will happen by pressing it.

Initially, Button 1 is lighten up. Takahashi wants to quit pressing buttons when Button 2 is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

Print -1 if it is impossible to lighten up Button 2.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button 2.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button 1, then Button 3.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button 1 lightens up Button 3, and vice versa, so Button 2 will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3


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

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

let rec f i ans s =
  let a = ar.(i-1) in
  if Ints.mem a s then -1
  else if a = 2 then succ ans
  else f a (succ ans) (Ints.add a s)

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


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

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

let rec solve n cnt list =
  if n = 1 then cnt else
    if List.mem n list then -1 else
      solve (array.(n) - 1) (cnt + 1) ((array.(n) - 1) :: list)

let ans = solve 0 0 []

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


let () =
  let i = 1000000007 in
  let fact a =
    let rec fact_aux x tmp =
      if x = 1 then tmp mod i else fact_aux (x - 1) (tmp * x mod i)
    in
    fact_aux a 1
  in
  let f n m = fact n mod i * fact m mod i in
  let dogs, monkeys = Scanf.scanf "%d %d" (fun x y -> (x, y)) in
  ( match abs (dogs - monkeys) with
    | 0 -> f dogs monkeys * 2 mod i
    | 1 -> f dogs monkeys mod i
    | _ -> 0 )
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

Snuke has N dogs and M monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo 10^9+7 (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

1 ≤ N,M ≤ 10^5

Input

Input is given from Standard Input in the following format:

N M

Output

Print the number of possible arrangements, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477


let init n = Array.make n (-1)

let rec find x p =
  if p.(x) < 0 then x else begin
    let x' = find p.(x) p in p.(x) <- x'; x'
  end

let unite x y p =
  let x', y' = find x p, find y p in
  if x' = y' then () else
  if p.(x') < p.(y') then (p.(y') <- x)
  else begin
    if p.(x') = p.(y') then p.(y') <- p.(y') - 1;
    p.(x') <- y'
  end

let same x y p = find x p = find y p

let () =
  Scanf.scanf "%d" @@ fun n ->
  let cs = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
  let xs, ys =
    Array.mapi (fun i (x,_) -> (x,i)) cs, Array.mapi (fun i (_,y) -> (y,i)) cs in

  Array.sort compare xs; Array.sort compare ys;

  let edges = Array.concat [
    Array.init (n-1) (fun i ->
      let (x0,i), (x1,j) = xs.(i+1), xs.(i) in (x0-x1, i, j));
    Array.init (n-1) (fun i ->
      let (y0,i), (y1,j) = ys.(i+1), ys.(i) in (y0-y1, i, j));
  ] in
  Array.sort compare edges;

  let uf = Array.make n (-1) in
  Array.fold_left (fun sw (d, i, j) ->
    if same i j uf then sw
    else (unite i j uf; sw+d)) 0 edges
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample Input 1

3
1 5
3 9
7 8

Sample Output 1

3

Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.

Sample Input 2

6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2

8


Scanf.scanf "%s" (fun s ->
    let h = Array.make 26 false in
    String.iter (fun c -> h.(int_of_char c - 97) <- true) s;
    let rec chl c s cnt =
        let n = String.length s in
        let rec loop i =
            if i = n then true else
                if s.[i] = c then loop (i + 1) else false
        in
        if loop 0 then cnt else
            let s = String.init (n - 1) (fun i ->
                if s.[i] = c || s.[i + 1] = c then c else s.[i])
            in
            chl c s (cnt + 1)
    in
    let rec loop i acc =
        if i = 26 then acc else
            if h.(i) then loop (i + 1) (min acc (chl (char_of_int (i + 97)) s 0))
                      else loop (i + 1) acc
    in
    loop 0 max_int |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:

For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.

There is a string s consisting of lowercase English letters.
Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same.
Find the minimum necessary number of operations.

Constraints

1 ≤ |s| ≤ 100

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

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

Sample Input 1

serval

Sample Output 1

3

One solution is: serval → srvvl → svvv → vvv.

Sample Input 2

jackal

Sample Output 2

2

One solution is: jackal → aacaa → aaaa.

Sample Input 3

zzz

Sample Output 3

0

All the characters in s are the same from the beginning.

Sample Input 4

whbrjpjyhsrywlqjxdbrbaomnw

Sample Output 4

8

In 8 operations, he can change s to rrrrrrrrrrrrrrrrrr.


print_endline @@
  Scanf.scanf "%d" @@ fun n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  Array.sort (-) a;
  let l, r = a.(0), a.(n-1) in
  if r-l >= 2 then "No" else
  if l = r then
    if n = l + 1 || n >= 2 * l then "Yes" else "No"
  else
  (* l+1 = r *)
  let lc = Array.fold_left (fun s x -> s + a.(n-1) - x) 0 a in
  let rc = n - lc in
  if lc < l && rc >= 2 * (r-lc) then "Yes" else "No"

Score : 700 points

Problem Statement

There are N cats.
We number them from 1 through N.

Each of the cats wears a hat.
Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me."

Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats.

Constraints

2 ≤ N ≤ 10^5

1 ≤ a_i ≤ N-1

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print Yes if there exists a sequence of colors of the hats that is consistent with the remarks of the cats; print No otherwise.

Sample Input 1

3
1 2 2

Sample Output 1

Yes

For example, if cat 1, 2 and 3 wears red, blue and blue hats, respectively, it is consistent with the remarks of the cats.

Sample Input 2

3
1 1 2

Sample Output 2

No

From the remark of cat 1, we can see that cat 2 and 3 wear hats of the same color.
Also, from the remark of cat 2, we can see that cat 1 and 3 wear hats of the same color.
Therefore, cat 1 and 2 wear hats of the same color, which contradicts the remark of cat 3.

Sample Input 3

5
4 3 4 3 4

Sample Output 3

No

Sample Input 4

3
2 2 2

Sample Output 4

Yes

Sample Input 5

4
2 2 2 2

Sample Output 5

Yes

Sample Input 6

5
3 3 3 3 3

Sample Output 6

No


let result = Scanf.scanf "%d %d %d\n" (fun x y z -> if (10*y+z) mod 4 = 0 then "YES" else "NO") ;;
print_endline result;;

Score : 100 points

Problem Statement

AtCoDeer has three cards, one red, one green and one blue.

An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.

We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.

Is this integer a multiple of 4?

Constraints

1 ≤ r, g, b ≤ 9

Input

Input is given from Standard Input in the following format:

r g b

Output

If the three-digit integer is a multiple of 4, print YES (case-sensitive); otherwise, print NO.

Sample Input 1

4 3 2

Sample Output 1

YES

432 is a multiple of 4, and thus YES should be printed.

Sample Input 2

2 3 4

Sample Output 2

NO

234 is not a multiple of 4, and thus NO should be printed.


let result = Scanf.scanf " %d %d %d/n" (fun x y z -> if 10*y+z mod 4 = 0 then true else false) ;;
match result with
| true -> print_endline "YES";
| false -> print_endline "NO";


Scanf.scanf "%d" @@ fun n ->
  let a_s = Array.init n @@ fun i -> Scanf.scanf " %d" @@ (+) 0 in
  Array.sort compare a_s;
  a_s.(Array.length a_s - 1) - a_s.(0) |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.

There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.

Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.

Constraints

1 ≤ N ≤ 100

0 ≤ a_i ≤ 1000

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum distance to be traveled.

Sample Input 1

4
2 3 7 9

Sample Output 1

7

The travel distance of 7 can be achieved by starting at coordinate 9 and traveling straight to coordinate 2.

It is not possible to do with a travel distance of less than 7, and thus 7 is the minimum distance to be traveled.

Sample Input 2

8
3 1 4 1 5 9 2 6

Sample Output 2

8

There may be more than one house at a position.


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_, bs =
    List.partition (( <= ) 3200) @@
    Array.to_list @@
    Array.init n @@ fun _ ->
      Scanf.scanf "%d " @@ fun a -> a in
  let x = List.length as_ in
  let y =
    List.length @@
    List.sort_uniq compare @@
    List.map (fun a -> a / 400) bs in
  Printf.printf "%d %d\n" (max (min 1 x) y) (x + y)

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


open Str
open List

let get_int () = int_of_string (read_line ());;

let rec to_int sep =
    match sep with
    | [] -> []
    | a :: b ->
            (int_of_string a) :: (to_int b);;

let rec to_color rates =
    match rates with
    | [] -> []
    | fst :: rst -> (fst / 400) :: (to_color rst)

let rec print_int_arr arr =
    match arr with
    | [] -> ()
    | fst :: rst -> Printf.printf "%d\n" fst; print_int_arr rst;;

let get_int_arr () =
    to_int (Str.split (Str.regexp " ") (read_line ()));;

let main =
    let _ = read_line () in
    let a = to_color (get_int_arr ()) in
    let const = List.length (List.sort_uniq (fun x y -> x - y) (List.filter (fun b -> b < 8) a)) in
    let change = List.length (List.filter (fun b -> b > 7) a) in

    Printf.printf "%d " const;
    Printf.printf "%d\n" (if const + change < 9 then const + change else 8);


open Str

let () =
  let _ = read_line () in
  let s = split (regexp "") (read_line ()) in
  let f (l, st) x =
    match st with
      [] -> if x = ")" then (l+1, []) else (l, ["("])
    | y :: ys -> if x = ")" && y = "(" then (l, ys) else (l, "("::y::ys) in
  let (l, r) = List.fold_left f (0,[]) s in
  String.make l '(' ^ String.concat "" s ^ String.make (List.length r) ')' |> print_endline

Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))


let f a b =
  let s = a + b in
  if s >= 10 then print_endline "error"
  else Printf.printf "%d\n" s

let () = Scanf.scanf "%d %d" f

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


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

let array = Array.init n (fun _ -> Scanf.scanf "%d\n" id)
let () = Array.sort compare array
let l = Array.length array

let rec pl i =
  if i = l then 0 else
    array.(i) + pl (i+1)

let rec func max i =
  if i = l then 0 else
    if ((max - array.(i)) mod 10 <> 0) then max - array.(i) else
      func max (i+1)

let m = pl 0
let ans = if m mod 10 <> 0 then m else func (pl 0) 0

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

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.


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

let array = Array.init n (fun _ -> Scanf.scanf "%d\n" id)
let l = Array.length array

let rec pl i =
  if i = l then 0 else
    array.(i) + pl (i+1)

let rec func max i =
  if i = l then 0 else
    if ((max - array.(i)) mod 10 <> 0) then max - array.(i) else
      func max (i+1)

let m = pl 0
let ans = if m mod 10 <> 0 then m else func (pl 0) 0

let () =
  Array.sort compare array;
  Printf.printf "%d\n" ans


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

let array = Array.init n (fun _ -> Scanf.scanf "%d\n" id)
let () = Array.sort compare array
let l = Array.length array

let max = array.(l-1) / b

let rec func1 tmid i m =
  if i = l then m else
    let x = array.(i) - b*tmid in
    if x < 0 then func1 tmid (i+1) m
    else if x mod (a-b) = 0 then func1 tmid (i+1) (m + x/(a-b))
    else func1 tmid (i+1) (m + 1+x/(a-b))

let rec func tmin tmax =
  let tmid = (tmax + tmin) / 2 in
  let tsuika = func1 tmid 0 0 in
  if tsuika <= tmid then (if tmax - tmin = 1 then tmin else func tmin tmid)
  else (if tmax - tmin = 1 then tmax else func tmid tmax)

let ans = if max <= 1 then 1 else func 1 max

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

Score : 400 points

Problem Statement

You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.

Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:

Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by A, and the health of each of the other monsters will decrease by B. Here, A and B are predetermined parameters, and A > B holds.

At least how many explosions do you need to cause in order to vanish all the monsters?

Constraints

All input values are integers.

1 ≤ N ≤ 10^5

1 ≤ B < A ≤ 10^9

1 ≤ h_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N A B
h_1
h_2
:
h_N

Output

Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

You can vanish all the monsters in two explosion, as follows:

First, cause an explosion centered at the monster with 8 health. The healths of the four monsters become 3, 4, 1 and -1, respectively, and the last monster vanishes.

Second, cause an explosion centered at the monster with 4 health remaining. The healths of the three remaining monsters become 0, -1 and -2, respectively, and all the monsters are now vanished.

Sample Input 2

2 10 4
20
20

Sample Output 2

4

You need to cause two explosions centered at each monster, for a total of four.

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000


let () = Scanf.scanf "%d %d\n"
	(fun x y -> let l = [4;6;9;11] in
    Printf.printf "%s\n"
    (if List.mem x l && List.mem y l || x = 2 && y = 2 || x <> 2 && y <> 2 && not (List.mem x l || List.mem y l)
    then "Yes" else "No"))

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


let g x = if List.mem x [4;6;9;11] then 1 else (if List.mem x [2] then 2 else 3);;
let calc a b = if g a=g b then "Yes" else "No";;
Scanf.scanf "%d %d" calc
|> Printf.printf "%s\n"


let h, w = Scanf.scanf " %d %d" @@ fun a b -> a, b
let a_ss = Array.init h @@ fun _ -> Scanf.scanf " %s" @@ fun s -> s
let s = String.make (w + 2) '#'
let _ = print_endline s; Array.iter (Printf.printf "#%s#\n") a_ss; print_endline s

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

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

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


let () =
  let h, w = Scanf.scanf "%d %d" (fun h w -> h, w) in
  let a = Array.init h (fun _ -> Scanf.scanf " %s" (fun s -> s)) in
  String.init (w+2) (fun _ -> '#') |> print_endline;
  Array.iter (Printf.printf "#%s#\n") a;
  String.init (w+2) (fun _ -> '#') |> print_endline


let diff3 a b c = max a (max b c) - min a (min b c)
let calc a b =
  let sub_calc s0 a' b' =
    let d0 = diff3 s0 (a'/2*b') ((a'-a'/2)*b') in
    let d1 = diff3 s0 (b'/2*a') ((b'-b'/2)*a') in
    min d0 d1
  in
  [ sub_calc (a/3*b) (a-a/3) b;
    sub_calc ((a+3)/3*b) (a-(a+3)/3) b;
    sub_calc (b/3*a) a (b-b/3);
    sub_calc ((b+3)/3*a) a (b-(b+3)/3);
  ] |> List.fold_left min 1010101010101010
let h, w = Scanf.scanf "%d %d" (fun x y -> x, y)
let () = calc h w |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

There is a bar of chocolate with a height of H blocks and a width of W blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize S_{max} - S_{min}, where S_{max} is the area (the number of blocks contained) of the largest piece, and S_{min} is the area of the smallest piece.
Find the minimum possible value of S_{max} - S_{min}.

Constraints

2 ≤ H, W ≤ 10^5

Input

Input is given from Standard Input in the following format:

H W

Output

Print the minimum possible value of S_{max} - S_{min}.

Sample Input 1

3 5

Sample Output 1

0

In the division below, S_{max} - S_{min} = 5 - 5 = 0.

Sample Input 2

4 5

Sample Output 2

2

In the division below, S_{max} - S_{min} = 8 - 6 = 2.

Sample Input 3

5 5

Sample Output 3

4

In the division below, S_{max} - S_{min} = 10 - 6 = 4.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000


module DirectedGraph
  (* 道の表現 *)
  (Path : sig
    type t
    (* 辺の名前 *)
    type edge
    (* 長さ0の道 *)
    val nil : t
    (* 道の後ろに辺を付け足した道 *)
    val snoc : t -> edge -> t
  end) :
sig
  (* BFSにより，重みのないグラフの最短経路を求める *)
  val bfs :
    (* 頂点数（Hashtblを用いるので目安程度） *)
    int ->
    (* 辺の名前が付いた隣接リスト *)
    ('v -> ('v * Path.edge) list) ->
    (* 始点 *)
    'v ->
    (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
    ('v -> Path.t option)
end = struct
  let rec bfs_aux es d frontier t =
    try Some (Hashtbl.find d t) with
    | Not_found ->
        match !frontier with
        | [] -> None
        | _ :: _ ->
            frontier := List.fold_right (fun u ->
              List.fold_right (fun (v, e) frontier ->
                if Hashtbl.mem d v
                then frontier
                else (Hashtbl.add d v (Path.snoc (Hashtbl.find d u) e); v :: frontier))
              (es u)) !frontier [];
            bfs_aux es d frontier t

  (*
   * 終点に辿り着いた時点で探索を切り上げるが，
   * 戻り値の関数を覚えておくと，途中まで探索した結果が再利用される
   * （#trace bfs_aux すると分かりやすい）
   *)
  let bfs n es s =
    let d = Hashtbl.create n in
    Hashtbl.add d s Path.nil;
    let frontier = ref [s] in
    bfs_aux es d frontier
end

module FlowNetwork
  (* 流量 *)
  (Flow : sig
    type t
    val inf : t
    val zero : t
    val ( + ) : t -> t -> t
    val ( - ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  val max_flow :
    (* 頂点の数（Hashtblを用いるので目安程度） *)
    int ->
    (* 各辺とその逆辺の容量 *)
    ('v * 'v * Flow.t * Flow.t) list ->
    (* 始点 *)
    'v ->
    (* 終点 *)
    'v ->
    (* 最大フロー *)
    Flow.t
end =
struct
  module G = DirectedGraph (struct
    type t = int
    type edge = unit
    let nil = 0
    let snoc t _ = t + 1
  end)

  (* 増加パスをDFSで探し，流せるだけ流していく *)
  let rec dfs capacity add_edge iter level v t f =
    if v = t then f
    else begin
      let rec find () =
        match Hashtbl.find iter v with
        | exception Not_found -> Flow.zero
        | (u, i) ->
            Hashtbl.remove iter v;
            (* capacity i <= 0 *)
            if Flow.compare (capacity i) Flow.zero <= 0 || level u <= level v then find ()
            else begin
              let d = dfs capacity add_edge iter level u t @@
                (* min f (capacity i) *)
                if Flow.compare f (capacity i) <= 0 then f else capacity i in
              (* d <= 0 *)
              if Flow.compare d Flow.zero <= 0 then find ()
              else (add_edge i d; d)
            end in find ()
    end

  let max_flow n es s t =
    assert (s <> t);
    (* 各辺に流せる流量 *)
    let capacity = Array.make (2 * List.length es) Flow.zero in
    (* 逆辺を張りつつ，隣接リスト形式に変換 *)
    let adj = Hashtbl.create n in
    List.iteri (fun i (u, v, c, c') ->
      (* 各辺は番号で管理する *)
      Hashtbl.add adj u (v, 2 * i);
      (* 容量はcapacityを見てほしい *)
      capacity.(2 * i) <- c;
      (* 逆辺 *)
      Hashtbl.add adj v (u, 2 * i + 1);
      capacity.(2 * i + 1) <- c') es;
    (* 番号iの辺にcだけフローを流す *)
    let add_edge i c =
      let open Flow in
      capacity.(i) <- capacity.(i) - c;
      (* 逆辺 *)
      capacity.(i lxor 1) <- capacity.(i lxor 1) + c in
    let rec outer flow =
      let level = G.bfs n (fun v ->
        List.concat @@ List.map (fun (u, i) ->
          if Flow.compare capacity.(i) Flow.zero <= 0 then []
          else [(u, ())]) @@ Hashtbl.find_all adj v) s in
      if level t = None then flow
      else
        let iter = Hashtbl.copy adj in
        let rec inner flow =
          let f = dfs (fun i -> capacity.(i)) add_edge iter level s t Flow.inf in
          if Flow.compare f Flow.zero <= 0 then flow
          else inner (Flow.( + ) flow f) in
        outer @@ inner flow in
    outer Flow.zero
end

module G = FlowNetwork (struct
  include Pervasives
  type t = int
  let zero = 0
  let inf = max_int
end)

let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ass = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let yxs =
    List.concat @@ Array.to_list @@ Array.init h @@ fun y ->
      Array.to_list @@ Array.init w @@ fun x -> y, x in
  let [(sy, sx); (ty, tx)] =
    List.map (fun c ->
      List.find (fun (y, x) -> ass.(y).[x] = c) yxs) ['S'; 'T'] in
  Printf.printf "%d\n" @@
  if sy = ty || sx = tx then -1
  else G.max_flow (2 + h + w)
    (List.concat @@ List.map (fun (y, x) ->
      match ass.(y).[x] with
      | '.' -> []
      | 'S' -> [(`Source, `Col x, 1, 0); (`Source, `Row y, 1, 0)]
      | 'T' -> [(`Sink, `Col x, 0, 1); (`Sink, `Row y, 0, 1)]
      | 'o' -> [(`Col x, `Row y, 1, 1)]) yxs) `Source `Sink

Score : 800 points

Problem Statement

There is a pond with a rectangular shape.
The pond is divided into a grid with H rows and W columns of squares.
We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).

Some of the squares in the pond contains a lotus leaf floating on the water.
On one of those leaves, S, there is a frog trying to get to another leaf T.
The state of square (i,\ j) is given to you by a character a_{ij}, as follows:

. : A square without a leaf.

o : A square with a leaf floating on the water.

S : A square with the leaf S.

T : A square with the leaf T.

The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."

Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T.
Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.

Constraints

2 ≤ H, W ≤ 100

a_{ij} is ., o, S or T.

There is exactly one S among a_{ij}.

There is exactly one T among a_{ij}.

Input

Input is given from Standard Input in the following format:

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

Output

If the objective is achievable, print the minimum necessary number of leaves to remove.
Otherwise, print -1 instead.

Sample Input 1

3 3
S.o
.o.
o.T

Sample Output 1

2

Remove the upper-right and lower-left leaves.

Sample Input 2

3 4
S...
.oo.
...T

Sample Output 2

0

Sample Input 3

4 3
.S.
.o.
.o.
.T.

Sample Output 3

-1

Sample Input 4

10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo

Sample Output 4

5


let solve (a : int) (b : int) (c : int) : string = if c >= a && c <= b then "Yes" else "No"

let () = Printf.printf "%s\n" (Scanf.scanf "%d %d %d" solve)

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


let () =
  let n, m = Scanf.scanf "%d %d" (fun n m -> n, m) in
  let es = Array.init m (fun _ -> Scanf.scanf " %d %d" (fun a b -> a-1, b-1)) in
  Array.init n (fun i ->
    Array.map (fun (a, b) -> if i = a || i = b then 1 else 0) es |> Array.fold_left (+) 0)
  |> Array.iter (Printf.printf "%d\n")

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let ab_s = Array.init n @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = Array.(sort compare ab_s; fold_left (fun r (a, b) -> if r + b >= k then (Printf.printf "%d\n" a; exit 0); r + b) 0 ab_s)

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


open Batteries
let n, k = Scanf.scanf "%d %d" (fun x y -> x, y)
let arr = Array.make 100010 0
let () =
  (1--n) |> Enum.iter begin fun _ ->
    Scanf.scanf " %d %d" (fun a b -> arr.(a) <- arr.(a) + b)
  end;
  (1--n) |> Enum.iter begin fun i ->
    arr.(i) <- arr.(i) + arr.(i-1)
  end;
  Array.findi (fun v -> v >= k) arr
  |> Printf.printf "%d\n"


let rec fold_n n f v = if n <= 0 then v else fold_n (n-1) f (f v)
let inf = 10101010101010

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

  let reach = begin
    let g = Array.init n (fun _ -> []) in
    a |> Array.iter (fun (u,v,_) -> g.(v) <- u :: g.(v));
    let vis = Array.make n false in
    let rec f u =
      vis.(u) <- true;
      List.iter (fun v -> if not vis.(v) then f v) g.(u)
    in f 0;
    vis
  end in

  let sc = Array.make n (-inf) in sc.(0) <- 0;
  let mem = Array.make n false in
  let has_loop = true |> fold_n (2*n) (fun upd ->
    if not upd then false else begin
      Array.fill mem 0 n false;
      Array.fold_left (fun b (u,v,c) ->
        let b' = sc.(u) + c > sc.(v) in
        if b' then (mem.(v) <- true; sc.(v) <- sc.(u) + c);
        b || b'
        ) false a
    end)
  in
  let inf_loop = has_loop && begin
    Array.init n (fun i -> reach.(i) && mem.(i)) |> Array.fold_left (||) false
  end in

  if inf_loop then
    print_endline "inf"
  else
    Printf.printf "%d\n" sc.(n-1)

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

1≤a_i,b_i≤N (1≤i≤M)

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

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 maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


let bellman_ford d es =
  for i = 1 to Array.length d - 1 do
    List.iter (fun (a, b, c) ->
      d.(b) <- min d.(b) (d.(a) + c)) es
  done

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let abcs = Array.to_list @@ Array.init m (fun _ -> Scanf.scanf "%d %d %d\n" (fun a b c -> a - 1, b - 1, -c)) in
  let d = Array.make n 1000000000000 in
  d.(0) <- 0;
  bellman_ford d abcs;
  if List.exists (fun (a, b, c) -> b = n - 1 && d.(a) + c < d.(b)) abcs then print_endline "inf"
  else Printf.printf "%d\n" (-d.(n - 1))


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

let rec func a b c n =
  if (a mod 2) = 1 || (b mod 2) = 1 || (c mod 2) = 1 then n
  else
    func ((b+c)/2) ((a+c)/2) ((a+b)/2) (n+1)

let ans = if a = b && b = c then -1 else func a b c 0

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

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


Scanf.scanf "%d %d" (fun n m ->
    let hist = Array.make n 0 in
    for i = 1 to m do
        Scanf.scanf " %d %d" (fun a b ->
            hist.(a - 1) <- hist.(a - 1) lxor 1;
            hist.(b - 1) <- hist.(b - 1) lxor 1;
        )
    done;
    print_endline @@ if Array.fold_left (+) 0 hist = 0 then "YES" else "NO"
)

Score : 500 points

Problem Statement

Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.

First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.

Then, Aoki gave him M queries. The i-th of them is as follows:

Increment the number written at each edge along the path connecting vertices a_i and b_i, by one.

After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number.
However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries.

Determine whether there exists a tree that has the property mentioned by Takahashi.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print YES if there exists a tree that has the property mentioned by Takahashi; print NO otherwise.

Sample Input 1

4 4
1 2
2 4
1 3
3 4

Sample Output 1

YES

For example, Takahashi's graph has the property mentioned by him if it has the following edges: 1-2, 1-3 and 1-4.
In this case, the number written at every edge will become 2.

Sample Input 2

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

Sample Output 2

NO


let (n, m) = Scanf.sscanf (read_line ()) "%d %d" @@ fun n m -> (n, m)
let ab = Array.init m @@ fun _ -> Scanf.sscanf (read_line ()) "%d %d" @@ fun a b -> (a, b)

let cnt = Array.make 10_001 0

let () =
  Array.iter (fun (a, b) ->
    cnt.(a) <- cnt.(a) + 1;
    cnt.(b) <- cnt.(b) + 1
  ) ab;
  print_endline @@ if cnt
    |> Array.map (fun cnt -> cnt mod 2 = 0)
    |> Array.fold_left (&&) true
    then "YES" else "NO"


open Scanf
open Printf
open String

let () = scanf "%s %s %s" (fun a b c-> if a.[(length a) - 1] = b.[0] && b.[(length b) - 1]  = c.[0]
   then "YES" else "NO"
  ) |> printf "%s\n"

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


let () =
  let a, b, c = Scanf.scanf "%d %d %d" (fun a b c -> (a, b, c)) in
  let rec f tmp =
    let x = tmp mod b in
    match x with 0 -> "NO" | y when y = c -> "YES" | _ -> f (tmp + a)
  in
  f a |> print_endline

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


let lim = 330
let () =
  Scanf.scanf "%d %d" @@ fun n ww ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
  let w0 = fst a.(0) in

  let dp = Array.make_matrix lim (n+1) 0 in
  a |> Array.iter (fun (w, v) ->
    let w = w - w0 in
    for i = lim-1 downto w do
      for j = n downto 1 do
        if i + j * w0 <= ww then
          dp.(i).(j) <- max dp.(i).(j) (dp.(i-w).(j-1) + v)
    done done);

  Array.fold_left (Array.fold_left max) 0 dp
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

You have N items and a bag of strength W.
The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

1 ≤ N ≤ 100

1 ≤ W ≤ 10^9

1 ≤ w_i ≤ 10^9

For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.

1 ≤ v_i ≤ 10^7

W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.


Scanf.scanf "%d %d" (fun n t ->
    let rec loop i prev acc =
        if i = n then acc + t else
            let ti = Scanf.scanf " %d" (fun t -> t) in
            let acc = if prev + t <= ti then acc + t else acc + ti - prev in
            loop (i + 1) ti acc
    in
    loop 0 0 0 |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

In a public bath, there is a shower which emits water for T seconds when the switch is pushed.

If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds.
Note that it does not mean that the shower emits water for T additional seconds.

N people will push the switch while passing by the shower.
The i-th person will push the switch t_i seconds after the first person pushes it.

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

0 = t_1 < t_2 < t_3 < , ..., < t_{N-1} < t_N ≤ 10^9

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

Assume that the shower will emit water for a total of X seconds. Print X.

Sample Input 1

2 4
0 3

Sample Output 1

7

Three seconds after the first person pushes the water, the switch is pushed again and the shower emits water for four more seconds, for a total of seven seconds.

Sample Input 2

2 4
0 5

Sample Output 2

8

One second after the shower stops emission of water triggered by the first person, the switch is pushed again.

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


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

Scanf.scanf "%d %d" (fun n w ->
    let vw = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun w v -> w, v)) in
    let map = Array.fold_left (fun map (w0, v0) ->
        M.fold (fun ww vv newmap ->
            let key = ww + w0 in
            if key <= w then (
                try
                    let v1 = M.find key newmap in
                    if v1 < vv + v0 then M.add key (vv + v0) newmap else newmap
                with _ ->
                    M.add key (vv + v0) newmap
            ) else newmap
        ) map map
    ) (M.add 0 0 M.empty) vw
    in
    M.fold (fun _ vv acc -> max vv acc) map 0 |> Printf.printf "%d\n"
)


let () = Scanf.scanf "%d\n" @@ fun n ->
  let xys = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun x y -> x, y in
  let rmax = Array.fold_right (fun (x, y) -> max @@ max x y) xys min_int in
  let bmin = Array.fold_right (fun (x, y) -> min @@ min x y) xys max_int in
  let (rmin, bmax) = Array.fold_left (fun (rmin, bmax) (x, y) ->
    if x <= y
    then (min rmin y, max bmax x)
    else (min rmin x, max bmax y)) (max_int, min_int) xys in
  Printf.printf "%d\n" @@ (rmax - rmin) * (bmax - bmin)

Score : 700 points

Problem Statement

There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively.

For each of these bags, you will paint one of the balls red, and paint the other blue.

Afterwards, the 2N balls will be classified according to color.

Then, we will define the following:

R_{max}: the maximum integer written on a ball painted in red

R_{min}: the minimum integer written on a ball painted in red

B_{max}: the maximum integer written on a ball painted in blue

B_{min}: the minimum integer written on a ball painted in blue

Find the minimum possible value of (R_{max} - R_{min}) \times (B_{max} - B_{min}).

Constraints

1 ≤ N ≤ 200,000

1 ≤ x_i, y_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum possible value.

Sample Input 1

3
1 2
3 4
5 6

Sample Output 1

15

The optimal solution is to paint the balls with x_1, x_2, y_3 red, and paint the balls with y_1, y_2, x_3 blue.

Sample Input 2

3
1010 10
1000 1
20 1020

Sample Output 2

380

Sample Input 3

2
1 1
1000000000 1000000000

Sample Output 3

999999998000000001


let () = Scanf.scanf "%s %s %s" @@ fun s1 s2 s3 ->
  Printf.printf "%c%c%c\n"
  (Char.uppercase s1.[0])
  (Char.uppercase s2.[0])
  (Char.uppercase s3.[0])

Score : 100 points

Problem Statement

You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.

Constraints

s_1, s_2 and s_3 are composed of lowercase English letters.

1 ≤ |s_i| ≤ 10 (1≤i≤3)

Input

Input is given from Standard Input in the following format:

s_1 s_2 s_3

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


open Printf
open Scanf

let () =
  let sl = scanf "%s %s %s\n" (fun x y z -> [x;y;z]) in
  String.init 3 (fun i -> Char.uppercase (List.nth sl i).[0]) |> printf "%s\n"


let a, b = Scanf.scanf " %s %s" @@ fun a b -> a, b
let n, m = String.length a, String.length b
let _ = print_endline @@
  if n < m then "LESS" else if n > m then "GREATER"
  else if a < b then "LESS" else if a > b then "GREATER" else "EQUAL"

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


let () = Scanf.scanf "%s\n%s" @@ fun a b ->
  if String.length a < String.length b then print_endline "LESS"
  else if String.length a > String.length b then print_endline "GREATER"
  else
    try
      Array.init (String.length a) (fun i -> Char.code b.[i] - Char.code a.[i])
      |> Array.to_list
      |> List.find (( <> ) 0)
      |> (fun d -> if 0 < d then "LESS" else "GREATER")
      |> print_endline
    with Not_found -> print_endline "EQUAL"


(* O(n) *)
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let ans = ref max_int
let _ =
  for m = 0 to 1 do
    let sum = ref a_s.(0) in
    let c = ref 0 in
    if a_s.(0) > 0 then if m = 0 then (sum := -1; c := abs !sum + 1) else ()
    else if m = 1 then (sum := 1; c := abs !sum + 1);
    for i = 1 to n - 1 do
      if i mod 2 = m then
        (sum := !sum + a_s.(i);
        if !sum >= 0 then (c := !c + abs !sum + 1; sum := -1))
      else
        (sum := !sum + a_s.(i);
        if !sum <= 0 then (c := !c + abs !sum + 1; sum := 1))
    done;
    ans := min !ans !c
  done;
  Printf.printf "%d\n" !ans

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


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.to_list as_
  |> (fun (h :: t) ->
    List.fold_left (fun (acc, a, dir) a' ->
      if dir = 0 || compare a a' = dir then (acc, a', compare a a')
      else (1 + acc, a', 0)) (1, h, 0) t)
  |> (fun (acc, _, _) -> acc)
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are given an array A of length N.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide A into?

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Each A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of subarrays after division of A.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3