let n = read_int ()
let i = ref 1
let _ =
  while !i * !i <= n do incr i done;
  Printf.printf "%d\n" @@ (!i - 1) * (!i - 1)

Score : 200 points

Problem Statement

Find the largest square number not exceeding N. Here, a square number is an integer that can be represented as the square of an integer.

Constraints

1 \leq N \leq 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the largest square number not exceeding N.

Sample Input 1

10

Sample Output 1

9

10 is not square, but 9 = 3 × 3 is. Thus, we print 9.

Sample Input 2

81

Sample Output 2

81

Sample Input 3

271828182

Sample Output 3

271821169


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

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

let id = identity

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

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

let scan_lines n fmt f =
  if n = 0 then Enum.empty ()
  else
    List.map (fun _ -> scan fmt f) (List.range 1 `To n)
    |> List.enum

let scan_list cnv =
  String.split_on_char ' ' @@ read_line ()
  |> List.map cnv

let scan_array cnv = Array.of_list @@ scan_list cnv

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (List.range 0 `To (pred n))
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

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

let n = scan "%d" id
let a = scan_array Int.of_string
let b = scan_array Int.of_string
let c = scan_array Int.of_string

let () =
  Array.sort Int.compare a;
  Array.sort Int.compare b;
  Array.sort Int.compare c;
  let d = Array.of_list @@
    ListL.map (0 ++^ Array.length b) ~f:(fun i ->
        match Array.bsearch Int.ord c b.(i) with
        | `At i | `Just_after i -> Array.length c - succ i
        | `All_bigger -> Array.length c
        | _ -> 0) in
  ListL.iter (List.rev @@ 0 ++^ Array.length d) ~f:(fun i ->
      if i - 1 >= 0 then d.(i-1) <- d.(i-1) + d.(i));
  ListL.map (0 ++^ Array.length c) ~f:(fun i ->
      match Array.bsearch Int.ord b a.(i) with
      | `At i | `Just_after i -> d.(succ i)
      | `All_bigger -> d.(0)
      | _ -> 0)
  |> List.sum
  |> Printf.printf "%d\n"

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

Score : 300 points

Problem Statement

The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.

He has N parts for each of the three categories. The size of the i-th upper part is A_i, the size of the i-th middle part is B_i, and the size of the i-th lower part is C_i.

To build an altar, the size of the middle part must be strictly greater than that of the upper part, and the size of the lower part must be strictly greater than that of the middle part. On the other hand, any three parts that satisfy these conditions can be combined to form an altar.

How many different altars can Ringo build? Here, two altars are considered different when at least one of the three parts used is different.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

1 \leq C_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N
B_1 ... B_N
C_1 ... C_N

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

Upper: 1-st part, Middle: 1-st part, Lower: 1-st part

Upper: 1-st part, Middle: 1-st part, Lower: 2-nd part

Upper: 1-st part, Middle: 2-nd part, Lower: 2-nd part

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output 3

87

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 Batteries
module EnumL = Enum.Labels
module ListL = List.Labels

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

let id = identity

let (++) n m = List.range n `To m
let (++^) n m = List.range n `To (pred m)

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

let scan_lines n fmt f =
  if n = 0 then Enum.empty ()
  else
    List.map (fun _ -> scan fmt f) (List.range 1 `To n)
    |> List.enum

let scan_list cnv =
  String.split_on_char ' ' @@ read_line ()
  |> List.map cnv

let scan_array cnv = Array.of_list @@ scan_list cnv

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (List.range 0 `To (pred n))
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

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

let n = scan "%d" id
let a = scan_array Int.of_string
let b = scan_array Int.of_string
let c = scan_array Int.of_string

let () =
  Array.sort Int.compare a;
  Array.sort Int.compare b;
  Array.sort Int.compare c;
  Array.Labels.map a ~f:(fun va ->
      match match Array.bsearch Int.ord b va with
        | `At i | `Just_after i -> Some (succ i)
        | `All_bigger -> Some 0
        | _ -> None
      with
      | Some i ->
        Array.Labels.map (Array.sub b i (Array.length b - i))
          ~f:(fun vb ->
              match Array.bsearch Int.ord c vb with
              | `At i | `Just_after i ->
                Array.length c - i - 1
              | `All_bigger -> Array.length c
              | _ -> 0)
        |> Array.sum
      | None -> 0)
  |> Array.sum
  |> Printf.printf "%d\n"


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

let () =
  Scanf.scanf "%d" @@ fun k ->
  let (+%) a b = (a + b) mod k in
  let ( *%) a b = (a * b) mod k in

  let a = Array.make k k in
  a.(1) <- 1;
  let rec loop pq =
    if M.is_empty pq then () else begin
      let (d, m) = M.min_elt pq in
      let pq' = M.remove (d, m) pq in
      if d > a.(m) then loop pq' else
      [(d+1, m+%1); (d, m *% 10)] |> List.fold_left (fun q (d',m') ->
        if d' < a.(m') then begin
          a.(m') <- d';
          M.add (d', m') q
        end else q
      ) pq' |> loop
    end
  in
  loop (M.singleton (1, 1));
  Printf.printf "%d\n" a.(0)

Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36


let rec sum10 n acc =
  let m = n / 10 in
  if m = 0 then n + acc
  else sum10 m (acc + (n mod 10))

let solve n =
  Array.init 100 (fun i -> sum10 (n * (i + 1)) 0)
  |> Array.fold_left min n

let () = Scanf.scanf "%d" solve |> Printf.printf "%d"


let f now to_ = to_+to_-now;;
Scanf.scanf "%d %d" f |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

Takahashi is a user of a site that hosts programming contests.

When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows:

Let the current rating of the user be a.

Suppose that the performance of the user in the contest is b.

Then, the new rating of the user will be the avarage of a and b.

For example, if a user with rating 1 competes in a contest and gives performance 1000, his/her new rating will be 500.5, the average of 1 and 1000.

Takahashi's current rating is R, and he wants his rating to be exactly G after the next contest.

Find the performance required to achieve it.

Constraints

0 \leq R, G \leq 4500

All input values are integers.

Input

Input is given from Standard Input in the following format:

R
G

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is 2002.

If his performance in the contest is 2032, his rating will be the average of 2002 and 2032, which is equal to the desired rating, 2017.

Sample Input 2

4500
0

Sample Output 2

-4500

Although the current and desired ratings are between 0 and 4500, the performance of a user can be below 0.


open Batteries
let () =
  let a,b = Scanf.scanf "%d %d " (fun a b -> a,b) in
  Printf.printf "%d\n" @@
  a+(b-a)*2


let rec f res (n, k) =
  if n <= 0 then res
  else if res > k then f (res + k) (n - 1, k)
  else f (res * 2) (n - 1, k)

let () =
  let n, k = Scanf.scanf "%d\n%d" (fun n k -> (n, k)) in
  f 1 (n, k) |> print_int

Score : 200 points

Problem Statement

Square1001 has seen an electric bulletin board displaying the integer 1.
He can perform the following operations A and B to change this value:

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by K.

Square1001 needs to perform these operations N times in total.
Find the minimum possible value displayed in the board after N operations.

Constraints

1 \leq N, K \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

Print the minimum possible value displayed in the board after N operations.

Sample Input 1

4
3

Sample Output 1

10

The value will be minimized when the operations are performed in the following order: A, A, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 7 → 10.

Sample Input 2

10
10

Sample Output 2

76

The value will be minimized when the operations are performed in the following order: A, A, A, A, B, B, B, B, B, B.

In this case, the value will change as follows: 1 → 2 → 4 → 8 → 16 → 26 → 36 → 46 → 56 → 66 → 76.

By the way, this contest is AtCoder Beginner Contest 076.


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


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let rec f i b =
  if i >= n then if b then 1 else 0
  else let ft, fb = f (i + 1) true, f (i + 1) b in if a_s.(i) mod 2 = 0 then ft + 2 * fb else fb + 2 * ft
let _ = Printf.printf "%d\n" @@ f 0 false

Score : 200 points

Problem Statement

We will say that two integer sequences of length N, x_1, x_2, ..., x_N and y_1, y_2, ..., y_N, are similar when |x_i - y_i| \leq 1 holds for all i (1 \leq i \leq N).

In particular, any integer sequence is similar to itself.

You are given an integer N and an integer sequence of length N, A_1, A_2, ..., A_N.

How many integer sequences b_1, b_2, ..., b_N are there such that b_1, b_2, ..., b_N is similar to A and the product of all elements, b_1 b_2 ... b_N, is even?

Constraints

1 \leq N \leq 10

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the number of integer sequences that satisfy the condition.

Sample Input 1

2
2 3

Sample Output 1

7

There are seven integer sequences that satisfy the condition:

1, 2

1, 4

2, 2

2, 3

2, 4

3, 2

3, 4

Sample Input 2

3
3 3 3

Sample Output 2

26

Sample Input 3

1
100

Sample Output 3

1

Sample Input 4

10
90 52 56 71 44 8 13 30 57 84

Sample Output 4

58921


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let rec f i b =
  if i >= n then if b then 1 else 0
  else if a_s.(i) mod 2 = 0 then f (i + 1) true + f (i + 1) b + f (i + 1) b
  else f (i + 1) b + f (i + 1) true + f (i + 1) true
let _ = Printf.printf "%d\n" @@ f 0 false


let a, b, c = Scanf.scanf "%d %d %d" @@ fun a b c -> a, b, c
let ans = if a = b then c else if a = c then b else a
let () = print_int ans

Score : 100 points

Problem Statement

You are given three integers, A, B and C.

Among them, two are the same, but the remaining one is different from the rest.

For example, when A=5,B=7,C=5, A and C are the same, but B is different.

Find the one that is different from the rest among the given three integers.

Constraints

-100 \leq A,B,C \leq 100

A, B and C are integers.

The input satisfies the condition in the statement.

Input

Input is given from Standard Input in the following format:

A B C

Output

Among A, B and C, print the integer that is different from the rest.

Sample Input 1

5 7 5

Sample Output 1

7

This is the same case as the one in the statement.

Sample Input 2

1 1 7

Sample Output 2

7

In this case, C is the one we seek.

Sample Input 3

-100 100 100

Sample Output 3

-100


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let xys = Array.init n @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let ans, xs, ys = ref max_int, ref [], ref []
let _ = Array.iteri (fun i (xi, yi) -> for j = i + 1 to n - 1 do let xj, yj = xys.(j) in xs := (xi, xj) :: !xs; ys := (yi, yj) :: !ys done) xys; List.(iter (fun (xi, xj) -> iter (fun (yi, yj) -> if Array.fold_left (fun c (x, y) -> if (xi <= x && x <= xj || xj <= x && x <= xi) && (yi <= y && y <= yj || yj <= y && y <= yi) then c + 1 else c) 0 xys >= k then ans := min !ans @@ abs (xi - xj) * abs (yi - yj)) !ys) !xs); Printf.printf "%d\n" !ans

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i).

Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior.

Here, points on the sides of the rectangle are considered to be in the interior.

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

-10^9 \leq x_i,y_i \leq 10^9 (1 \leq i \leq N)

x_i≠x_j (1 \leq i<j \leq N)

y_i≠y_j (1 \leq i<j \leq N)

All input values are integers. (Added at 21:50 JST)

Input

Input is given from Standard Input in the following format:

N K
x_1 y_1
:
x_{N} y_{N}

Output

Print the minimum possible area of a rectangle that satisfies the condition.

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

One rectangle that satisfies the condition with the minimum possible area has the following vertices: (1,1), (8,1), (1,4) and (8,4).

Its area is (8-1) × (4-1) = 21.

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

4 3
-1000000000 -1000000000
1000000000 1000000000
-999999999 999999999
999999999 -999999999

Sample Output 3

3999999996000000001

Watch out for integer overflows.


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let xys = Array.init n @@ fun _ ->
    Scanf.scanf "%d %d\n" @@ fun x y -> x, y in
  Array.sort (fun (v, w) (x, y) -> compare (v, ~- w) (x, ~- y)) xys;
  Printf.printf "%d\n" @@ Array.fold_left (Array.fold_left min) max_int @@
    Array.init (n - k + 1) @@ fun i ->
      Array.init (n - i - k + 1) @@ fun j ->
        let xys' = Array.init (j + k) (fun k -> snd xys.(i + k)) in
        Array.sort compare xys';
        (fst xys.(i + j + k - 1) - fst xys.(i)) *
        Array.fold_left min max_int (Array.init (j + 1) (fun j -> xys'.(j + k - 1) - xys'.(j)))


let () = Scanf.scanf "%d" (fun n ->
  try
    for h = 1 to 3500 do
      for w = h to 3500 do
        if 4 * h * w > n * w + n * h && (n * h * w) mod (4 * h * w - n * w - n * h) = 0
        then (Printf.printf "%d %d %d\n" h ((n * h * w) / (4 * h * w - n * w - n * h)) w; raise Not_found)
      done
    done
  with Not_found -> ())

Score : 300 points

Problem Statement

You are given an integer N.

Find a triple of positive integers h, n and w such that 4/N = 1/h + 1/n + 1/w.

If there are multiple solutions, any of them will be accepted.

Constraints

It is guaranteed that, for the given integer N, there exists a solution such that h,n,w \leq 3500.

Inputs

Input is given from Standard Input in the following format:

N

Outputs

Print a triple of positive integers h, n and w that satisfies the condition, in the following format:

h n w

Sample Input 1

2

Sample Output 1

1 2 2

4/2 = 1/1 + 1/2 + 1/2.

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

It is allowed to use an integer exceeding 3500 in a solution.

Sample Input 3

4664

Sample Output 3

3498 3498 3498


let flood_bits bits =
  List.fold_left (fun bits shamt ->
    bits lor (bits lsr shamt)) bits
  [1; 2; 4; 8; 16; 32]
let highest_bit bits =
  bits land lnot (flood_bits bits lsr 1)

let rec generate_pattern k =
  if k = 0 then [0]
  else begin
    let highest = highest_bit k in
    highest - 1 :: List.map (( lor ) highest) (generate_pattern (k land lnot highest))
  end

let () =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let abs = Array.init n (fun _ -> Scanf.scanf "%d %d\n" (fun a b -> a, b)) in
  generate_pattern k
  |> List.map (fun pat ->
      Array.fold_left (fun b' (a, b) ->
        if a land lnot pat = 0 then b + b' else b') 0 abs)
  |> List.fold_left max 0
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

Seisu-ya, a store specializing in non-negative integers, sells N non-negative integers. The i-th integer is A_i and has a utility of B_i.
There may be multiple equal integers with different utilities.

Takahashi will buy some integers in this store. He can buy a combination of integers whose bitwise OR is less than or equal to K. He wants the sum of utilities of purchased integers to be as large as possible.

Find the maximum possible sum of utilities of purchased integers.

Constraints

1 \leq N \leq 10^5

0 \leq K < 2^{30}

0 \leq A_i < 2^{30}(1\leq i\leq N)

1 \leq B_i \leq 10^9(1\leq i\leq N)

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N K
A_1 B_1
:
A_N B_N

Outputs

Print the maximum possible sum of utilities of purchased integers.

Sample Input 1

3 5
3 3
4 4
2 5

Sample Output 1

8

Buy 2 and 3 to achieve the maximum possible total utility, 8.

Sample Input 2

3 6
3 3
4 4
2 5

Sample Output 2

9

Buy 2 and 4 to achieve the maximum possible total utility, 9.

Sample Input 3

7 14
10 5
7 4
11 4
9 8
3 6
6 2
8 9

Sample Output 3

32


open Printf
open Scanf

let flip f x y = f y x

let () =
  let n = scanf "%d " (fun x -> x) in
  let rec read x ls =
    if x = 0 then ls
    else let p = scanf "%d %d " (fun a b -> (a, b)) in
         read (x - 1) (p :: ls) in
  let ps = read n [] in
  List.sort (flip compare) ps |> List.hd |> (fun (a, b) -> printf "%d\n" (a + b))

Score : 200 points

Problem Statement

A group of people played a game. All players had distinct scores, which are positive integers.

Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i.

Find the maximum possible number of players in the game.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9(1\leq i\leq N)

0 \leq B_i \leq 10^9(1\leq i\leq N)

If i ≠ j, A_i ≠ A_j.

There exists a possible outcome of the game that are consistent with the facts.

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Outputs

Print the maximum possible number of players in the game.

Sample Input 1

3
4 7
2 9
6 2

Sample Output 1

8

The maximum possible number of players is achieved when, for example, the players have the following scores: 12,9,8,7,5,2,1,0.

Sample Input 2

5
1 10
3 6
5 2
4 4
2 8

Sample Output 2

7

Sample Input 3

2
1 1000000000
1000000000 1

Sample Output 3

1000000001


let () =
  let n, m, k = Scanf.scanf "%d %d %d" (fun n m k -> n, m, k) in
  begin List.concat @@ Array.to_list @@ Array.init (n + 1) (fun x ->
    Array.to_list @@ Array.init (m + 1) (fun y -> (x, y))) end
  |> List.exists (fun (x, y) -> k = x * m + y * n - 2 * x * y)
  |> (function true -> "Yes" | false -> "No")
  |> print_endline

Score : 200 points

Problem Statement

We have a grid with N rows and M columns of squares. Initially, all the squares are white.

There is a button attached to each row and each column.
When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa.
When a button attached to a column is pressed, the colors of all the squares in that column are inverted.

Takahashi can freely press the buttons any number of times. Determine whether he can have exactly K black squares in the grid.

Constraints

1 \leq N,M \leq 1000

0 \leq K \leq NM

Input

Input is given from Standard Input in the following format:

N M K

Output

If Takahashi can have exactly K black squares in the grid, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

Press the buttons in the order of the first row, the first column.

Sample Input 2

2 2 1

Sample Output 2

No

Sample Input 3

3 5 8

Sample Output 3

Yes

Press the buttons in the order of the first column, third column, second row, fifth column.

Sample Input 4

7 9 20

Sample Output 4

No


open Scanf
open Printf

let cell n a = n * n - a

let a, n = (read_int (), read_int())
let () = printf "%d\n" @@ cell n a

Score : 100 points

Problem Statement

We have an N \times N square grid.

We will paint each square in the grid either black or white.

If we paint exactly A squares white, how many squares will be painted black?

Constraints

1 \leq N \leq 100

0 \leq A \leq N^2

Inputs

Input is given from Standard Input in the following format:

N
A

Outputs

Print the number of squares that will be painted black.

Sample Input 1

3
4

Sample Output 1

5

There are nine squares in a 3 \times 3 square grid.
Four of them will be painted white, so the remaining five squares will be painted black.

Sample Input 2

19
100

Sample Output 2

261

Sample Input 3

10
0

Sample Output 3

100

As zero squares will be painted white, all the squares will be painted black.


Array.(Scanf.scanf" %d %d %d %d %d %d"@@fun a b c d e f->
  let r=ref (0.,(0,0)) in
  for i=0 to 32 do
    for j=0 to 32 do
      for k=0 to 103 do
        for l=0 to 103 do
          let w,s=100*a*i+100*b*j,c*k+d*l in
          if w+s<=f && w/100*e>=s && w+s<>0 then
            let d=100. *. (float s) /. (float w +. float s) in
            if d>fst !r then r:=(d,(w+s,s)) done;done;done;done;
  Printf.printf "%d %d\n" (fst@@snd !r) (snd@@snd !r))

Score : 300 points

Problem Statement

Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

Operation 1: Pour 100A grams of water into the beaker.

Operation 2: Pour 100B grams of water into the beaker.

Operation 3: Put C grams of sugar into the beaker.

Operation 4: Put D grams of sugar into the beaker.

In our experimental environment, E grams of sugar can dissolve into 100 grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most F grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains a grams of water and b grams of sugar is \frac{100b}{a + b} percent.
Also, in this problem, pure water that does not contain any sugar is regarded as 0 percent density sugar water.

Constraints

1 \leq A < B \leq 30

1 \leq C < D \leq 30

1 \leq E \leq 100

100A \leq F \leq 3 000

A, B, C, D, E and F are all integers.

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

In this environment, 15 grams of sugar can dissolve into 100 grams of water, and the beaker can contain at most 200 grams of substances.

We can make 110 grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:

If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.

If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed 200 grams.

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

This is because, in order to make 300 grams of sugar water containing 150 grams of sugar, we need to pour exactly 150 grams of water into the beaker, which is impossible.

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934


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

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

let id = identity

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

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

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

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

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

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

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

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

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

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

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

let n = scan "%d" id
let mat = scan_matrix ~sep:' ' n n 0 Int.of_string
let mat2 = Array.make_matrix n n true

let () =
  ListL.map (0 ++^ n) ~f:(fun k ->
      ListL.map (0 ++^ n) ~f:(fun i ->
          ListL.map (0 ++^ n) ~f:(fun j ->
              if mat.(i).(j) > mat.(i).(k) + mat.(k).(j) then -1
              else mat.(i).(j)
            )
        )
    )
  |> List.concat |> List.concat |> List.min
  |> (fun v -> if v = -1 then Printf.printf "-1\n" else
         (ListL.iter (0 ++^ n) ~f:(fun k ->
              ListL.iter (0 ++^ n) ~f:(fun i ->
                  ListL.iter (0 ++^ n) ~f:(fun j ->
                      if i <> k && k <> j && mat.(i).(j) = mat.(i).(k) + mat.(k).(j) then
                        mat2.(i).(j) <- false
                    )
                )
            );
          ArrayL.mapi mat2 ~f:(fun i a ->
              ArrayL.mapi a ~f:(fun j v ->
                  if v then mat.(i).(j)
                  else 0
                )
              |> Array.sum
            ) |> Array.sum |> (fun v -> Printf.printf "%d\n" (v/2)))
     )

Score : 500 points

Problem Statement

In Takahashi Kingdom, which once existed, there are N cities, and some pairs of cities are connected bidirectionally by roads.
The following are known about the road network:

People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.

Different roads may have had different lengths, but all the lengths were positive integers.

Snuke the archeologist found a table with N rows and N columns, A, in the ruin of Takahashi Kingdom.
He thought that it represented the shortest distances between the cities along the roads in the kingdom.

Determine whether there exists a road network such that for each u and v, the integer A_{u, v} at the u-th row and v-th column of A is equal to the length of the shortest path from City u to City v.
If such a network exist, find the shortest possible total length of the roads.

Constraints

1 \leq N \leq 300

If i ≠ j, 1 \leq A_{i, j} = A_{j, i} \leq 10^9.

A_{i, i} = 0

Inputs

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} ... A_{1, N}
A_{2, 1} A_{2, 2} ... A_{2, N}
...
A_{N, 1} A_{N, 2} ... A_{N, N}

Outputs

If there exists no network that satisfies the condition, print -1.
If it exists, print the shortest possible total length of the roads.

Sample Input 1

3
0 1 3
1 0 2
3 2 0

Sample Output 1

3

The network below satisfies the condition:

City 1 and City 2 is connected by a road of length 1.

City 2 and City 3 is connected by a road of length 2.

City 3 and City 1 is not connected by a road.

Sample Input 2

3
0 1 3
1 0 1
3 1 0

Sample Output 2

-1

As there is a path of length 1 from City 1 to City 2 and City 2 to City 3, there is a path of length 2 from City 1 to City 3.
However, according to the table, the shortest distance between City 1 and City 3 must be 3.

Thus, we conclude that there exists no network that satisfies the condition.

Sample Input 3

5
0 21 18 11 28
21 0 13 10 26
18 13 0 23 13
11 10 23 0 17
28 26 13 17 0

Sample Output 3

82

Sample Input 4

3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0

Sample Output 4

3000000000


open Scanf
open Printf

let flip f x y = f y x

let range a b =
  let rec f acc a b = if a > b then acc else f (b::acc) a (b-1) in
  f [] a (b-1)

let read_int () = scanf " %d" (fun x -> x)
let rec read_ints n = Array.init n (fun _ -> read_int ())

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 rec for_all_iter a b f = if a >= b then true else f a && for_all_iter (a+1) b f

let inf = 20202020202020

let () =
  let n = read_int () in
  let mtx = Array.init n (fun _ -> read_ints n) in

  let mtx' = Array.init n (fun i -> Array.copy mtx.(i)) in
  for_iter_ 0 n (fun k -> for_iter_ 0 n (fun i -> for_iter_ 0 n (fun j ->
    mtx'.(i).(j) <- min mtx'.(i).(j) (mtx'.(i).(k) + mtx'.(k).(j)))));

  let valid = for_all_iter 0 n (fun i ->
    for_all_iter 0 n (fun j ->
      mtx.(i).(j) = mtx'.(i).(j))) in
  if not valid then (print_endline "-1"; exit 0);

  let edges =
    let res = Array.make (n*(n-1)/2) (-1,-1,-1) in
    let rec f i a b =
      if a >= n then ()
      else if b >= n then f i (a+1) (a+2)
      else (res.(i) <- (a, b, mtx.(a).(b)); f (i+1) a (b+1)) in
    f 0 0 1;
    Array.sort (fun (_,_,w0) (_,_,w1) -> w0-w1) res;
    res in

  for_iter_ 0 n (fun j ->
    for_iter_ 0 n (fun k -> mtx'.(j).(k) <- inf);
    mtx'.(j).(j) <- 0);
  Array.fold_left (fun s (u, v, w) ->
    if mtx'.(u).(v) <= w then s
    else (
      mtx'.(u).(v) <- w; mtx'.(v).(u) <- w;
      for_iter_ 0 n (fun j -> for_iter_ 0 n (fun k ->
        mtx'.(j).(k) <- min mtx'.(j).(k) (mtx'.(j).(u) + w + mtx'.(v).(k));
        mtx'.(j).(k) <- min mtx'.(j).(k) (mtx'.(j).(v) + w + mtx'.(u).(k))));
      s+w)) 0 edges
  |> printf "%d\n"


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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let es = Array.make n [] in
  if n = 1 then
    ignore (read_line ())
  else
    for i = 1 to n - 1 do
      Scanf.scanf "%d " @@ fun p ->
        es.(p - 1) <- i :: es.(p - 1)
    done;
  let xs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun x -> x in
  let rec solve v =
    let xys = List.map (fun u -> xs.(u), solve u) es.(v) in
    let most = List.fold_right (fun (x, y) -> ( + ) @@ max x y) xys 0 in
    let least = List.fold_right (fun (x, y) -> ( + ) @@ min x y) xys 0 in
    if xs.(v) < least then raise Not_found
    else IntMap.fold (fun _ -> min)
      (List.fold_left (fun m (w, v_) ->
        let le, _, _ = IntMap.split (xs.(v) - least - w + 1) m in
        IntMap.fold (fun w' v' m ->
          IntMap.add (w + w')
            (max (v_ + v') @@
              try IntMap.find (w + w') m
              with Not_found -> min_int) m) le m) (IntMap.singleton 0 most) @@
        List.map (fun (x, y) -> abs (x - y), ~- (abs (x - y))) xys) max_int in
  print_endline @@
  try ignore (solve 0); "POSSIBLE"
  with Not_found -> "IMPOSSIBLE"

Score : 700 points

Problem Statement

We have a tree with N vertices. Vertex 1 is the root of the tree, and the parent of Vertex i (2 \leq i \leq N) is Vertex P_i.

To each vertex in the tree, Snuke will allocate a color, either black or white, and a non-negative integer weight.

Snuke has a favorite integer sequence, X_1, X_2, ..., X_N, so he wants to allocate colors and weights so that the following condition is satisfied for all v.

The total weight of the vertices with the same color as v among the vertices contained in the subtree whose root is v, is X_v.

Here, the subtree whose root is v is the tree consisting of Vertex v and all of its descendants.

Determine whether it is possible to allocate colors and weights in this way.

Constraints

1 \leq N \leq 1 000

1 \leq P_i \leq i - 1

0 \leq X_i \leq 5 000

Inputs

Input is given from Standard Input in the following format:

N
P_2 P_3 ... P_N
X_1 X_2 ... X_N

Outputs

If it is possible to allocate colors and weights to the vertices so that the condition is satisfied, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3
1 1
4 3 2

Sample Output 1

POSSIBLE

For example, the following allocation satisfies the condition:

Set the color of Vertex 1 to white and its weight to 2.

Set the color of Vertex 2 to black and its weight to 3.

Set the color of Vertex 3 to white and its weight to 2.

There are also other possible allocations.

Sample Input 2

3
1 2
1 2 3

Sample Output 2

IMPOSSIBLE

If the same color is allocated to Vertex 2 and Vertex 3, Vertex 2 cannot be allocated a non-negative weight.

If different colors are allocated to Vertex 2 and 3, no matter which color is allocated to Vertex 1, it cannot be allocated a non-negative weight.

Thus, there exists no allocation of colors and weights that satisfies the condition.

Sample Input 3

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

Sample Output 3

POSSIBLE

Sample Input 4

1

0

Sample Output 4

POSSIBLE


open Batteries
(* charのカウント *)
let count_char target str =
  let rec count lst =
    match lst with
    | [] -> 0
    | first :: rest -> if first = target then 1 + count rest else count rest
  in let explode s = List.init (String.length s) (String.get s)
  in count @@ explode str

let _ =
  let d =read_line () |> count_char '9'
  in (if d != 0 then "Yes" else "No") |> print_endline

Score : 100 points

Problem Statement

It is September 9 in Japan now.

You are given a two-digit integer N. Answer the question: Is 9 contained in the decimal notation of N?

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

If 9 is contained in the decimal notation of N, print Yes; if not, print No.

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


(* O(n) *)
open Hashtbl
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let h = create n
let _ =
  Array.iter (fun a -> try ignore @@ find h a; remove h a with _ -> add h a 1) a_s;
  length h |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are playing the following game with Joisino.

Initially, you have a blank sheet of paper.

Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times.

Then, you are asked a question: How many numbers are written on the sheet now?

The numbers announced by Joisino are given as A_1, ... ,A_N in the order she announces them. How many numbers will be written on the sheet at the end of the game?

Constraints

1≤N≤100000

1≤A_i≤1000000000(=10^9)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print how many numbers will be written on the sheet at the end of the game.

Sample Input 1

3
6
2
6

Sample Output 1

1

The game proceeds as follows:

6 is not written on the sheet, so write 6.

2 is not written on the sheet, so write 2.

6 is written on the sheet, so erase 6.

Thus, the sheet contains only 2 in the end. The answer is 1.

Sample Input 2

4
2
5
5
2

Sample Output 2

0

It is possible that no number is written on the sheet in the end.

Sample Input 3

6
12
22
16
22
18
12

Sample Output 3

2


open Printf
open Scanf

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

let () =
  let n = scanf "%d " (fun x -> x) in
  let rec loop i st =
    if i = 0 then SI.cardinal st
    else
      let a = scanf "%d " (fun x -> x) in
      if SI.mem a st then loop (i-1) (SI.remove a st)
      else loop (i-1) (SI.add a st) in
  loop n SI.empty |> printf "%d\n"


let n, m, r, ans, ds, rs = Scanf.(scanf "%d %d %d" @@ fun n m r -> Array.(n, m, r, ref max_int, make_matrix n n (1 lsl 40), init r @@ fun _ -> scanf " %d" pred))
let s, fs, is, es = Array.(ref 0, make r false, make r 0, init m @@ fun _ -> Scanf.scanf " %d %d %d" @@ fun a b t -> ds.(a - 1).(b - 1) <- t; ds.(b - 1).(a - 1) <- t; a - 1, b - 1, t)
let rec f i = if i >= r then ans := min !ans !s else for j = 0 to r - 1 do if not fs.(j) then (fs.(j) <- true; is.(i) <- j; let d = if i > 0 then ds.(rs.(is.(i - 1))).(rs.(j)) else 0 in s := !s + d; f (i + 1); fs.(j) <- false; s := !s - d) done
let _ = Array.(iteri (fun i d -> iteri (fun j _ -> if i = j then d.(j) <- 0) d) ds); for k = 0 to n - 1 do for i = 0 to n - 1 do for j = 0 to n - 1 do ds.(i).(j) <- min ds.(i).(j) @@ ds.(i).(k) + ds.(k).(j) done done done; f 0; Printf.printf "%d\n" !ans

Score : 400 points

Problem Statement

There are N towns in the State of Atcoder, connected by M bidirectional roads.

The i-th road connects Town A_i and B_i and has a length of C_i.

Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).

She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road.

If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be?

Constraints

2≤N≤200

1≤M≤N×(N-1)/2

2≤R≤min(8,N) (min(8,N) is the smaller of 8 and N.)

r_i≠r_j (i≠j)

1≤A_i,B_i≤N, A_i≠B_i

(A_i,B_i)≠(A_j,B_j),(A_i,B_i)≠(B_j,A_j) (i≠j)

1≤C_i≤100000

Every town can be reached from every town by road.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M R
r_1 ... r_R
A_1 B_1 C_1
:
A_M B_M C_M

Output

Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.

Sample Input 1

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

Sample Output 1

2

For example, if she visits the towns in the order of 1, 2, 3, the distance traveled will be 2, which is the minimum possible.

Sample Input 2

3 3 2
1 3
2 3 2
1 3 6
1 2 2

Sample Output 2

4

The shortest distance between Towns 1 and 3 is 4. Thus, whether she visits Town 1 or 3 first, the distance traveled will be 4.

Sample Input 3

4 6 3
2 3 4
1 2 4
2 3 3
4 3 1
1 4 1
4 2 2
3 1 6

Sample Output 3

3


open Printf
open Scanf

let () =
        let s = read_line() in
        let rec iter i ans =
                if i = (String.length s) then
                        printf "%s\n" ans
                else if (i mod 2 = 0) then
                        iter (i + 1) (ans ^ (String.make 1 s.[i]))
                else
                        iter (i + 1) ans
        in iter 0 ""

Score : 100 points

Problem Statement

We have a sandglass that runs for X seconds. The sand drops from the upper bulb at a rate of 1 gram per second. That is, the upper bulb initially contains X grams of sand.

How many grams of sand will the upper bulb contains after t seconds?

Constraints

1≤X≤10^9

1≤t≤10^9

X and t are integers.

Input

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

X t

Output

Print the number of sand in the upper bulb after t second.

Sample Input 1

100 17

Sample Output 1

83

17 out of the initial 100 grams of sand will be consumed, resulting in 83 grams.

Sample Input 2

48 58

Sample Output 2

0

All 48 grams of sand will be gone, resulting in 0 grams.

Sample Input 3

1000000000 1000000000

Sample Output 3

0


open Printf
open Scanf

let () =
	let (x, t) = scanf "%d %d" (fun x t -> (x, t)) in
	(if x < t then
		0
	else x - t)
	|> printf "%d\n"


(* O(n) *)
let kMax = 100000 + 10
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let ns = Array.make (kMax + 1) 0
let f a =
  for i = 0 to 2 do ns.(a + i) <- ns.(a + i) + 1 done
let _ =
  Array.iter f a_s;
  Array.fold_left max 0 ns |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are given an integer sequence of length N, a_1,a_2,...,a_N.

For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing.

After these operations, you select an integer X and count the number of i such that a_i=X.

Maximize this count by making optimal choices.

Constraints

1≤N≤10^5

0≤a_i<10^5 (1≤i≤N)

a_i is an integer.

Input

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

N
a_1 a_2 .. a_N

Output

Print the maximum possible number of i such that a_i=X.

Sample Input 1

7
3 1 4 1 5 9 2

Sample Output 1

4

For example, turn the sequence into 2,2,3,2,6,9,2 and select X=2 to obtain 4, the maximum possible count.

Sample Input 2

10
0 1 2 3 4 5 6 7 8 9

Sample Output 2

3

Sample Input 3

1
99999

Sample Output 3

1


open Hashtbl

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

let f n =
  let rec g n' =
    if n' = 0 then ()
    else
      let a = Scanf.scanf "%d " id in
      let v = try find h a with _ -> 0 in
      replace h a (v + 1) ;
      g (n' - 1)
  in
  g n

let () =
  f n ;
  fold (fun k v tmp ->
      let v' = try find h (k - 1) with _ -> 0 in
      let v'' = try find h (k + 1) with _ -> 0 in
      max tmp (v + v' + v'')) h 0
  |> Printf.printf "%d\n"


open Hashtbl

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

let f n =
  let rec g n' =
    if n' = 0 then ()
    else
      let a = Scanf.scanf "%d " id in
      let v = try find h a with _ -> 0 in
      let v' = try find h (a - 1) with _ -> 0 in
      let v'' = try find h (a + 1) with _ -> 0 in
      replace h a (v + 1) ;
      replace h (a - 1) (v' + 1) ;
      replace h (a + 1) (v'' + 1) ;
      g (n' - 1)
  in
  g n

let () =
  f n ;
  fold (fun _ v tmp -> max v tmp) h 0 |> Printf.printf "%d\n"


module IMap=Map.Make(struct type t=int let compare=compare end);;
Scanf.(Array.(scanf" %d"@@ fun n->
	let m = init n(fun _->scanf" %d"@@fun v->v)
	|> fold_left(fun m v->IMap.add v (1+try IMap.find v m with Not_found -> 0) m) IMap.empty
	in IMap.fold(fun v c r->
		let p,q=(try IMap.find (v-1) m with Not_found->0),(try IMap.find (v+1) m with Not_found->0)
		in max r (p+q+c)) m 0 |> print_int))


let q, h, s, d = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> a, b, c, d
let n = Scanf.scanf " %d" @@ (+) 0
let m0_5 = min h @@ q * 2
let m1 = min s @@ m0_5 * 2
let m2 = min d @@ m1 * 2
let c2 = n / 2
let c1 = n - c2 * 2
let _ = c2 * m2 + c1 * m1 |> Printf.printf "%d\n"

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


let () =
  let q, h, s, d = Scanf.scanf "%d %d %d %d\n" (fun q h s d -> q, h, s, d) in
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  [(1, q); (2, h); (4, s); (8, d)]
  |> List.sort (fun (size, price) (size', price') -> compare (price * size') (price' * size))
  |> List.fold_left (fun (acc, n) (size, price) -> (acc + n / size * price, n mod size)) (0, 4 * n)
  |> fst
  |> Printf.printf "%d\n"


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

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 n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let xs = Array.(sort (-) a_s; fold_left (fun (xs, p) a -> if p = a then a :: xs, 0 else xs, a) ([], 0) a_s) |> fst
let _ = Printf.printf "%d\n" @@ match xs with a :: b :: _ -> a * b | _ -> 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


open Hashtbl
let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let h = create n
let acs = Array.(iter (fun a -> replace h a @@ try find h a + 1 with _ -> 1) a_s; List.(fold (fun a c xs -> (a, c) :: xs) h [] |> filter (fun (_, c) -> c >= 2) |> sort (fun x y -> compare y x) |> of_list))
let _ = Printf.printf "%d\n" @@ if Array.length acs < 2 then 0 else fst acs.(0) * fst acs.(1)


let mkls n =
  let rec f n' ls =
    if n' = 0 then List.fast_sort (fun i j -> j - i) ls
    else
      f (pred n') (Scanf.scanf "%d " (fun x -> x) :: ls)
  in
  f n []

let solve ls =
  let rec f ed = function
    | [] | [_] -> 0
    | h :: (h' :: t as t') ->
      if h = h' && ed > 0 then h * ed
      else if h = h' && ed <= 0 then f h t
      else f ed t'
  in
  f 0 ls

let () = Scanf.scanf "%d\n" mkls |> solve |> 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') ->
      let mult = match x with H -> 6 | V -> 3 in
      List.fold_left f (x, mult) 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


Scanf.scanf " %d %d %d %d" @@ fun a b c d ->
  max 0 @@ min b d - max a c |> Printf.printf "%d\n"

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 a, b, c, d = Scanf.scanf "%d %d %d %d" (fun a b c d -> (a, b, c, d))

let () =
  let x = max a c in
  let y = min b d in
  if y - x > 0 then Printf.printf "%d\n" (y - x) else Printf.printf "%d\n" 0


open Printf
open Scanf
open Num

module Pqueue = struct

  type 'a t = {mutable cnt : int; hp : 'a array; cmp : 'a -> 'a -> int}

  let create n v f = {cnt = 0; hp = Array.make n v; cmp = f}

  let push k pq =
    let swap i j =
      let t = pq.hp.(i) in
      pq.hp.(i) <- pq.hp.(j);
      pq.hp.(j) <- t in
    let rec iter i =
      let p = i / 2 in
      if p = 0 || pq.cmp pq.hp.(p) pq.hp.(i) >= 0 then ()
      else (swap p i; iter p)
    in
    pq.cnt <- pq.cnt + 1;
    pq.hp.(pq.cnt) <- k;
    iter (pq.cnt)

  let max_heapify pq n =
    let swap i j =
      let t = pq.hp.(i) in
      pq.hp.(i) <- pq.hp.(j);
      pq.hp.(j) <- t in
    let rec iter i =
      let l = 2 * i in
      let r = 2 * i + 1 in
      let mi =
        let ti = if l <= pq.cnt && pq.cmp pq.hp.(l) pq.hp.(i) > 0 then l else i in
        if r <= pq.cnt && pq.cmp pq.hp.(r) pq.hp.(ti) > 0 then r else ti in
      if mi <> i then
        begin
          swap mi i;
          iter mi
        end
    in
    iter n

  let pop pq =
    let ret = pq.hp.(1) in
    pq.hp.(1) <- pq.hp.(pq.cnt);
    pq.cnt <- pq.cnt - 1;
    max_heapify pq 1;
    ret

  let top pq = pq.hp.(1)

  let is_empty pq = pq.cnt = 0

  let length pq = pq.cnt

end

let id x = x

let dijkstra g n s =
  let d = Array.make n (num_of_string "200000000000000") in
  let av = Array.make n true in
  let pq = Pqueue.create 2000000 ((num_of_int 0),0) (fun x y -> let x1 = fst x and y1 = fst y in if y1 >/ x1 then 1 else if y1 =/ x1 then 0 else (-1)) in
  let rec loop () =
    if Pqueue.is_empty pq then d
    else let du, u = Pqueue.pop pq in
         if av.(u) then begin
             av.(u) <- false;
             List.iter (fun (v, c) ->
                        if du +/ c </ d.(v) then begin
                            d.(v) <- du +/ c;
                            Pqueue.push (d.(v), v) pq
                          end
                       ) g.(u);
             loop ()
           end
         else loop ()
  in
  d.(s) <- num_of_int 0;
  Pqueue.push (d.(s), s) pq;
  loop ()

let () =
  let n = scanf "%d " id in
  let g = Array.make n [] in
  let rec make_g x =
    if x = 0 then ()
    else
      let a, b, c = scanf "%d %d %s " (fun i j k -> (i-1, j-1, num_of_string k)) in
      g.(a) <- (b, c) :: g.(a);
      g.(b) <- (a, c) :: g.(b);
      make_g (x-1) in
  make_g (n-1);
  let q, k = scanf "%d %d " (fun i j -> (i, j-1)) in
  let d = dijkstra g n k in
  let rec loop z =
    if z = 0 then ()
    else
      let x, y = scanf "%d %d " (fun i j -> (i-1, j-1)) in
      printf "%s\n" (string_of_num (d.(x) +/ d.(y)));
      loop (z-1)
  in
  loop q

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


let solve n m = (n - 1) * (m - 1)

let read_ints () = read_line () |> Str.split (Str.regexp " ") |> List.map int_of_string

let _ =
  match read_ints () with
  | [n; m] -> solve n m |> string_of_int |> print_endline
  | _ -> ()

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 "%d %d" (fun n m -> (n - 1) * (m - 1))
  |> Printf.printf "%d\n"


let main () = Scanf.sscanf (read_line()) "%d %d" (fun a b -> print_int((a-1)*(b-1)));;

let _ = main()


let () =
  let (n, m) = Scanf.scanf "%d %d " (fun n m -> n, m) in
  (n - 1) * (m - 1) |> Printf.printf "%d\n"


let () =
  let s = read_line () in
  Printf.printf "%c%d%c\n" s.[0] (String.length s - 2) s.[String.length s - 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 f s =
  let len = String.length s in
  Printf.sprintf "%c%d%c" s.[0] (len - 2) s.[len-1]

let () = f (read_line ()) |> print_endline


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.to_list @@ Array.init n @@ fun _ ->
    Scanf.scanf "%d " @@ fun a -> a in
  print_endline @@
    if
      List.for_all (fun a -> a mod 2 = 0) as_ ||
      List.length (List.filter (fun a -> a mod 2 = 1) as_)
      <= 2 * List.length (List.filter (fun a -> a mod 4 = 0) as_) - 1
    then "Yes"
    else "No"

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
  if four >= len/2 then true else
    if g fourl <= four then true else false

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 () =
  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 - 2 <= o then "No" else "Yes")


let ans, c, h, w, a_s = Scanf.(scanf "%d %d %d" @@ fun h w n -> Array.(make_matrix h w 0, ref 0, h, w, init n @@ fun _ -> scanf " %d" (+) 0))
let rec f i = if a_s.(i) = 0 then f (i + 1) else (a_s.(i) <- a_s.(i) - 1; i)
let _ = for i = 0 to h - 1 do for j = 0 to w - 1 do c := f !c; ans.(i).(if i mod 2 = 1 then w - 1 - j else j) <- !c + 1 done done; Array.(iter (fun cs -> to_list cs |> List.map string_of_int |> String.concat " " |> print_endline) ans)

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) mod 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 () = print_endline ("ABC" ^ (read_line ()))

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 id x = x
let n = Scanf.scanf "%d\n" id

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


let n = read_int ()
let m = ref (0, 1)
let rec f n = if n mod 2 <> 0 then 0 else 1 + f (n / 2)
let _ = for i = 1 to n do m := max !m @@ (f i, i) done; Printf.printf "%d\n" @@ snd !m

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


let () = Scanf.scanf "%d" @@ fun n ->
  let n = n lor (n lsr 1) in
  let n = n lor (n lsr 2) in
  let n = n lor (n lsr 4) in
  let n = n lor (n lsr 8) in
  let n = n lor (n lsr 16) in
  let n = (n land 0x55555555) + ((n lsr 1) land 0x55555555) in
  let n = (n land 0x33333333) + ((n lsr 2) land 0x33333333) in
  let n = (n land 0x0f0f0f0f) + ((n lsr 4) land 0x0f0f0f0f) in
  let n = (n land 0x00ff00ff) + ((n lsr 8) land 0x00ff00ff) in
  let n = (n land 0x0000ffff) + ((n lsr 16) land 0x0000ffff) in
  Printf.printf "%d\n" @@ 1 lsl (n - 1)


open Batteries
open Printf
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in

  let l = [1;2;4;8;16;32;64] in
  let ans =
    List.filter (fun x -> x <= n) l |>
    List.max
  in

  Printf.printf "%d\n" ans


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

let hash = Hashtbl.create m

let rec init_hash m =
  if m = 0 then ()
  else
    let a, b = Scanf.scanf "%d %d\n" (fun a b -> (a, b)) in
    let ls = b :: (try Hashtbl.find hash a with Not_found -> []) in
    Hashtbl.replace hash a ls ;
    init_hash (m - 1)

let rec iter_search = function
  | [] -> "IMPOSSIBLE"
  | from_first :: rest ->
    let to_n = (try Hashtbl.find hash from_first with Not_found -> []) in
    if List.exists (( = ) n)  to_n then "POSSIBLE"
    else iter_search rest

let () =
  let () = init_hash m in
  Hashtbl.find hash 1 |> iter_search |> Printf.printf "%s\n"

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.


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

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let abs = Array.init m (fun _ -> Scanf.scanf "%d %d\n" (fun a b -> a, b)) in
  let e = Array.make n IntSet.empty in
  Array.iter (fun (a, b) ->
    e.(a - 1) <- IntSet.add (b - 1) e.(a - 1);
    e.(b - 1) <- IntSet.add (a - 1) e.(b - 1)) abs;
  if IntSet.is_empty (IntSet.inter e.(0) e.(n - 1)) then
    print_endline "IMPOSSIBLE"
  else
    print_endline "POSSIBLE"


let () =
  Scanf.scanf "%d %d\n" @@ fun n k ->
  let l = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  let _ = Array.fast_sort (fun x y -> y-x) l in
  let ans = ref 0 in
  for i = 0 to k-1 do
    ans := !ans + l.(i)
  done;
  Printf.printf "%d\n" !ans

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


let rec take n = function
  | [] -> []
  | x :: xs ->
      if n = 0 then []
      else x :: take (n - 1) xs

let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  Array.init n (fun _ ->
    Scanf.scanf "%d " @@ fun l -> l)
  |> Array.to_list
  |> List.sort (fun x y -> compare y x)
  |> take k
  |> List.fold_left ( + ) 0
  |> Printf.printf "%d\n"


open Batteries
open Printf
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let k = Scanf.scanf "%d " (fun a -> a) in
  let a_lst = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in

  let l = List.sort (fun x y -> compare y x) a_lst in
  let (ans_l,_) = List.split_nth k l in

  Printf.printf "%d\n" @@
  List.fold_left (+) 0 ans_l


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

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

let total = Array.fold_left ( + ) 0 a

let () =
  let rec f i sumx tmp =
    if i = n then tmp
    else
      let next_sumx = sumx + a.(i) in
      let next_tmp = min tmp (abs (2 * sumx - total)) in
      f (i + 1) next_sumx next_tmp
  in
  f 1 a.(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.


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 - 1) / 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


open Printf
open Scanf

type node = {p : int; cs : int list}

let id x = x

let rec remove e = function
    [] -> []
  | x::xs when x = e -> xs
  | x::xs -> x :: remove e xs

let spath tr n =
  let rec iter i ls =
    let p = tr.(i).p in
    if p = 0 then ls
    else iter p (p::ls)
  in iter n []

let count tr n =
  let rec iter i =
    let cs = tr.(i).cs in
    match cs with
      [] -> 1
    | xs -> List.fold_left (fun s j -> s + iter j) 1 xs
  in
  iter n

let () =
  let n = scanf "%d\n" id in
  let adj = Array.make n [] in
  let tree = Array.make n {p = -1; cs = []} in
  let rec read n =
    if n = 1 then ()
    else let i, j = scanf "%d %d\n" (fun x y -> (x-1, y-1)) in
         adj.(i) <- j :: adj.(i);
         adj.(j) <- i :: adj.(j);
         read (n-1)
  in
  let rec set_node p i =
    let cs = remove p adj.(i) in
    tree.(i) <- {p = p; cs = cs};
    List.iter (fun x -> set_node i x) cs
  in
  read n;
  set_node (-1) 0;
  let pt = spath tree (n-1) in
  let l = List.length pt in
  let w = (if l <= 1 then n-1 else List.nth pt ((l+1) / 2)) in
  let s = count tree w in
  printf "%s\n" (if s >= n - s then "Snuke" else "Fennec")


(* unihernandez22
 * https://atcoder.jp/contests/abc066/tasks/abc066_a
 * sorting, implementation
 * *)

Printf.printf "%d\n" @@
Scanf.scanf "%d %d %d\n" @@ fun a b c ->
    [a; b; c]
    |> List.sort compare
    |> fun l -> List.nth l 0 + List.nth l 1

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 () = Scanf.scanf "%d %d %d"
(fun a b c -> a+b+c - max a (max b c))
|> Printf.printf "%d\n"


open Batteries
open Printf
let () =
  let a,b,c = Scanf.scanf "%d %d %d " (fun a b c -> a,b,c) in

  let ans =
    let (l, _) = List.sort compare [a;b;c] |>
                 List.split_nth 2 in
    List.fold_left (+) 0 l
  in

  Printf.printf "%d\n" ans


Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    for i = 0 to n - 1 do
        let f = i < (n + 1) / 2 in
        let idx = if f then n - 1 - i * 2 else (i - (n + 1) / 2) * 2 + (n mod 2) in
        Printf.printf "%d " a.(idx)
    done;
    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 x, a, b = Scanf.scanf "%d %d %d\n" @@ fun a b c -> a, b, c
let ans = if a <= b then "delicious" else if a + x <= b then "safe" else "dangerous"
let () = print_endline ans

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 _ = Scanf.sscanf (read_line()) "%d %d %d" (fun x a b ->
  if b <= a then "delicious" else
  if x + a < b then "dangerous" else "safe"
) |> print_endline


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


open Batteries
open Printf
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let a_lst = Array.to_list @@ Array.init n (fun i -> (Scanf.scanf "%d " (fun a -> a))) in

  let rec aux visited i cnt =
    let next = (List.nth a_lst i)-1 in
    if List.mem i visited then -1 else
    if i = 1 then cnt else
      aux (i::visited) next (cnt+1)
  in

  Printf.printf "%d\n" @@
  aux [] 0 0

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


let n, m = Scanf.scanf " %d %d" @@ fun a b -> a, b
let ( * ) a b = a * b mod 1000000007
let rec f n a = if n <= 1 then a else f (n - 1) (a * n)
let _ = Printf.printf "%d\n" @@ f n 1 * f m 1 * max 0 (2 - abs (n - m))

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


Scanf.scanf "%d" (fun n ->
    let xy = Array.init n (fun i -> Scanf.scanf " %d %d" (fun x y -> x, y, i)) in
    Array.sort compare xy;
    let module S = Set.Make (struct type t = int * int * int let compare = compare end) in
    let rec loop j acc =
        if j = n then acc else
            let px, _, pi = xy.(j - 1) in
            let cx, _, ci = xy.(j)     in
            let acc = S.add (cx - px, pi, ci) acc in
            loop (j + 1) acc
    in
    let edges = loop 1 S.empty in
    Array.sort (fun (x0, y0, _) (x1, y1, _) -> compare (y0, x0) (y1, x1)) xy;
    let rec loop j acc =
        if j = n then acc else
            let _, py, pi = xy.(j - 1) in
            let _, cy, ci = xy.(j)     in
            let acc = S.add (cy - py, pi, ci) acc in
            loop (j + 1) acc
    in
    let edges = loop 1 edges in

    let par = Array.init n (fun i -> i) in
    let rec root x =
        if x = par.(x) then x else
            let r = root par.(x) in
            let () = par.(x) <- r in
            r
    in

    let merge a b =
        if root a <> root b then par.(par.(b)) <- par.(a)
    in

    let rec loop edges cost =
        if S.is_empty edges then cost else (
            let ((c, n1, n2) as elt) = S.min_elt edges in
            let edges = S.remove elt edges in
            if root n1 = root n2 then loop edges cost else (
                merge n1 n2;
                loop edges (cost + c)
            )
        )
    in
    loop edges 0 |> 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


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

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

let id = identity

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

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

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

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

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

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

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

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

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

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

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

let n = scan "%d" id
let ls = scan_lines n "%d %d" Tuple2.make
let edges = Queue.create ()

module UnionFind = struct
  let empty n = Array.init n id

  let root t n =
    let rec aux c =
      if c = t.(c) then c
      else let p = aux t.(c) in t.(c) <- p; p in
    aux n

  let unite t v0 v1 =
    let w0 = root t v0 in
    let w1 = root t v1 in
    t.(w1) <- w0

  let same t v0 v1 =
    root t v0 = root t v1
end

let uf = UnionFind.empty n

let () =
  let lx = ListL.mapi ls ~f:(fun i (x,_) -> (x,i))
           |> List.sort Tuple2.compare in
  let ly = ListL.mapi ls ~f:(fun i (_,y) -> (y,i))
           |> List.sort Tuple2.compare in
  ListL.iter (List.combine (List.take (n-1) lx) (List.drop 1 lx))
    ~f:(fun ((x0,i), (x1,j)) ->
        let d = Int.abs (x0-x1)  in
        Queue.add (d, i, j) edges);
  ListL.iter (List.combine (List.take (n-1) ly) (List.drop 1 ly))
    ~f:(fun ((x0,i), (x1,j)) ->
        let d = Int.abs (x0-x1)  in
        Queue.add (d, i, j) edges);
  edges
  |> Queue.enum |> List.of_enum
  |> List.sort Tuple3.compare
  |> ListL.map  ~f:(fun (d, i, j) ->
      if UnionFind.same uf i j then 0
      else
        (UnionFind.unite uf i j; d))
  |> List.sum |> Printf.printf "%d\n"


let () =
  let s = read_line () in
  let rec shrink a ss c =
    let sl = String.length ss in
    if  sl = 1 || (ss = String.make sl c) then a
    else
      let ns = String.init (sl - 1) (fun i -> if ss.[i] = c || ss.[i+1] = c then c else ss.[i]) in
      shrink (a+1) ns c in
  let tbl = ['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'] in
  List.map (shrink 0 s) tbl |> List.sort compare |> List.hd |> string_of_int |> print_endline

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 _ = Scanf.sscanf (read_line()) "%s %s %s" (fun r g b ->
  if (int_of_string (r ^ g ^ b)) mod 4 = 0 then "YES" else "NO"
)

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 f a b c = if (mod) (100*a+10*b+c) 4 = 0 then "YES" else "NO";;
Scanf.scanf "%d %d %d" f
|> Printf.printf "%s\n"


let () = Scanf.scanf "%d %d %d" (fun r g b ->
  print_endline @@ if (10 * g + b) mod 4 = 0 then "YES" else "NO")