let ans = Scanf.scanf "%d %d\n" (fun a b -> string_of_int ((a-1) * (b-1)))
let () = List.iter print_endline [ans]

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

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

Submitted source-code file size, in bytes.

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

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


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


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

  let i18n str =
    let len = String.length str in
    if len < 3 then failwith "too small" else
    let fst = String.slice ~last:1 str in
    let mid = string_of_int (len-2) in
    let lst = String.slice ~first:(len-1) str in
    fst ^ mid ^ lst
  in

  Printf.printf "%s\n" @@
  i18n s

Score : 200 points

Problem Statement

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

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

Constraints

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

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the abbreviation of s.

Sample Input 1

internationalization

Sample Output 1

i18n

Sample Input 2

smiles

Sample Output 2

s4s

Sample Input 3

xyz

Sample Output 3

x1z


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


open Printf
open Scanf

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


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

Score : 400 points

Problem Statement

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

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

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

Determine whether Snuke can achieve his objective.

Constraints

2 ≤ N ≤ 10^5

a_i is an integer.

1 ≤ a_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

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

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is (1, 100, 10).

Sample Input 2

4
1 2 3 4

Sample Output 2

No

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

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes


let () = Scanf.scanf "%d\n" @@ fun n ->
  Printf.printf "ABC%03d\n" n

Score : 100 points

Problem Statement

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

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

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

Constraints

100 ≤ N ≤ 999

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

100

Sample Output 1

ABC100

The 100th round of ABC is ABC100.

Sample Input 2

425

Sample Output 2

ABC425

Sample Input 3

999

Sample Output 3

ABC999


let () = read_line () |> Printf.printf "ABC%s\n"


let n = read_int ()
let m = ref 1
let _ = while !m * 2 <= n do m := !m * 2 done; Printf.printf "%d\n" @@ !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
  Printf.printf "%d\n" @@ (n + 1) lsr 1


let f n = log n /. log 2. |> floor |> ( ** ) 2.
let () = f (read_float ()) |> Printf.printf "%.f\n"


let () =
  let n = read_int () in
  let rec find x =
    let y = 2 * x in
    if y > n then x else find y
  in find 1 |> string_of_int |> print_endline


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

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

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

Score : 300 points

Problem Statement

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

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

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

Help him.

Constraints

3 ≤ N ≤ 200 000

1 ≤ M ≤ 200 000

1 ≤ a_i < b_i ≤ N

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

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

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

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

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

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

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

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


let () =
  Scanf.scanf "%d" @@ fun k ->
  let n = 50 in
  let d, r = k / n, k mod n in
  Printf.printf "%d\n" n;
  for i = 0 to n-1 do
    (if i < r then n+d else n+d-1-r) |> Printf.printf "%d "
  done;
  print_newline ()

Score : 600 points

Problem Statement

We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller.

Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by N, and increase each of the other elements by 1.

It can be proved that the largest element in the sequence becomes N-1 or smaller after a finite number of operations.

You are given an integer K. Find an integer sequence a_i such that the number of times we will perform the above operation is exactly K. It can be shown that there is always such a sequence under the constraints on input and output in this problem.

Constraints

0 ≤ K ≤ 50 \times 10^{16}

Input

Input is given from Standard Input in the following format:

K

Output

Print a solution in the following format:

N
a_1 a_2 ... a_N

Here, 2 ≤ N ≤ 50 and 0 ≤ a_i ≤ 10^{16} + 1000 must hold.

Sample Input 1

0

Sample Output 1

4
3 3 3 3

Sample Input 2

1

Sample Output 2

3
1 0 3

Sample Input 3

2

Sample Output 3

2
2 2

The operation will be performed twice: [2, 2] -> [0, 3] -> [1, 1].

Sample Input 4

3

Sample Output 4

7
27 0 0 0 0 0 0

Sample Input 5

1234567894848

Sample Output 5

10
1000 193 256 777 0 1 1192 1234567891011 48 425


let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let _ = Scanf.scanf "%d %d" @@ fun n k ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let v = Array.fold_left gcd a.(0) a in
  Array.fold_left (fun b x -> b || x >= k && (x - k) mod v = 0) false a
  |> fun b -> print_endline (if b then "POSSIBLE" else "IMPOSSIBLE")

Score : 300 points

Problem Statement

There is a box containing N balls. The i-th ball has the integer A_i written on it.
Snuke can perform the following operation any number of times:

Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written.

Determine whether it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written.

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq K \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

If it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written, print POSSIBLE; if it is not possible, print IMPOSSIBLE.

Sample Input 1

3 7
9 3 4

Sample Output 1

POSSIBLE

First, take out the two balls 9 and 4, and return them back along with a new ball, abs(9-4)=5.
Next, take out 3 and 5, and return them back along with abs(3-5)=2.
Finally, take out 9 and 2, and return them back along with abs(9-2)=7.
Now we have 7 in the box, and the answer is therefore POSSIBLE.

Sample Input 2

3 5
6 9 3

Sample Output 2

IMPOSSIBLE

No matter what we do, it is not possible to have 5 in the box. The answer is therefore IMPOSSIBLE.

Sample Input 3

4 11
11 3 7 15

Sample Output 3

POSSIBLE

The box already contains 11 before we do anything. The answer is therefore POSSIBLE.

Sample Input 4

5 12
10 2 8 6 4

Sample Output 4

IMPOSSIBLE


let _ =
    let [a; b] = List.map int_of_string (Str.split (Str.regexp " ") (read_line ())) in
    if a mod 3 = 0 || b mod 3 = 0 || (a+b) mod 3 = 0 then print_string "Possible"
    else print_string "Impossible"

Score : 100 points

Problem Statement

Snuke is giving cookies to his three goats.

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

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

Constraints

1 \leq A,B \leq 100

Both A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

4 5

Sample Output 1

Possible

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

Sample Input 2

1 1

Sample Output 2

Impossible

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


open Batteries

let n,k = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> (a, b))
let () = read_line ()
  |> String.split_on_char ' '
  |> List.map int_of_string
  |> List.sort compare
  |> List.rev
  |> Batteries.List.take k
  |> List.fold_left (+) 0
  |> Printf.sprintf "%d"
  |> print_endline

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


open Batteries

let rec print_int_list = function
  | [] -> print_endline "DONE"
  | x :: xs -> Printf.printf "%d " x ; print_int_list xs

let () =
  let n, k = Scanf.scanf " %d %d " (fun n k -> (n, k)) in
  List.init n (fun _ -> Scanf.scanf " %d" (fun li -> li))
  |> List.sort (fun x y -> y - x)
  (* |> print_int_list *)
  |> List.take k |> List.fold_left ( + ) 0 |> Printf.printf "%d\n"


let inf = 10101010101010
let n = Scanf.scanf "%d" (fun x -> x)
let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x)) |> Array.to_list
let sum = List.fold_left (+) 0 a
let f (v, s) a = if s+a = sum then v, s else min v (abs @@ sum - 2*(s+a)), s+a
let () =
  List.fold_left f (inf, 0) a
  |> fst |> 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


let dfs g n =
  let que = Queue.create () in
  Queue.push 1 que;
  let reached_p = Array.make (n + 1) false in
  reached_p.(1) <- true;
  let rec doit depth n_p =
    if n_p || Queue.is_empty que then depth
    else begin
      let x = Queue.pop que in
      let n_p = ref false in
      List.iter (fun e ->
        if not reached_p.(e) then begin
          reached_p.(e) <- true;
          Queue.push e que;
          if e = n then n_p := true;
        end)
        g.(x);
      doit (depth + 1) !n_p
    end in
  doit 0 false

let () =
  let n = Scanf.scanf "%d " (fun i -> i) in
  let g = Array.make (n + 1) [] in
  for _ = 1 to n - 1 do
    let (x, y) = Scanf.scanf "%d %d " (fun x y -> (x, y)) in
    g.(x) <- y :: g.(x);
    g.(y) <- x :: g.(y);
  done;
  let x = dfs g n in
  print_endline (if x = 1 then "Snuke" else "Fennec")


open Str

let read_list f =
  split (regexp " +") (read_line ()) |> List.map f

let () =
  let n = read_int () in
  let al = read_list int_of_string in
  let rec iter sn ar mx = function
      x :: [] -> mx
    | x :: xs -> let sn' = sn + x in
                 let ar' = ar - x in
                 iter sn' ar' (min (abs (sn' - ar')) mx) xs
    | _ -> failwith "splitting_pile"
  in
  let sn = List.hd al in
  let ar = List.fold_left (+) 0 (List.tl al) in
  iter sn ar (abs (sn - ar)) (List.tl al) |> string_of_int |> print_endline


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

    let rec loop i p0 p1 =
        if i = n then (if p = 0 then p0 else p1) else
            if a.(i) mod 2 = 0 then loop (i + 1) (p0 * 2) (p1 * 2) else
                                    loop (i + 1) (p0 + p1) (p0 + p1)
    in
    loop 0 1 0 |> Printf.printf "%d\n"
)

Score : 200 points

Problem Statement

There are N bags of biscuits. The i-th bag contains A_i biscuits.

Takaki will select some of these bags and eat all of the biscuits inside.
Here, it is also possible to select all or none of the bags.

He would like to select bags so that the total number of biscuits inside is congruent to P modulo 2.
How many such ways to select bags there are?

Constraints

1 \leq N \leq 50

P = 0 or 1

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N P
A_1 A_2 ... A_N

Output

Print the number of ways to select bags so that the total number of biscuits inside is congruent to P modulo 2.

Sample Input 1

2 0
1 3

Sample Output 1

2

There are two ways to select bags so that the total number of biscuits inside is congruent to 0 modulo 2:

Select neither bag. The total number of biscuits is 0.

Select both bags. The total number of biscuits is 4.

Sample Input 2

1 1
50

Sample Output 2

0

Sample Input 3

3 0
1 1 1

Sample Output 3

4

Two bags are distinguished even if they contain the same number of biscuits.

Sample Input 4

45 1
17 55 85 55 74 20 90 67 40 70 39 89 91 50 16 24 14 43 24 66 25 9 89 71 41 16 53 13 61 15 85 72 62 67 42 26 36 66 4 87 59 91 4 25 26

Sample Output 4

17592186044416


let () =
  let n, p = Scanf.scanf "%d %d\n" (fun n p -> n, p) in
  let as_ = Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  Array.fold_left (fun (odd, even) a ->
    if a mod 2 = 0 then (2 * odd, 2 * even)
    else (odd + even, odd + even)) (0, 1) as_
  |> (if p = 1 then fst else snd)
  |> Printf.printf "%d\n"


Scanf.scanf "%d %d %d %d %d" (fun n a b c d ->
    let rec loop m =
        if m = n then false else
            let q = (n - 1) - m in
            if c * q - d * m <= b - a &&
               d * q - c * m >= b - a then true else loop (m + 1)
    in
    print_endline @@ if loop 0 then "YES" else "NO"
)

Score : 400 points

Problem Statement

There are N squares in a row.
The leftmost square contains the integer A, and the rightmost contains the integer B. The other squares are empty.

Aohashi would like to fill the empty squares with integers so that the following condition is satisfied:

For any two adjacent squares, the (absolute) difference of the two integers in those squares is between C and D (inclusive).

As long as the condition is satisfied, it is allowed to use arbitrarily large or small integers to fill the squares.
Determine whether it is possible to fill the squares under the condition.

Constraints

3 \leq N \leq 500000

0 \leq A \leq 10^9

0 \leq B \leq 10^9

0 \leq C \leq D \leq 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B C D

Output

Print YES if it is possible to fill the squares under the condition; print NO otherwise.

Sample Input 1

5 1 5 2 4

Sample Output 1

YES

For example, fill the squares with the following integers: 1, -1, 3, 7, 5, from left to right.

Sample Input 2

4 7 6 4 5

Sample Output 2

NO

Sample Input 3

48792 105960835 681218449 90629745 90632170

Sample Output 3

NO

Sample Input 4

491995 412925347 825318103 59999126 59999339

Sample Output 4

YES


let () = print_endline @@ Scanf.scanf "%d %d %d %d %d" (fun n a b c d ->
  Array.init n (fun i -> (i * c - (n - 1 - i) * d, i * d - (n - 1 - i) * c))
  |> Array.to_list
  |> List.exists (fun (min, max) -> min <= abs (a - b) && abs (a - b) <= max)
  |> function true -> "YES" | false -> "NO")


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

  let is_even str =
    let len = String.length str in
    if len mod 2 <> 0 then false else
      let fst = String.slice ~last:(len/2) str in
      let lst = String.slice ~first:(len/2) str in
      fst = lst
  in

  let rec aux str =
    let len = String.length str in
    if is_even str then len else
      aux (String.slice ~last:(len-1) str)
  in

  Printf.printf "%d\n" @@
  aux (String.slice ~last:(String.length s - 1) s)

Score : 200 points

Problem Statement

We will call a string that can be obtained by concatenating two equal strings an even string.
For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not.

You are given an even string S consisting of lowercase English letters.
Find the length of the longest even string that can be obtained by deleting one or more characters from the end of S.
It is guaranteed that such a non-empty string exists for a given input.

Constraints

2 \leq |S| \leq 200

S is an even string consisting of lowercase English letters.

There exists a non-empty even string that can be obtained by deleting one or more characters from the end of S.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest even string that can be obtained.

Sample Input 1

abaababaab

Sample Output 1

6

abaababaab itself is even, but we need to delete at least one character.

abaababaa is not even.

abaababa is not even.

abaabab is not even.

abaaba is even. Thus, we should print its length, 6.

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

The longest even string that can be obtained is abcabc, whose length is 6.

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

The longest even string that can be obtained is akasakaakasaka, whose length is 14.


open String

let is s =
  let len = length s in
  if len mod 2 = 0 then
    let half = len / 2 in
    sub s 0 half = sub s half half
  else false

let rec solve s =
  let len = length s in
  if is s then len else solve (sub s 0 (pred len))

let () =
  let s = read_line () in
  let len = pred @@ length s in
  solve (sub s 0 len) |> Printf.printf "%d\n"


let () =
  Scanf.scanf "%d %d %d" (fun x a b ->
      if b - a <= 0 then "delicious"
      else if b - a - x <= 0 then "safe"
      else "dangerous" )
  |> Printf.printf "%s\n"

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.scanf "%d %d %d" (fun x a b ->
      if b - a < 0 then "delicious"
      else if b - a - x <= 0 then "safe"
      else "dangerous" )
  |> Printf.printf "%s\n"


(* O(n) *)
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ fun a -> a - 1
let rec loop acc i =
  if acc > n then -1
  else if i = 1 then acc
  else loop (acc + 1) a_s.(i)
let _ = loop 0 0 |> Printf.printf "%d\n"

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 = read_int ()

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

let () =
  let rec f count value i =
    if i = n then -1
    else
      let next = a.(value) in
      if next = 2 then count + 1
      else f (count + 1) (next - 1) (i + 1)
  in
  f 0 0 0 |> Printf.printf "%d\n"


module WeightedGraph
  (Vertex : sig
    type t
    val compare : t -> t -> int
  end)
  (Weight : sig
    type t
    val compare : t -> t -> int
  end) :
sig
  val prim :
    (* 隣接リスト *)
    (Vertex.t -> (Vertex.t * Weight.t) list) ->
    (* 始点 *)
    Vertex.t ->
    (* 最小全域木に含まれる辺のリスト *)
    (Vertex.t * Vertex.t * Weight.t) list
end =
struct
  module VSet = Set.Make (Vertex)
  module WMap = Map.Make (Weight)

  let prim es =
    (*
     * プリム法のメインループ
     * es : 隣接リスト
     * vs : 訪れた頂点の集合
     * q : 訪れた頂点から伸びる辺が重み順に入ったヒープ
     * acc : 最小全域木に使うのが確定した辺を入れるやつ
     *)
    let rec prim acc vs q =
      match WMap.min_binding q with
      | exception Not_found -> acc
      | (w, []) -> prim acc vs (WMap.remove w q)
      | (w, (u, v) :: rest) ->
          ( if VSet.mem v vs
            (* vは既に訪れていた *)
            then prim acc vs
            (* vはまだ訪れていなかった *)
            else prim_aux ((u, v, w) :: acc) vs v ) (WMap.add w rest q)
    (* vを訪れ，vから伸びる辺をキューに追加してループを続行する *)
    and prim_aux acc vs v q =
      prim acc (VSet.add v vs) @@
      List.fold_left (fun q (u, w) ->
        WMap.add w ((v, u) :: try WMap.find w q with Not_found -> []) q) q (es v) in
    fun s -> prim_aux [] VSet.empty s WMap.empty
end

module Int = struct
  type t = int
  let compare = compare
end

module G = WeightedGraph (Int) (Int)

let () = Scanf.scanf "%d\n" (fun n ->
  let xys = Array.to_list @@ Array.init n (fun i -> Scanf.scanf "%d %d\n" (fun x y -> x, y, i)) in
  let es = Array.make n [] in
  begin match List.sort (fun (x, _, _) (x', _, _) -> compare x x') xys with
  | [] -> ()
  | (x, y, i) :: rest ->
      ignore @@ List.fold_left (fun (x, y, i) (x', y', j) ->
        es.(i) <- (j, min (abs (x - x')) (abs (y - y'))) :: es.(i);
        es.(j) <- (i, min (abs (x - x')) (abs (y - y'))) :: es.(j);
        (x', y', j)) (x, y, i) rest
  end;
  begin match List.sort (fun (_, y, _) (_, y', _) -> compare y y') xys with
  | [] -> ()
  | (x, y, i) :: rest ->
      ignore @@ List.fold_left (fun (x, y, i) (x', y', j) ->
        es.(i) <- (j, min (abs (x - x')) (abs (y - y'))) :: es.(i);
        es.(j) <- (i, min (abs (x - x')) (abs (y - y'))) :: es.(j);
        (x', y', j)) (x, y, i) rest
  end;
  G.prim (Array.get es) 0
  |> List.map (fun (_, _, w) -> w)
  |> List.fold_left ( + ) 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


module PArray = struct
  type 'a t = 'a data ref
  and 'a data = Arr of 'a array | Diff of int * 'a * 'a t

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

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

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

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

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

module PUnionFind = struct
  type t = { rank : int PArray.t; mutable parent : int PArray.t }

  type class_ = int

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

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

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

let () =
  let n = Scanf.scanf "%d\n" @@ fun n -> n in
  let xys = Array.to_list @@ Array.init n @@ fun i ->
    Scanf.scanf "%d %d\n" @@ fun x y -> x, y, i in
  let xedges =
    List.sort (fun (x, _, _) (x', _, _) -> compare x x') xys
    |> (fun ((x, y, i) :: xys) ->
        List.fold_left (fun (acc, x, y, i) (x', y', j) ->
          ((x' - x, i, j) :: acc, x', y', j)) ([], x, y, i) xys)
    |> (fun (acc, _, _, _) -> acc) in
  let yedges =
    List.sort (fun (_, y, _) (_, y', _) -> compare y y') xys
    |> (fun ((x, y, i) :: xys) ->
        List.fold_left (fun (acc, x, y, i) (x', y', j) ->
          ((y' - y, i, j) :: acc, x', y', j)) ([], x, y, i) xys)
    |> (fun (acc, _, _, _) -> acc) in
  List.rev_append xedges yedges
    |> List.sort (fun (d, _, _) (d', _, _) -> compare d d')
    |> List.fold_left (fun (cost, connection) (d, i, j) ->
        if PUnionFind.find connection i = PUnionFind.find connection j then (cost, connection)
        else (d + cost, PUnionFind.union connection i j)) (0, PUnionFind.make n)
    |> fst
    |> Printf.printf "%d\n"


open Printf
open Scanf

let id x = x

let rec read f n =
  if n <= 0 then []
  else
    let x = f () in
    x :: read f (n - 1)

let rec remove x = function
    [] -> []
  | h :: t when h = x -> t
  | h :: t -> h :: remove x t

let cost p1 p2 =
  let d1 = abs (fst p1 - fst p2) and
      d2 = abs (snd p1 - snd p2) in
  min d1 d2

let () =
  let n = scanf "%d\n" id in
  let ps =
    let f () = scanf "%d %d\n" (fun x y -> (x, y)) in
    read f n in
  let rec iter xs ys c =
    match ys with
      [] -> c
    | _ -> let (mp, mc) = List.fold_left (
                              fun (tp, tc) x -> let (up, uc) =
                                                  List.fold_left (fun (sp, sc) y ->
                                                                  let vc = cost x y in
                                                                  if vc < sc then (y, vc) else (sp, sc)
                                                                 ) ((-1, -1), 1000000000) ys in
                                                if uc < tc then (up, uc) else (tp, tc)
                            ) ((-1, -1), 1000000000) xs in
           iter (mp :: xs) (remove mp ys) (c+mc)
  in
  iter [(List.hd ps)] (List.tl ps) 0 |> printf "%d\n"


Scanf.scanf "%d %d %d" (fun r g b ->
    print_endline @@ if (r * 100 + g * 10 + 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 () =
  let a = Scanf.scanf "%d" (fun n -> Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))) in
  let x, y = Array.fold_left min 1001 a, Array.fold_left max 0 a in
  Printf.printf "%d\n" (y-x)

Score : 200 points

Problem Statement

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

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

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

Constraints

1 ≤ N ≤ 100

0 ≤ a_i ≤ 1000

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum distance to be traveled.

Sample Input 1

4
2 3 7 9

Sample Output 1

7

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

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

Sample Input 2

8
3 1 4 1 5 9 2 6

Sample Output 2

8

There may be more than one house at a position.


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

    let rec loop i arr g =
        if i = n then (
            let s = Array.fold_left (fun acc v -> if v > 0 then acc + 1 else acc) 0 arr in
            let mi = if s = 0 then 1 else s in
            let mx = min (s + g) 8 in
            Printf.printf "%d %d\n" mi mx
        ) else (
            if a.(i) < 3200 then (
                let () = arr.(a.(i) / 400) <- arr.(a.(i) / 400) + 1 in
                loop (i + 1) arr g
            ) else loop (i + 1) arr (g + 1)
        )
    in
    loop 0 (Array.make 8 0) 0
)

Score : 300 points

Problem Statement

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

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

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

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

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

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

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

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

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

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

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

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

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

Sample Input 3

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

Sample Output 3

1 1

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


open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
end open MyInt64

let f v =
	[v<400L;v<800L;v<1200L;v<1600L;v<2000L;v<2400L;v<2800L;v<3200L;v>=3200L]
	|> List.rev
	|> List.mapi (fun i v -> i,v)
	|> List.fold_left (fun u (i,v) -> if v then 8-$i else u) 0
	|> Int64.of_int
let (<+) a (i,v) = a<@(i,(a@i)+v)
let () =
	let n = get_i64 0 in
	let a = input_i64_array n in
	let count = Array.make 9 0L in
	Array.iter (fun v ->
		count<+(f v,1L);
	) a;
	let p,q = repm 0L 8L 0L (fun u i ->
		let v = count@i in `Ok (u + if i<>8L && v>0L then 1L else 0L)
	), count@8L
	in
	printf "%Ld %Ld\n" (max p 1L) (min 8L (p+q))


open Str

open List

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

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

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

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

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

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

    Printf.printf "%d " const;
    Printf.printf "%d\n" (const + change);


open Str
open List

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

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

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

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

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

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

    Printf.printf "%d " const;
    Printf.printf "%d\n" (const + change);


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

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  Array.fold_left (fun (s, n) a ->
    if a < 3200 then (IntSet.add (a / 400) s, n)
    else (s, n + 1)) (IntSet.empty, 0) as_
  |> (fun (s, n) -> (max 1 (IntSet.cardinal s), min 8 (IntSet.cardinal s + n)))
  |> (fun (max, min) -> Printf.printf "%d %d\n" max min)


let n = read_int ()
let s = read_line ()
let l, r = ref 0, ref 0
let _ = String.(iter (function '(' -> incr r | _ -> if !r = 0 then incr l else decr r) s; Printf.printf "%s%s%s\n" (make !l '(') s (make !r ')'))

Score : 400 points

Problem Statement

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

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

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

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

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

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

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

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


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

let rec makestr str n =
if n = String.length str - 1 then str else
  if str.[n] = '(' && str.[n+1] = ')' then
    makestr ((String.sub str 0 n) ^ (String.sub str (n+2) ((String.length str) - (n+2)))) 0 else makestr str (n+1)

let str = makestr string 0

let rec count x y str n =
  if n = String.length str then (x,y) else
  match str.[n] with
  | '(' -> count (x+1) y str (n+1)
  | ')' -> count x (y+1) str (n+1)

let (x,y) = count 0 0 str 0

let xlist = String.make x ')'
let ylist = String.make y '('

let () =
  Printf.printf "%s\n" (ylist ^ string ^ xlist)


Scanf.scanf "%d %d" (fun a b ->
    if a + b >= 10 then print_endline "error"
                   else Printf.printf "%d\n" (a + b)
)

Score : 100 points

Problem Statement

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

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

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


let () =
  Scanf.scanf "%d %d" (fun a b ->
      if a + b >= 10 then "error" else (string_of_int (a + b)))
  |> print_endline


Scanf.scanf "%s" (fun s ->
    let n = String.length s in
    let rec loop i acc =
        if i = n then "yes" else
            let c = int_of_char s.[i] - 97 in
            let m = 1 lsl c in
            if m land acc = 0 then loop (i + 1) (acc lor c)
            else "no"
    in
    loop 0 0 |> print_endline
)

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different.

Constraints

2 ≤ |S| ≤ 26, where |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

If all the characters in S are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes


let s = read_line ()
let _ = String.(iteri (fun i c -> iteri (fun j d -> if i <> j && c = d then (print_endline "no"; exit 0)) s) s); print_endline "yes"


open Batteries
open Printf
let () =
  let s = Scanf.scanf "%s " (fun a -> a) in
  let l = String.to_list s in
  let sl = List.sort_uniq compare l in

  Printf.printf "%s\n" @@
  if List.length l = (List.length sl) then "yes" else "no"


Scanf.scanf "%d %d %d" (fun n a b ->
    let h = Array.init n (fun _ -> Scanf.scanf " %d" (fun h -> h)) in
    Array.sort compare h;

    let check m =
        let c = a - b in
        let s = Array.fold_left (fun acc v ->
            acc + (max 0 (v - m * b) + c - 1) / c) 0 h
        in
        s <= m
    in

    let rec bin left right =
        if left = right then left else
            let m = (left + right) / 2 in
            if check m then bin left m
                       else bin (m + 1) right
    in
    bin 0 ((h.(n - 1) + b - 1) / b + 1) |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

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

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

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

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

Constraints

All input values are integers.

1 ≤ N ≤ 10^5

1 ≤ B < A ≤ 10^9

1 ≤ h_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N A B
h_1
h_2
:
h_N

Output

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

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

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

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

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

Sample Input 2

2 10 4
20
20

Sample Output 2

4

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

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000


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

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

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

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

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

let ans = func 1 max

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


(** val add : int -> int -> int **)

let rec add = ( + )

(** val sub : int -> int -> int **)

let rec sub = ( - )

module Nat =
 struct
  (** val div2 : int -> int **)

  let rec div2 = (fun x -> x / 2)
 end

(** val lower_bound_aux : (int -> bool) -> int -> int -> int **)

let rec lower_bound_aux p_dec x x0 =
  (fun fO fS n -> if n = 0 then fO () else fS (n-1))
    (fun _ ->
    x)
    (fun n0 ->
    if p_dec (add x (Nat.div2 (succ n0)))
    then lower_bound_aux p_dec x (Nat.div2 (succ n0))
    else lower_bound_aux p_dec (add (succ (Nat.div2 (succ n0))) x)
           (sub (succ n0) (succ (Nat.div2 (succ n0)))))
    x0

(** val lower_bound : (int -> bool) -> int -> int -> int **)

let lower_bound p_dec alpha beta =
  lower_bound_aux p_dec alpha (sub beta alpha)

let () =
  let n, a, b = Scanf.scanf "%d %d %d\n" (fun n a b -> n, a, b) in
  let hs = Array.init n (fun _ -> Scanf.scanf "%d\n" (fun h -> h)) in
  lower_bound
    (fun x -> Array.fold_left ( + ) 0 (Array.map (fun h -> max 0 ((h - b * x + a - b - 1) / (a - b))) hs) <= x)
    (Array.fold_left max 0 hs / a)
    ((Array.fold_left max 0 hs + b - 1) / b)
  |> Printf.printf "%d\n"


let a = [1;3;5;7;8;10;12];;
let b = [4;6;9;11];;
let c = [2];;

let (x, y) = Scanf.scanf "%d %d" (fun x y -> (x, y));;
let ans =
  if List.mem x a && List.mem y a then
    "Yes"
  else if List.mem x b && List.mem y b then
    "Yes"
  else if List.mem x c && List.mem y c then
    "Yes"
  else
    "No";;
let () = print_endline ans;;

Score : 100 points

Problem Statement

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

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

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

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


open List;;
Scanf.scanf "%d %d" @@ fun x y -> print_endline @@
  if x = 2 || y = 2 then "No"
  else if exists (fun g -> mem x g && mem y g) [[1; 3; 5; 7; 8; 10; 12]; [4; 6; 9; 11]] then "Yes"
  else "No"


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

  let a = [1;3;5;7;8;10;12] in
  let b = [4;6;9;11] in
  let c = [2] in

  Printf.printf "%s\n" @@
  if List.mem x a && List.mem y a || List.mem x b && List.mem y b || List.mem x c && List.mem y c then
    "Yes" else "No"


let ar = [|1;3;1;2;1;2;1;1;2;1;2;1|]
let f x y = if ar.(x-1) = ar.(y-1) then "Yes" else "No"
let () = Scanf.scanf "%d %d" f |> print_endline


let g = [| 0; 1; 3; 1; 2; 1; 2; 1; 1; 2; 1; 2; 1 |]

let solve a b = if g.(a) == g.(b) then "Yes" else "No"

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


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

Score : 200 points

Problem Statement

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

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

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2 3
abc
arc

Sample Output 1

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

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


open Batteries

let () =
  let n, m = Scanf.scanf " %d %d\n" (fun n m -> (n, m)) in
  let arr = Array.make n 0 in
  let () =
    1 -- m
    |> Enum.iter (fun _ ->
           Scanf.scanf " %d %d" (fun n m ->
               arr.(n - 1) <- arr.(n - 1) + 1 ;
               arr.(m - 1) <- arr.(m - 1) + 1 ) )
  in
  let () = Array.iter (fun x -> Printf.printf "%d\n" x) arr in
  ()

Score : 200 points

Problem Statement

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

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

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

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

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

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

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

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

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


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

let f n m =
  let rec aux m' map =
    if m' <= 0 then map
    else
      let a, b = Scanf.scanf "%d %d\n" (fun a b -> a, b) in
      let va = try Im.find a map with _ -> 0 in
      let vb = try Im.find b map with _ -> 0 in
      aux (pred m') (Im.add a (succ va) map |> Im.add b (succ vb))
  in
  let rec pr n' map =
    if n' > n then ()
    else
      (Printf.printf "%d\n" (try Im.find n' map with _ -> 0) ;
       pr (succ n') map)
  in
  aux m Im.empty |> pr 1

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


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

Score : 300 points

Problem Statement

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

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

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

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

1


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t
    val zero : t
    val neg_inf : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    d.(s) <- Weight.zero;
    (* n回目以降の反復 手動ループアンローリング *)
    let rec loop' n =
      if
        0 < n &&
        es.fold (fun (u, v, c) b -> (* bは更新の有無 *)
          let open Weight in
          (* c は u から v への辺の重さ
             d.(u) + c < d.(v) *)
          0 < Weight.compare d.(v) (d.(u) + c)
          (* n 回目以降に変更が起こった場合，v までの経路に負閉路が含まれている *)
          && (d.(v) <- d.(u) + c; neg.(v) <- true; true) || b) false
      then loop' (n - 1) in
    (* n-1回目までの反復 *)
    let rec loop = function
      | 0 -> loop' n
      | n ->
          if
            es.fold (fun (u, v, c) b ->
              let open Weight in
              0 < Weight.compare d.(v) (d.(u) + c) && (d.(v) <- d.(u) + c; true) || b) false
          then loop (n - 1) in
    loop (n - 1);
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let inf = -123456789012345678
  let zero = 0
  let neg_inf = 123456789012345678
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let abcs = Array.init m @@ fun _ -> Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abcs } 0 (n - 1) in
  if 123456789012345678 <= d
  then print_endline "inf"
  else Printf.printf "%d\n" d

Score : 400 points

Problem Statement

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

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

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

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

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

Constraints

2≤N≤1000

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

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

a_i≠b_i (1≤i≤M)

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

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

c_i is an integer.

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

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

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

vertex 1 → vertex 3 : score 5

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

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

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

Sample Input 3

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

Sample Output 3

-5000000000


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

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

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

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

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

4 12 20

Sample Output 1

3

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

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

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

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

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

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


let () = Scanf.scanf "%d %d %d\n" @@ fun h w k ->
  let ass = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun as_ -> as_ in
  let sy, sx =
    List.find (fun (y, x) -> ass.(y).[x] = 'S') @@
    List.concat @@ Array.to_list @@ Array.init h @@ fun y ->
      Array.to_list @@ Array.init w @@ fun x -> (y, x) in
  let visited = Array.make_matrix h w false in
  let rec dfs y x = function
    | 0 -> ()
    | k ->
        if
          0 <= y && y < h &&
          0 <= x && x < w &&
          ass.(y).[x] <> '#' &&
          not visited.(y).(x)
        then begin
          visited.(y).(x) <- true;
          dfs (y - 1) x (k - 1);
          dfs y (x - 1) (k - 1);
          dfs (y + 1) x (k - 1);
          dfs y (x + 1) (k - 1)
        end in
  dfs sy sx (k + 1);
  Printf.printf "%d\n" @@ succ @@
  Array.fold_left (Array.fold_left min) max_int @@
  Array.init h @@ fun i ->
    Array.init w @@ fun j ->
      if not visited.(i).(j)
      then max_int
      else (min (min i j) (min (h - 1 - i) (w - 1 - j)) + k - 1) / k

Score : 700 points

Problem Statement

Takahashi is locked within a building.

This building consists of H×W rooms, arranged in H rows and W columns.
We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= #, the room is locked and cannot be entered; if A_{i,j}= ., the room is not locked and can be freely entered.
Takahashi is currently at the room where A_{i,j}= S, which can also be freely entered.

Each room in the 1-st row, 1-st column, H-th row or W-th column, has an exit.
Each of the other rooms (i,j) is connected to four rooms: (i-1,j), (i+1,j), (i,j-1) and (i,j+1).

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most K times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most K locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

3 ≤ H ≤ 800

3 ≤ W ≤ 800

1 ≤ K ≤ H×W

Each A_{i,j} is # , . or S.

There uniquely exists (i,j) such that A_{i,j}= S, and it satisfies 2 ≤ i ≤ H-1 and 2 ≤ j ≤ W-1.

Input

Input is given from Standard Input in the following format:

H W K
A_{1,1}A_{1,2}...A_{1,W}
:
A_{H,1}A_{H,2}...A_{H,W}

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room (1,2) in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room (1,2).
Then, he can move to room (1,2) in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2


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

  Printf.printf "%s\n" @@
  if
    (String.sub a (String.length a - 1) 1) = (String.sub b 0 1) &&
    (String.sub b (String.length b - 1) 1) = (String.sub c 0 1)
  then "YES" else "NO"

Score : 100 points

Problem Statement

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

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

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

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

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

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

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


open String
let () =
  Scanf.scanf "%s %s %s" (fun a b c ->
      let lena = length a and lenb = length b in
      if a.[lena-1] = b.[0] && b.[lenb-1] = c.[0] then "YES"
      else "NO")
  |> print_endline


let f s = s.[String.length s - 1]
let () = Scanf.scanf "%s %s %s" (fun a b c -> if f a = b.[0] && f b = c.[0] then "YES" else "NO")
|> print_endline


Scanf.scanf "%d %d %d" (fun a b c ->
    let rec loop i =
        if i = b then "NO" else
            if (i * a) mod b = c then "YES" else loop (i + 1)
    in
    loop 0 |> print_endline
)

Score : 200 points

Problem Statement

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

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

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

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

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

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

Sample Input 2

2 2 1

Sample Output 2

NO

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

Sample Input 3

1 100 97

Sample Output 3

YES

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

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


Scanf.scanf " %d %d %d" @@ fun a b c ->
  let rems = Array.make b false in
  let rec f n =
    let r = n mod b in
    if r = c then (print_endline "YES"; exit 0)
    else if rems.(r) then (print_endline "NO"; exit 0)
    else
      (rems.(r) <- true;
      f (n + a)) in
  f a


open Batteries
let () =
  let n, l = Scanf.scanf "%d %d" (fun x y -> x, y) in
  let f (acc, prev) t = (acc + min l (t - prev), t) in
  List.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))
  |> List.fold_left f (0, -l)
  |> fst |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

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

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

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

How long will the shower emit water in total?

Constraints

1 ≤ N ≤ 200,000

1 ≤ T ≤ 10^9

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

T and each t_i are integers.

Input

Input is given from Standard Input in the following format:

N T
t_1 t_2 ... t_N

Output

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

Sample Input 1

2 4
0 3

Sample Output 1

7

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

Sample Input 2

2 4
0 5

Sample Output 2

8

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

Sample Input 3

4 1000000000
0 1000 1000000 1000000000

Sample Output 3

2000000000

Sample Input 4

1 1
0

Sample Output 4

1

Sample Input 5

9 10
0 3 5 7 100 110 200 300 311

Sample Output 5

67


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

Score : 100 points

Problem Statement

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

s_1 s_2 s_3

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

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

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


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


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

  let a = String.uppercase_ascii (String.sub a 0 1) in
  let b = String.uppercase_ascii (String.sub b 0 1) in
  let c = String.uppercase_ascii (String.sub c 0 1) in

  Printf.printf "%s\n" (a ^ b ^ c)


let a = read_line () in
let b = read_line () in
let al = String.length a in
let bl = String.length b in
print_endline @@
if al > bl then "GREATER" else
    if al < bl then "LESS" else
        if a > b then "GREATER" else
            if a < b then "LESS" else
                "EQUAL"

Score : 200 points

Problem Statement

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

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

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

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


let a = read_line ()
let b = read_line ()
let n, m = String.length a, String.length b
let _ = print_endline @@ match if n < m then -1 else if n > m then 1 else compare a b with 1 -> "GREATER" | 0 -> "EQUAL" | _ -> "LESS"


open Bytes
let a, b = Scanf.scanf " %s %s" @@ fun a b -> a, b
let n, m = String.length a, String.length b
let ma = max n m
let a', b' = make ma '0', make ma '0'
let _ =
  List.iter (fun (b, s, l) -> String.iteri (fun i -> set b (i + ma - l)) s) [a', a, n; b', b, m];
  print_endline @@ if a' > b' then "GREATER" else if a' < b' then "LESS" else "EQUAL"


open Batteries
let n = Scanf.scanf "%d" (fun x -> x)
let a = List.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))
let rec solve acc sum sign = function
  | [] -> acc
  | (x::xs) ->
      if (sum+x) * sign > 0 then
        solve acc (sum+x) (-sign) xs
      else
        let acc' = acc + abs (sum+x - sign) in
        solve acc' sign (-sign) xs

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

Score : 300 points

Problem Statement

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

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

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

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

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

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

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


let rec seq s t f = if s > t then []
                    else (f s) :: seq (s + 1) t f
let _ =
  let n::k::_ = List.map int_of_string @@ Str.split (Str.regexp "[ \t]+") (read_line ()) in
  let hs = List.map int_of_string @@ Str.split (Str.regexp "[ \t]+") (read_line ()) in
  print_endline @@ string_of_int @@
    List.fold_left (+) 0 @@
      List.map2 (-) (seq 0 (n-1) (fun x -> List.hd hs + x)) hs

Max Score: 350 Points

Problem Statement

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

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

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

You cannot decrease height of buildings.

Calculate the minimum cost of satisfying Chokudai's objective.

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

Input Format

N K
a_1 a_2 a_3 ... a_N

Output Format

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

Constraints

1 ≤ K ≤ N ≤ 15

1 ≤ a_i ≤ 10^9

Scoring

Subtask 1 [120 points]

N = K

Subtask 2 [90 points]

N ≤ 5

a_i ≤ 7

Subtask 3 [140 points]

There are no additional constraints.

Sample Input 1

5 5
3949 3774 3598 3469 3424

Sample Output 1

1541

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

Sample Input 2

5 3
7 4 2 6 4

Sample Output 2

7

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


Scanf.scanf "%d %d %d"
(fun a b c -> (b-a) = (c-b))
|> (fun b -> match b with true -> "YES" | false -> "NO")
|> Printf.printf "%s\n"

Score : 100 points

Problem Statement

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

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

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

Sample Input 1

2 4 6

Sample Output 1

YES

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

Sample Input 2

2 5 6

Sample Output 2

NO

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

Sample Input 3

3 2 1

Sample Output 3

YES

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


let o = read_line ()

let e = read_line ()

let rec solve i =
  try
    print_char o.[i];
    print_char e.[i];
    solve (i + 1)
  with _ -> ()

let () = solve 0

Score : 200 points

Problem Statement

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

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

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

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

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


let o = read_line ()
let e = read_line ()
let _ = String.(init (length o + length e) (fun i -> [|o; e|].(i mod 2).[i / 2])) |> print_endline


let o = read_line ()
let e = read_line ()
let buf = Buffer.create (String.length o * 2)

let () =
  if String.length o = String.length e then
    for i = 0 to (String.length o - 1) do
      Buffer.add_char buf o.[i] ;
      Buffer.add_char buf e.[i] ;
    done
  else
    begin
      for i = 0 to (String.length e - 1) do
        Buffer.add_char buf o.[i] ;
        Buffer.add_char buf e.[i] ;
      done ;
      Buffer.add_char buf o.[String.length o - 1]
    end ;
  print_endline (Buffer.contents buf)


open Batteries

let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let s_l = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%s " (fun a -> a)) in
  let c_l_l = List.map (fun s -> String.to_list s |> List.sort compare) s_l in

  let intersection xs ys =
    List.fold_left (fun a b -> if List.mem b ys then (b::a) else a) [] xs
  in

  let res = List.fold_left intersection (List.hd c_l_l) (List.tl c_l_l) in

  Printf.printf "%s\n" @@
  String.of_list res

Score : 300 points

Problem Statement

Snuke loves "paper cutting": he cuts out characters from a newspaper headline and rearranges them to form another string.

He will receive a headline which contains one of the strings S_1,...,S_n tomorrow.
He is excited and already thinking of what string he will create.
Since he does not know the string on the headline yet, he is interested in strings that can be created regardless of which string the headline contains.

Find the longest string that can be created regardless of which string among S_1,...,S_n the headline contains.
If there are multiple such strings, find the lexicographically smallest one among them.

Constraints

1 \leq n \leq 50

1 \leq |S_i| \leq 50 for every i = 1, ..., n.

S_i consists of lowercase English letters (a - z) for every i = 1, ..., n.

Input

Input is given from Standard Input in the following format:

n
S_1
...
S_n

Output

Print the lexicographically smallest string among the longest strings that satisfy the condition.
If the answer is an empty string, print an empty line.

Sample Input 1

3
cbaa
daacc
acacac

Sample Output 1

aac

The strings that can be created from each of cbaa, daacc and acacac, are aa, aac, aca, caa and so forth.
Among them, aac, aca and caa are the longest, and the lexicographically smallest of these three is aac.

Sample Input 2

3
a
aa
b

Sample Output 2

The answer is an empty string.


Scanf.scanf "%d %d" (fun n m ->
    let mm = 1_000_000_007 in
    let ( +@) a b = (((a + b) mod mm) + mm) mod mm in
    let ( *@) a b = (a * b) mod mm in
    let calc lim =
        Scanf.scanf " %d" (fun offset ->
            let rec loop i coeff acc =
                if i = lim then acc else
                    let acc = acc +@ coeff *@ Scanf.scanf " %d" (fun x -> x - offset) in
                    loop (i + 1) (coeff + 2) acc
            in
            loop 1 (3 - lim) 0
        )
    in
    Printf.printf "%d\n" @@ (calc m *@ calc n)
)

Score : 500 points

Problem Statement

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

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

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

Constraints

2 \leq n,m \leq 10^5

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

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

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

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

Sample Input 2

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

Sample Output 2

835067060


let c = 1000000007

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

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


let () = Scanf.scanf "%s\n%s\n%d\n" @@ fun s t q ->
  let count_s = Array.make (String.length s + 1) 0 in
  let count_t = Array.make (String.length t + 1) 0 in
  String.iteri (fun i c ->
    count_s.(i + 1) <- count_s.(i) + if c = 'A' then 1 else 2) s;
  String.iteri (fun i c ->
    count_t.(i + 1) <- count_t.(i) + if c = 'A' then 1 else 2) t;
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d %d %d\n" @@ fun a b c d ->
      print_endline @@
      if (count_s.(b) - count_s.(a - 1)) mod 3 = (count_t.(d) - count_t.(c - 1)) mod 3 then "YES" else "NO"
  done

Score : 600 points

Problem Statement

Let us consider the following operations on a string consisting of A and B:

Select a character in a string. If it is A, replace it with BB. If it is B, replace with AA.

Select a substring that is equal to either AAA or BBB, and delete it from the string.

For example, if the first operation is performed on ABA and the first character is selected, the string becomes BBBA.
If the second operation is performed on BBBAAAA and the fourth through sixth characters are selected, the string becomes BBBA.

These operations can be performed any number of times, in any order.

You are given two string S and T, and q queries a_i, b_i, c_i, d_i.
For each query, determine whether S_{a_i} S_{{a_i}+1} ... S_{b_i}, a substring of S, can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, a substring of T.

Constraints

1 \leq |S|, |T| \leq 10^5

S and T consist of letters A and B.

1 \leq q \leq 10^5

1 \leq a_i \leq b_i \leq |S|

1 \leq c_i \leq d_i \leq |T|

Input

Input is given from Standard Input in the following format:

S
T
q
a_1 b_1 c_1 d_1
...
a_q b_q c_q d_q

Output

Print q lines. The i-th line should contain the response to the i-th query. If S_{a_i} S_{{a_i}+1} ... S_{b_i} can be made into T_{c_i} T_{{c_i}+1} ... T_{d_i}, print YES. Otherwise, print NO.

Sample Input 1

BBBAAAABA
BBBBA
4
7 9 2 5
7 9 1 4
1 7 2 5
1 7 2 4

Sample Output 1

YES
NO
YES
NO

The first query asks whether the string ABA can be made into BBBA.
As explained in the problem statement, it can be done by the first operation.

The second query asks whether ABA can be made into BBBB, and the fourth query asks whether BBBAAAA can be made into BBB.
Neither is possible.

The third query asks whether the string BBBAAAA can be made into BBBA.
As explained in the problem statement, it can be done by the second operation.

Sample Input 2

AAAAABBBBAAABBBBAAAA
BBBBAAABBBBBBAAAAABB
10
2 15 2 13
2 13 6 16
1 13 2 20
4 20 3 20
1 18 9 19
2 14 1 11
3 20 3 15
6 16 1 17
4 18 8 20
7 20 3 14

Sample Output 2

YES
YES
YES
YES
YES
YES
NO
NO
NO
NO


let rec input xs n =
    if n = 0 then
        xs
    else
        let a = Scanf.scanf "%d " (fun a -> a) in
        input (a :: xs) (n-1)

let rec solve xs n res
    = if n = 0 then
          Printf.printf "%d\n" res
      else
          solve xs (n-1) (res + (List.nth xs (1 + (n-1)*2)))

let _ =
    let xs = Scanf.scanf "%d " (fun n -> 3 * n) |> input [] |> List.sort compare in
    let xs = List.rev xs in
    solve xs ((List.length xs) / 3) 0

Score : 300 points

Problem Statement

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

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

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

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

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

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

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

Sample Input 2

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

Sample Output 2

10000000000

The sum of the strengths can be quite large.


let get_odd lst =
	let rec loop idx acc lst =
		match lst with
		| [] -> acc
		| x :: xs ->
			if idx mod 2 = 1 then loop (idx + 1) (x :: acc) xs
			else loop (idx + 1) acc xs
	in
	loop 0 [] lst

let rec head n lst =
	match lst with
	| [] -> []
	| x :: xs ->
		if n > 0 then x :: head (n - 1) xs
		else []

let () =
	let n = read_int () in
	let a =
		read_line ()
		|> Str.split (Str.regexp " ")
		|> List.map int_of_string
	in
	get_odd a
	|> head n
	|> List.fold_left (+) 0
	|> print_int
	|> print_newline


let _ = Scanf.sscanf (read_line()) "%d %d" (fun a b ->
  if a + b >= 24 then a + b - 24 else a + b
) |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

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

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

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

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

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

A B

Output

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

Sample Input 1

9 12

Sample Output 1

21

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

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

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


let rec search x y m cd index ans =
if cd = []
then
    ans
else
    let (c,d) = (List.hd cd)  in
    let dis = abs(x-c) + abs(y-d) in
    if dis <= m
    then
        search x y dis (List.tl cd) (index-1) index
    else
        search x y m (List.tl cd) (index-1) ans;;

let n,m = Scanf.scanf "%d %d " (fun a b -> a,b) in
let rec loop i=
    if i <= 0
    then
         []
    else
        (Scanf.scanf "%d %d " (fun a b -> a,b)) :: loop (i-1) in
let ab = List.rev (loop n) in
let cd = loop m in
let rec loop2 ls =
    match ls with
        |[] -> ()
        |(a,b)::tail ->  Printf.printf "%d\n" (search a b 1000000000 cd m 0);loop2 tail in
loop2 ab;;


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


let rt a b = (a + b) mod 24

let _ =
  Printf.printf "%d\n" @@ Scanf.scanf "%d %d\n" rt


let read_array n = Array.init n (fun _ -> Scanf.scanf "%d %d\n" (fun x y -> x, y))

let md (x1, y1) (x2, y2) = abs (x1 - x2) + abs (y1 - y2)

let ans n m ab cd =
  let rec solve i =
    if i < n then
      let abi = ab.(i) in
      let rec f j d ret =
        if j = m then ret
        else
          let t = md abi cd.(j) in
          if t < d then f (j + 1) t (j + 1)
          else f (j + 1) d ret
      in (Printf.printf "%d\n" (f 0 1000000000 0); solve (i + 1))
  in solve 0

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let ab = read_array n
  and cd = read_array m in
  ans n m ab cd

Score : 200 points

Problem Statement

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

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

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

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

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

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

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

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

All input values are integers.

Input

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

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

Output

Print N lines.

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

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

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

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

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

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

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

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

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

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

Sample Input 2

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

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

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

Sample Output 3

5
4
3
2
1