let solve monsters =
  let min_hp = List.hd monsters in
  let monsters = List.tl monsters in
  let rec inner cur_min =
    let ls = List.filter (fun e -> e mod cur_min <> 0) monsters in
    match ls with
    | [] -> cur_min
    | ls ->
       List.fold_left (fun me e -> min me (e mod cur_min)) max_int ls |> inner
  in inner min_hp

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let monsters = ref [] in
  for i = 0 to n - 1 do
    Scanf.scanf (if i <> n - 1 then "%d " else "%d\n")
      (fun m -> monsters := m::!monsters)
  done;
  List.sort (compare) !monsters
  |> solve |> print_int

Score : 300 points

Problem Statement

There are N monsters, numbered 1, 2, ..., N.

Initially, the health of Monster i is A_i.

Below, a monster with at least 1 health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be 2, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


let cost = Array.get [| 2; 5; 5; 4; 5; 6; 3; 7; 6 |]

let () = Scanf.scanf "%d %d" @@ fun n m ->
  let as_ = Array.init m @@ fun m -> Scanf.scanf "%c%d" @@ fun _ a -> a in
  let dp = Array.make (n + 10) (-1, []) in
  dp.(0) <- (0, []);
  for i = 0 to n - 1 do
    Array.iter (fun a ->
      if 0 <= fst dp.(i) then
        dp.(i + cost (a - 1)) <-
          max dp.(i + cost (a - 1)) @@ (fst dp.(i) + 1, a :: snd dp.(i))) as_
  done;
  List.iter print_int (snd dp.(n));
  print_newline ()

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

Score : 400 points

Problem Statement

Find the largest integer that can be formed with exactly N matchsticks, under the following conditions:

Every digit in the integer must be one of the digits A_1, A_2, ..., A_M (1 \leq A_i \leq 9).

The number of matchsticks used to form digits 1, 2, 3, 4, 5, 6, 7, 8, 9 should be 2, 5, 5, 4, 5, 6, 3, 7, 6, respectively.

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

There exists an integer that can be formed by exactly N matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

Print the largest integer that can be formed with exactly N matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer 777773 can be formed with 3 + 3 + 3 + 3 + 3 + 5 = 20 matchsticks, and this is the largest integer that can be formed by 20 matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a 64-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654

Submitted source-code file size, in bytes.

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

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


Scanf.scanf " %d %d" @@ fun n k ->
  print_string @@ if 2*k - 1 > n then "NO" else "YES"

Score : 100 points

Problem Statement

Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.

Constraints

1\leq N,K\leq 100

N and K are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

If we can choose K integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose 1 and 3.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO


let ab_s = Array.init 3 @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let cs = Array.make 5 0
let _ = Array.iter (fun (a, b) -> cs.(a) <- cs.(a) + 1; cs.(b) <- cs.(b) + 1) ab_s;
  for i = 1 to 4 do if cs.(i) = 0 || cs.(i) >= 3 then (print_endline "NO"; exit 0) done;
  print_endline "YES"

Score : 200 points

Problem Statement

There are four towns, numbered 1,2,3 and 4.
Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally.
No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roads.

Determine if we can visit all the towns by traversing each of the roads exactly once.

Constraints

1 \leq a_i,b_i \leq 4(1\leq i\leq 3)

a_i and b_i are different. (1\leq i\leq 3)

No two roads connect the same pair of towns.

Any town can be reached from any other town using the roads.

Input

Input is given from Standard Input in the following format:

a_1 b_1
a_2 b_2
a_3 b_3

Output

If we can visit all the towns by traversing each of the roads exactly once, print YES; otherwise, print NO.

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

We can visit all the towns in the order 1,3,2,4.

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES


Scanf.scanf "%d %d %d" (fun k a b ->
  if k < a-1 || b-a < 2 then k+1
  else a + (k-a+1) / 2 * (b-a) + (k-a+1) mod 2)
|> Printf.printf "%d\n"

Score : 400 points

Problem Statement

Snuke has one biscuit and zero Japanese yen (the currency) in his pocket.
He will perform the following operations exactly K times in total, in the order he likes:

Hit his pocket, which magically increases the number of biscuits by one.

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

Find the maximum possible number of biscuits in Snuke's pocket after K operations.

Constraints

1 \leq K,A,B \leq 10^9

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

Print the maximum possible number of biscuits in Snuke's pocket after K operations.

Sample Input 1

4 2 6

Sample Output 1

7

The number of biscuits in Snuke's pocket after K operations is maximized as follows:

Hit his pocket. Now he has 2 biscuits and 0 yen.

Exchange 2 biscuits to 1 yen. his pocket. Now he has 0 biscuits and 1 yen.

Hit his pocket. Now he has 1 biscuits and 1 yen.

Exchange 1 yen to 6 biscuits. his pocket. Now he has 7 biscuits and 0 yen.

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


let () = Scanf.scanf "%d %d %d" @@ fun k a b ->
    Printf.printf "%d" @@ max (a + (k - a + 1) * (b - a) / 2 - if (k - a + 1) mod 2 = 1 then 1 else 0) (k + 1)


open Scanf
open Printf
open Array

let max_i64,(++),i64 = Int64.(max_int,add,of_int)

let () = scanf " %d" @@ fun l ->
  let a = init l (fun _ -> scanf " %d" @@ fun v -> v) in
  let dp = make_matrix (l+1) 5 max_i64 in
  let f typ v = i64 @@
    match typ with
    | 0 | 4 -> (* zero *)
      v
    | 1 | 3 -> (* even >= 2 *)
      if v=0 then 2
      else if v mod 2 = 0 then 0 else 1
    | 2 | _ -> (* odd *)
      if v mod 2 = 1 then 0 else 1
  in
  let update i j v =
    dp.(i).(j) <- min dp.(i).(j) v
  in
  for k=0 to 4 do
    dp.(0).(k) <- 0L;
  done;
  let to_ = [|
    [0;1;2];
    [1;2;4];
    [2;3;4];
    [3;4];
    [4]
  |] in
  for i=1 to l do
    for k=0 to 4 do
      List.iter (fun j ->
        update i j @@ dp.(i-1).(k) ++ f j a.(i-1)
      ) to_.(k)
    done
  done;
  (* iter (fun b ->
    iter (printf "%2Ld ") b;
    print_newline ()
  ) dp; *)
  printf "%Ld" @@ fold_left min max_i64 dp.(l)

Score : 600 points

Problem Statement

Snuke stands on a number line. He has L ears, and he will walk along the line continuously under the following conditions:

He never visits a point with coordinate less than 0, or a point with coordinate greater than L.

He starts walking at a point with integer coordinate, and also finishes walking at a point with integer coordinate.

He only changes direction at a point with integer coordinate.

Each time when Snuke passes a point with coordinate i-0.5, where i is an integer, he put a stone in his i-th ear.

After Snuke finishes walking, Ringo will repeat the following operations in some order so that, for each i, Snuke's i-th ear contains A_i stones:

Put a stone in one of Snuke's ears.

Remove a stone from one of Snuke's ears.

Find the minimum number of operations required when Ringo can freely decide how Snuke walks.

Constraints

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

0 \leq A_i \leq 10^9(1\leq i\leq L)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L
A_1
:
A_L

Output

Print the minimum number of operations required when Ringo can freely decide how Snuke walks.

Sample Input 1

4
1
0
2
3

Sample Output 1

1

Assume that Snuke walks as follows:

He starts walking at coordinate 3 and finishes walking at coordinate 4, visiting coordinates 3,4,3,2,3,4 in this order.

Then, Snuke's four ears will contain 0,0,2,3 stones, respectively.
Ringo can satisfy the requirement by putting one stone in the first ear.

Sample Input 2

8
2
0
0
2
1
3
4
1

Sample Output 2

3

Sample Input 3

7
314159265
358979323
846264338
327950288
419716939
937510582
0

Sample Output 3

1


open Scanf
open Printf
open Array

let max_i64,(++),i64 = Int64.(max_int,add,of_int)

let () = scanf " %d" @@ fun l ->
  let a = init l (fun _ -> scanf " %d" @@ fun v -> v) in
  let dp = make_matrix (l+1) 5 max_i64 in
  let f typ v = i64 @@
    match typ with
    | 0 | 4 -> (* zero *)
      v
    | 1 | 3 -> (* even >= 2 *)
      if v=0 then 2
      else if v mod 2 = 0 then 0 else 1
    | 2 | _ -> (* odd *)
      if v mod 2 = 1 then 0 else 1
  in
  let update i j v =
    dp.(i).(j) <- min dp.(i).(j) v
  in
  for k=0 to 4 do
    dp.(0).(k) <- 0L;
  done;
  for i=1 to l do
    for k=0 to 4 do
      for j=k to 4 do
        if k=0 && j=4 || k=1 && j=3 then ()
        else update i j @@ dp.(i-1).(k) ++ f j a.(i-1)
      done
    done
  done;
  (* iter (fun b ->
    iter (printf "%2Ld ") b;
    print_newline ()
  ) dp; *)
  printf "%Ld" @@ fold_left min max_i64 dp.(l)


let () = Scanf.scanf "%d\n" @@ fun l ->
  let as_ = Array.init l @@ fun _ -> Scanf.scanf "%d\n" @@ fun a -> a in
  let ans, dp1, dp2, dp3 =
    Array.fold_left (fun (ans, dp1, dp2, dp3) a ->
      max ans (max dp1 (max dp2 dp3)),
      (if a < 2 then 0 else a - a mod 2 + dp1),
      (if a < 1 then 0 else a - (a + 1) mod 2 + max dp1 dp2),
      (if a < 2 then 0 else a - a mod 2 + max dp2 dp3))
    (min_int, 0, 0, 0) as_ in
  Printf.printf "%d\n" @@ Array.fold_left ( + ) (( ~- ) @@ max ans @@ max dp1 @@ max dp2 dp3) as_


Scanf.scanf "%f %f" (/.) |> Printf.printf "%f\n"

Score : 100 points

Problem Statement

In order to pass the entrance examination tomorrow, Taro has to study for T more hours.

Fortunately, he can leap to World B where time passes X times as fast as it does in our world (World A).

While (X \times t) hours pass in World B, t hours pass in World A.

How many hours will pass in World A while Taro studies for T hours in World B?

Constraints

All values in input are integers.

1 \leq T \leq 100

1 \leq X \leq 100

Input

Input is given from Standard Input in the following format:

T X

Output

Print the number of hours that will pass in World A.

The output will be regarded as correct when its absolute or relative error from the judge's output is at most 10^{-3}.

Sample Input 1

8 3

Sample Output 1

2.6666666667

While Taro studies for eight hours in World B where time passes three times as fast, 2.6666... hours will pass in World A.

Note that an absolute or relative error of at most 10^{-3} is allowed.

Sample Input 2

99 1

Sample Output 2

99.0000000000

Sample Input 3

1 100

Sample Output 3

0.0100000000


let _ = Scanf.scanf "%f %f" @@ fun t x ->
    t /. x |> Printf.printf "%.10f\n"


let rec f maxN others lst =
  match lst with
  | [] -> (maxN, others)
  | x :: xs ->
    if x > maxN then f x (maxN :: others) xs
    else f maxN (x :: others) xs
let rec sum lst = match lst with
  | [] -> 0
  | x :: xs -> x + sum xs
let () = Scanf.scanf "%d\n"
    (fun n -> Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x)))
  |> Array.to_list
  |> f 0 []
  |> (fun (maxN, otherlst) -> if maxN < sum otherlst then "Yes" else "No")
  |> print_string

Score : 200 points

Problem Statement

Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other N-1 sides.

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

If an N-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since 8 < 9 = 3 + 5 + 1, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since 8 \geq 8 = 3 + 4 + 1, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


let n, m = Scanf.scanf " %d %d" @@ fun a b -> a, b
let xs = Array.init m @@ fun _ -> Scanf.scanf " %d" (+) 0
let ds = if n >= m then (print_endline "0"; exit 0); Array.(sort (-) xs; init (m - 1) @@ fun i -> xs.(i + 1) - xs.(i))
let _ = Array.(sort (fun x y -> y - x) ds; sub ds 0 @@ n - 1 |> fold_left (+) 0 |> (-) @@ xs.(m - 1) - xs.(0) |> Printf.printf "%d\n")

Score : 300 points

Problem Statement

We will play a one-player game using a number line and N pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:

Move: Choose a piece and let x be its coordinate. Put that piece at coordinate x+1 or x-1.

Note that the coordinates where we initially place the pieces are already regarded as visited.

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

-10^5 \leq X_i \leq 10^5

X_1, X_2, ..., X_M are all different.

Input

Input is given from Standard Input in the following format:

N M
X_1 X_2 ... X_M

Output

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

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates 1 and 10.

Move the piece at coordinate 1 to 2.

Move the piece at coordinate 10 to 11.

Move the piece at coordinate 11 to 12.

Move the piece at coordinate 12 to 13.

Move the piece at coordinate 13 to 14.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0


let rec sum_k acc k ls =
  match k, ls with
  | 0, _ -> acc
  | _, [] -> acc
  | k, l::ls -> sum_k (l + acc) (k - 1) ls

let right (_, r) = r

let _ =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let xs = ref [] in
  let max_m, min_m = ref min_int, ref max_int in
  for i = 0 to m - 1 do
    Scanf.scanf (if i <> m - 1 then "%d " else "%d\n") (fun x -> xs := x::!xs);
    max_m := max !max_m (List.hd !xs);
    min_m := min !min_m (List.hd !xs)
  done;
  !xs
  |> List.sort compare
  |> (fun xs -> List.fold_left (fun (prev, acc) x -> (x, (x - prev)::acc))
                  (List.hd xs, []) @@ List.tl xs)
  |> right
  |> List.sort (fun x y -> 1 - (compare x y))
  |> sum_k 0 (n - 1)
  |> (fun ls -> (!max_m - !min_m) - ls)
  |> print_int


Scanf.scanf " %d %d %d" @@ fun n a b ->
  Printf.printf "%d %d" (max (a+b-n) 0) (min a b)

Score : 100 points

Problem Statement

We conducted a survey on newspaper subscriptions.
More specifically, we asked each of the N respondents the following two questions:

Question 1: Are you subscribing to Newspaper X?

Question 2: Are you subscribing to Newspaper Y?

As the result, A respondents answered "yes" to Question 1, and B respondents answered "yes" to Question 2.

What are the maximum possible number and the minimum possible number of respondents subscribing to both newspapers X and Y?

Write a program to answer this question.

Constraints

1 \leq N \leq 100

0 \leq A \leq N

0 \leq B \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the maximum possible number and the minimum possible number of respondents subscribing to both newspapers, in this order, with a space in between.

Sample Input 1

10 3 5

Sample Output 1

3 0

In this sample, out of the 10 respondents, 3 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 3 and at least 0.

Sample Input 2

10 7 5

Sample Output 2

5 2

In this sample, out of the 10 respondents, 7 answered they are subscribing to Newspaper X, and 5 answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most 5 and at least 2.

Sample Input 3

100 100 100

Sample Output 3

100 100


let rv f p q = f q p;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let a,b = make n 0,make n 0 in
  init n (fun i -> scanf " %d %d" @@ fun u v -> a.(i) <- u; b.(i) <- v);
  let c = init n (fun i -> a.(i)+b.(i),i) in
  sort (rv compare) c;
  print_int @@ fst @@
    fold_left (fun (sum,j) (_,i) ->
      (sum + if j mod 2 = 0 then a.(i) else -b.(i)),j+1
    ) (0,0) c))

Score : 400 points

Problem Statement

There are N dishes of cuisine placed in front of Takahashi and Aoki.
For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.

When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.

Starting from Takahashi, they alternately choose one dish and eat it, until there is no more dish to eat.
Here, both of them choose dishes so that the following value is maximized: "the sum of the happiness he/she will earn in the end" minus "the sum of the happiness the other person will earn in the end".

Find the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the value: "the sum of the happiness Takahashi earns in the end" minus "the sum of the happiness Aoki earns in the end".

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

In this sample, both of them earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since Takahashi and Aoki have the same "taste", each time they will choose the dish with which they can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (30 + 10) - 20 = 20.

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

In this sample, Takahashi earns 20 points of happiness by eating any one of the dishes 1, 2 and 3, but Aoki earns 10 points of happiness by eating Dish 1, 20 points by eating Dish 2, and 30 points by eating Dish 3.

In this case, since only Aoki has likes and dislikes, each time they will choose the dish with which Aoki can earn the greatest happiness. Thus, first Takahashi will choose Dish 3, then Aoki will choose Dish 2, and finally Takahashi will choose Dish 1, so the answer is (20 + 20) - 20 = 20.

Sample Input 3

6
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 3

-2999999997

Note that the answer may not fit into a 32-bit integer.


Scanf.scanf "%d %d" (fun n m ->
    let nei = Array.make n [] in
    let rev = Array.make n 0 in
    for i = 1 to n - 1 + m do
        Scanf.scanf " %d %d" (fun a b ->
            let a = a - 1 in
            let b = b - 1 in
            nei.(a) <- b :: nei.(a);
            rev.(b) <- rev.(b) + 1
        )
    done;
    let rec loop i =
        if rev.(i) = 0 then i else loop (i + 1)
    in
    let root = loop 0 in
    let par = Array.make n 0 in

    let rec loop next = function
        | [] -> if next <> [] then loop [] next
        | hd :: tl ->
            let rec loop2 next = function
                | [] -> loop next tl
                | x :: xs ->
                        par.(x) <- hd + 1; loop2 (x :: next) xs
            in
            loop2 next nei.(hd)
    in
    loop [] [ root ];
    Array.iter (Printf.printf "%d\n") par
)

Score : 500 points

Problem Statement

There is a rooted tree (see Notes) with N vertices numbered 1 to N.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex 1.

Takahashi has added M new directed edges to this graph.
Each of these M edges, u \rightarrow v, extends from some vertex u to its descendant v.

You are given the directed graph with N vertices and N-1+M edges after Takahashi added edges.
More specifically, you are given N-1+M pairs of integers, (A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M}), which represent that the i-th edge extends from Vertex A_i to Vertex B_i.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

If i \neq j, (A_i, B_i) \neq (A_j, B_j).

The graph in input can be obtained by adding M edges satisfying the condition in the problem statement to a rooted tree with N vertices.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_{N-1+M} B_{N-1+M}

Output

Print N lines.
In the i-th line, print 0 if Vertex i is the root of the original tree, and otherwise print the integer representing the parent of Vertex i in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge 1 \rightarrow 3 to the rooted tree 1 \rightarrow 2 \rightarrow 3.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


let rec fix f x = f (fix f) x;;
Scanf.(Array.(scanf " %d %d" @@ fun n m ->
  let e = make n [] in
  let e_rev = make n [] in
  init (n-1+m) (fun i -> scanf " %d %d" @@ fun u v ->
    let u,v = u-1,v-1 in
    e.(u) <- v :: e.(u);
    e_rev.(v) <- u :: e_rev.(v)
  ) |> ignore;
  let root = fst @@ fold_left (fun (root,i) ls ->
    (if List.length ls = 0 then i else root),i+1
  ) (0,0) e_rev in
  let dep = make n 0 in
  fix (fun f i d ->
    dep.(i) <- max dep.(i) d;
    List.iter (fun j ->
      f j (d+1)
    ) e.(i)
  ) root 0;
  (* iteri (fun i d -> Printf.printf "%d: %d\n" i d) dep; *)
  let res = make n 0 in
  fix (fun f i d ->
    List.iter (fun j ->
      if dep.(j) = d+1 then res.(j) <- i + 1;
      f j (d+1)
    ) e.(i)
  ) root 0;
  res.(root) <- 0;
  iter (fun d -> Printf.printf "%d\n" d) res;
))


open Printf
open Scanf

let solve a b = a * b / 2

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

Score : 100 points

Problem Statement

There is a right triangle ABC with ∠ABC=90°.

Given the lengths of the three sides, |AB|,|BC| and |CA|, find the area of the right triangle ABC.

It is guaranteed that the area of the triangle ABC is an integer.

Constraints

1 \leq |AB|,|BC|,|CA| \leq 100

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


let () = Scanf.scanf "%d %d %d" @@ fun ab bc _ ->
    Printf.printf "%d" (ab * bc / 2)


module IntSet = Set.Make (struct type t = int let compare = (-) end)
let _ =
  let s = read_int () in
  let rec find i set n =
    if IntSet.mem n set then
      i
    else
      find (i + 1) (IntSet.add n set) @@ if n mod 2 = 0 then n / 2 else 3 * n + 1
  in
    find 1 IntSet.empty s |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

A sequence a=\{a_1,a_2,a_3,......\} is determined as follows:

The first term s is given as input.

Let f(n) be the following function: f(n) = n/2 if n is even, and f(n) = 3n+1 if n is odd.

a_i = s when i = 1, and a_i = f(a_{i-1}) when i > 1.

Find the minimum integer m that satisfies the following condition:

There exists an integer n such that a_m = a_n (m > n).

Constraints

1 \leq s \leq 100

All values in input are integers.

It is guaranteed that all elements in a and the minimum m that satisfies the condition are at most 1000000.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

a=\{8,4,2,1,4,2,1,4,2,1,......\}. As a_5=a_2, the answer is 5.

Sample Input 2

7

Sample Output 2

18

a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}.

Sample Input 3

54

Sample Output 3

114


let rec f hs =
    let (_, l) = Array.fold_left (fun (st, cnt) h ->
        h > 0, if h > 0 && not st then cnt + 1 else cnt)
        (false, 0)
        hs in
    if l > 0
    then l + f (Array.map (fun n -> n - 1) hs)
    else l

let id x = x

let () = Scanf.scanf "%d\n" @@ fun n ->
    Array.init n (fun _ -> Scanf.scanf " %d" id)
    |> f |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


let rv f p q = f q p
module MultiSet_test = struct
  module Make (X:Map.OrderedType) = struct
    include Map.Make(X)
    let count v set =
      try find v set with Not_found -> 0
    let remove_each v set =
      let k = count v set in
      if k<=0 then raise Not_found
      else if k=1 then remove v set
      else add v (k-1) set
    let add_each v set =
      let k = count v set in
      if k=0 then add v 1 set
      else add v (k+1) set
    let iter_each f set =
      let rec f0 k = function
      | 0 -> ()
      | i -> let () = f k in f0 k (i-1)
      in iter f0 set
    let fold_each f set ac =
      let rec f0 k i ac = match i with
      | 0 -> ac
      | i -> f0 k (i-1) (f k ac)
      in fold f0 set ac
    let bindings_each set =
      fold_each (fun v ls -> v::ls) set []
      |> List.rev
    let min_binding_each set = fst @@ min_binding set
    let max_binding_each set = fst @@ max_binding set
    let exists_each f = exists (fun k _ -> f k)
    let cardinal_each set = (* slow *)
      fold (fun _ v sum -> sum + v) set 0
  end
end
module IRSet = MultiSet_test.Make (struct type t = int let compare = rv compare end);;
Scanf.(Array.(scanf " %d %d" @@ fun n k ->
  let t,d = make n 0,make n 0 in
  let repr = make n 0 in
  init n (fun i -> scanf " %d %d" @@ fun u v ->
    t.(i) <- u-1; d.(i) <- v;
    repr.(t.(i)) <- max v repr.(t.(i))
  ) |> ignore;
  let rest = init n (fun _ -> IRSet.empty) in
  init n (fun i ->
    (* if repr.(t.(i)) <> d.(i) then *)
      rest.(t.(i)) <- IRSet.add_each d.(i) rest.(t.(i))
  ) |> ignore;
  iteri (fun i v ->
    if v>0 then rest.(i) <- IRSet.remove_each v rest.(i)
  ) repr;
  (* iteri (fun i set ->
    Printf.printf "%d: " @@ i+1; IRSet.iter_each (Printf.printf "%2d ") set;
    print_newline ()
  ) rest; *)
  let repr = to_list repr |> List.filter ((<>) 0)
  |> List.mapi (fun i v -> v,t.(i))
  |> List.sort (rv compare)
  in
  (* List.iter (fun (v,i) -> Printf.printf "%d:%d; " v @@ i+1) repr; print_newline (); *)
  let _,_,_,res,_ = init n (fun w -> w+1)
  |> fold_left (fun ((best,sum_best,repr,res,car_best) as u) w -> match repr with
    | [] -> u
    | (v,i)::t -> (
      let best = IRSet.merge (fun i p q -> match p,q with
      | Some p,Some q -> Some (p+q)
      | Some p,_ | _,Some p -> Some p
      | None,None -> None
      ) best rest.(i) in
      let car_best = car_best + IRSet.cardinal_each rest.(i) in
      (* Printf.printf "%d :: " (k-w);
      IRSet.iter_each (Printf.printf "%d ") best; print_newline (); *)
      if k - w < 0 || car_best < k - w then (
        (best,sum_best+v,t,res,car_best)
      ) else
      let best,sum = init (k-w) (fun i -> i)
      |> fold_left (fun (set,sum) _ ->
        let v = IRSet.max_binding_each set in
        (* (IRSet.remove v set,sum) *)
        (set,sum+v)
      ) (best,0)
      in
      (* Printf.printf "  %6d v. %6d :: %2d + %2d + %2d\n" res (w*w + sum + sum_best + v) (w*w) sum (sum_best + v); *)
      (best,sum_best+v,t,max res (w*w + sum + sum_best + v),car_best)
    )
  ) (IRSet.empty,0,repr,0,0) in
  print_int res
));;

Score : 400 points

Problem Statement

There are N pieces of sushi. Each piece has two parameters: "kind of topping" t_i and "deliciousness" d_i.
You are choosing K among these N pieces to eat.
Your "satisfaction" here will be calculated as follows:

The satisfaction is the sum of the "base total deliciousness" and the "variety bonus".

The base total deliciousness is the sum of the deliciousness of the pieces you eat.

The variety bonus is x*x, where x is the number of different kinds of toppings of the pieces you eat.

You want to have as much satisfaction as possible.
Find this maximum satisfaction.

Constraints

1 \leq K \leq N \leq 10^5

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

5 3
1 9
1 7
2 6
2 5
3 1

Sample Output 1

26

If you eat Sushi 1,2 and 3:

The base total deliciousness is 9+7+6=22.

The variety bonus is 2*2=4.

Thus, your satisfaction will be 26, which is optimal.

Sample Input 2

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

Sample Output 2

25

It is optimal to eat Sushi 1,2,3 and 4.

Sample Input 3

6 5
5 1000000000
2 990000000
3 980000000
6 970000000
6 960000000
4 950000000

Sample Output 3

4900000016

Note that the output may not fit into a 32-bit integer type.


Scanf.(List.(scanf " %d %d %d %d" @@ fun p q r s ->
  print_endline @@
    if [1;4;7;9] = sort compare [p;q;r;s] then "YES"
    else "NO"))

Score : 100 points

Problem Statement

You are given four digits N_1, N_2, N_3 and N_4. Determine if these can be arranged into the sequence of digits "1974".

Constraints

0 \leq N_1, N_2, N_3, N_4 \leq 9

N_1, N_2, N_3 and N_4 are integers.

Input

Input is given from Standard Input in the following format:

N_1 N_2 N_3 N_4

Output

If N_1, N_2, N_3 and N_4 can be arranged into the sequence of digits "1974", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get 1974 by swapping N_2 and N_3.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have 1974 before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO


let s = read_line ()

let k = "keyence"

let s_len = String.length s

let rec loop si ki r =
  if si = s_len then
  print_string @@ if ki = 7 then "YES" else "NO"
  else if ki = 7 then
    print_string @@ if si = s_len then "YES" else "NO"
  else
    if s.[si] = k.[ki] then
      loop (si + 1) (ki + 1) r
    else if r = 0 then print_string "NO"
    else
      let rec f i = if i = s_len then -1 else if s.[i] = k.[ki] then i else f (i + 1) in
      let ni = f si in
      if ni = -1 then print_string "NO"
      else loop (ni + 1) (ki + 1) 0

let () = loop 0 0 1

Score : 200 points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string S consisting of lowercase English letters, determine if S is a KEYENCE string.

Constraints

The length of S is between 7 and 100 (inclusive).

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


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

    let ( *@) a b = (a * b) mod 1_000_000_007 in

    let dup x =
        let n = Array.length x in
        let rec loop i =
            if i = n then false else
                if x.(i) = x.(i - 1) then true else loop (i + 1)
        in
        loop 1
    in

    let upper_bound arr v =
        let n = Array.length arr in
        let rec loop l r =
            if l = r then l else
                let m = (l + r) / 2 in
                if arr.(m) < v then loop (m + 1) r else loop l m
        in
        loop 0 n
    in

    let rec loop i acc =
        if i = 0 then acc else
            let r = upper_bound a i in
            let c = upper_bound b i in
            let mr = r < n && a.(r) = i in
            let mc = c < m && b.(c) = i in
            match mr, mc with
            | true,  true  -> loop (i - 1) acc
            | true,  false -> loop (i - 1) (acc *@ (m - c))
            | false, true  -> loop (i - 1) (acc *@ (n - r))
            | false, false -> loop (i - 1) (acc *@ ((m - c) * (n - r) - (n * m - i)))
    in
    Printf.printf "%d\n" @@ if dup a || dup b then 0 else loop (n * m) 1
)

Score : 500 points

Problem Statement

Consider writing each of the integers from 1 to N \times M in a grid with N rows and M columns, without duplicates.
Takahashi thinks it is not fun enough, and he will write the numbers under the following conditions:

The largest among the values in the i-th row (1 \leq i \leq N) is A_i.

The largest among the values in the j-th column (1 \leq j \leq M) is B_j.

For him, find the number of ways to write the numbers under these conditions, modulo 10^9 + 7.

Constraints

1 \leq N \leq 1000

1 \leq M \leq 1000

1 \leq A_i \leq N \times M

1 \leq B_j \leq N \times M

A_i and B_j are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_{N}
B_1 B_2 ... B_{M}

Output

Print the number of ways to write the numbers under the conditions, modulo 10^9 + 7.

Sample Input 1

2 2
4 3
3 4

Sample Output 1

2

(A_1, A_2) = (4, 3) and (B_1, B_2) = (3, 4). In this case, there are two ways to write the numbers, as follows:

1 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 2 in (2, 2).

2 in (1, 1), 4 in (1, 2), 3 in (2, 1) and 1 in (2, 2).

Here, (i, j) denotes the square at the i-th row and the j-th column.

Sample Input 2

3 3
5 9 7
3 6 9

Sample Output 2

0

Since there is no way to write the numbers under the condition, 0 should be printed.

Sample Input 3

2 2
4 4
4 4

Sample Output 3

0

Sample Input 4

14 13
158 167 181 147 178 151 179 182 176 169 180 129 175 168
181 150 178 179 167 180 176 169 182 177 175 159 173

Sample Output 4

343772227


let n, h, w = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = Printf.printf "%d\n" @@ (n - h + 1) * (n - w + 1)

Score : 100 points

Problem Statement

It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.

The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns.

How many ways are there to choose where to put the notice so that it completely covers exactly HW squares?

Constraints

1 \leq H, W \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
H
W

Output

Print the answer.

Sample Input 1

3
2
3

Sample Output 1

2

There are two ways to put the notice, as follows:

### ...
### ###
... ###

Here, # represents a square covered by the notice, and . represents a square not covered.

Sample Input 2

100
1
1

Sample Output 2

10000

Sample Input 3

5
4
2

Sample Output 3

8


let n, a, b = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let ps = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let cs = Array.make 3 0
let f i = cs.(i) <- cs.(i) + 1
let _ = Array.(iter (fun p -> if p <= a then f 0 else if p <= b then f 1 else f 2) ps; fold_left min cs.(0) cs) |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

You have written N problems to hold programming contests.
The i-th problem will have a score of P_i points if used in a contest.

With these problems, you would like to hold as many contests as possible under the following condition:

A contest has three problems. The first problem has a score not greater than A points, the second has a score between A + 1 and B points (inclusive), and the third has a score not less than B + 1 points.

The same problem should not be used in multiple contests.
At most how many contests can be held?

Constraints

3 \leq N \leq 100

1 \leq P_i \leq 20 (1 \leq i \leq N)

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

Two contests can be held by putting the first, second, third problems and the fourth, fifth, sixth problems together.

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

No contest can be held, because there is no problem with a score of A = 3 or less.

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1


let memoize n f =
  let dp = Hashtbl.create n in
  let rec get x =
    try Hashtbl.find dp x with
    | Not_found ->
        let result = f get x in
        Hashtbl.add dp x result;
        result in get

let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ass = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let dp = memoize (h * w) @@ fun dp -> function
    | (0, 0) -> 1
    | (i, 0) -> if ass.(i).[0] = '.' then dp (i - 1, 0) else 0
    | (0, j) -> if ass.(0).[j] = '.' then dp (0, j - 1) else 0
    | (i, j) -> if ass.(i).[j] = '.' then (dp (i - 1, j) + dp (i, j - 1)) mod 1000000007 else 0 in
  Printf.printf "%d\n" @@ dp (h - 1, w - 1)

Score : 100 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns.
Let (i, j) denote the square at the i-th row from the top and the j-th column from the left.

For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}.
If a_{i, j} is ., Square (i, j) is an empty square; if a_{i, j} is #, Square (i, j) is a wall square.
It is guaranteed that Squares (1, 1) and (H, W) are empty squares.

Taro will start from Square (1, 1) and reach (H, W) by repeatedly moving right or down to an adjacent empty square.

Find the number of Taro's paths from Square (1, 1) to (H, W).
As the answer can be extremely large, find the count modulo 10^9 + 7.

Constraints

H and W are integers.

2 \leq H, W \leq 1000

a_{i, j} is . or #.

Squares (1, 1) and (H, W) are empty squares.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}\ldotsa_{1, W}
:
a_{H, 1}\ldotsa_{H, W}

Output

Print the number of Taro's paths from Square (1, 1) to (H, W), modulo 10^9 + 7.

Sample Input 1

3 4
...#
.#..
....

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2
..
#.
..
.#
..

Sample Output 2

0

There may be no paths.

Sample Input 3

5 5
..#..
.....
#...#
.....
..#..

Sample Output 3

24

Sample Input 4

20 20
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................

Sample Output 4

345263555

Be sure to print the count modulo 10^9 + 7.


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

let memo = Array.make_matrix (succ k) 2 None

let rec solve k t =
  match memo.(k).(if t then 1 else 0) with
  | Some v -> v
  | None ->
    let v = if t then
        if k < arr.(0) then false
        else ArrayL.exists arr ~f:(fun a ->
            if k - a >= 0 then solve (k-a) false else false)
      else
      if k < arr.(0) then true
      else not @@ ArrayL.exists arr ~f:(fun a ->
          if k - a >= 0 then solve (k-a) true  = false else false) in
    memo.(k).(if t then 1 else 0) <- Some v; v

let () =
  solve k true
  |> (fun b -> Printf.printf "%s\n" (if b then "First" else "Second"))

Score : 100 points

Problem Statement

There is a set A = \{ a_1, a_2, \ldots, a_N \} consisting of N positive integers.
Taro and Jiro will play the following game against each other.

Initially, we have a pile consisting of K stones.
The two players perform the following operation alternately, starting from Taro:

Choose an element x in A, and remove exactly x stones from the pile.

A player loses when he becomes unable to play.
Assuming that both players play optimally, determine the winner.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 10^5

1 \leq a_1 < a_2 < \cdots < a_N \leq K

Input

Input is given from Standard Input in the following format:

N K
a_1 a_2 \ldots a_N

Output

If Taro will win, print First; if Jiro will win, print Second.

Sample Input 1

2 4
2 3

Sample Output 1

First

If Taro removes three stones, Jiro cannot make a move.
Thus, Taro wins.

Sample Input 2

2 5
2 3

Sample Output 2

Second

Whatever Taro does in his operation, Jiro wins, as follows:

If Taro removes two stones, Jiro can remove three stones to make Taro unable to make a move.

If Taro removes three stones, Jiro can remove two stones to make Taro unable to make a move.

Sample Input 3

2 7
2 3

Sample Output 3

First

Taro should remove two stones. Then, whatever Jiro does in his operation, Taro wins, as follows:

If Jiro removes two stones, Taro can remove three stones to make Jiro unable to make a move.

If Jiro removes three stones, Taro can remove two stones to make Jiro unable to make a move.

Sample Input 4

3 20
1 2 3

Sample Output 4

Second

Sample Input 5

3 21
1 2 3

Sample Output 5

First

Sample Input 6

1 100000
1

Sample Output 6

Second


Scanf.scanf "%d" @@ fun n ->
let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
let dp = Array.init (n+1) (fun _ -> Array.make (n+1) 0) in
for w = 1 to n do
  for i = 0 to n-w do
    dp.(i).(i+w) <-
      max (a.(i) - dp.(i+1).(i+w)) (a.(i+w-1) - dp.(i).(i+w-1))
  done;
done;
Printf.printf "%d\n" dp.(0).(n)

Score : 100 points

Problem Statement

Taro and Jiro will play the following game against each other.

Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N).
Until a becomes empty, the two players perform the following operation alternately, starting from Taro:

Remove the element at the beginning or the end of a. The player earns x points, where x is the removed element.

Let X and Y be Taro's and Jiro's total score at the end of the game, respectively.
Taro tries to maximize X - Y, while Jiro tries to minimize X - Y.

Assuming that the two players play optimally, find the resulting value of X - Y.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print the resulting value of X - Y, assuming that the two players play optimally.

Sample Input 1

4
10 80 90 30

Sample Output 1

10

The game proceeds as follows when the two players play optimally (the element being removed is written bold):

Taro: (10, 80, 90, 30) → (10, 80, 90)

Jiro: (10, 80, 90) → (10, 80)

Taro: (10, 80) → (10)

Jiro: (10) → ()

Here, X = 30 + 80 = 110 and Y = 90 + 10 = 100.

Sample Input 2

3
10 100 10

Sample Output 2

-80

The game proceeds, for example, as follows when the two players play optimally:

Taro: (10, 100, 10) → (100, 10)

Jiro: (100, 10) → (10)

Taro: (10) → ()

Here, X = 10 + 10 = 20 and Y = 100.

Sample Input 3

1
10

Sample Output 3

10

Sample Input 4

10
1000000000 1 1000000000 1 1000000000 1 1000000000 1 1000000000 1

Sample Output 4

4999999995

The answer may not fit into a 32-bit integer type.

Sample Input 5

6
4 2 9 7 1 5

Sample Output 5

2

The game proceeds, for example, as follows when the two players play optimally:

Taro: (4, 2, 9, 7, 1, 5) → (4, 2, 9, 7, 1)

Jiro: (4, 2, 9, 7, 1) → (2, 9, 7, 1)

Taro: (2, 9, 7, 1) → (2, 9, 7)

Jiro: (2, 9, 7) → (2, 9)

Taro: (2, 9) → (2)

Jiro: (2) → ()

Here, X = 5 + 1 + 9 = 15 and Y = 4 + 7 + 2 = 13.


module SegTree = struct
  module type Monoid = sig
    type t
    val e : t
    val op : t -> t -> t
  end

  module Make (S : Monoid) : sig
    type t
    type elt
    (* n要素の単位元からなるセグ木を作る *)
    val make : int -> t
    (*
     * update i f t
     * i番目の要素にfを適用したセグ木を作る
     *)
    val update : int -> (elt -> elt) -> t -> t
    (*
     * update_range l r f t
     * [l, r)の要素に自己準同型写像fを適用したセグ木を作る
     *)
    val update_range : int -> int -> (elt -> elt) -> t -> t
    (*
     * query l r t
     * [l, r)の要素の積を求める
     *)
    val query : int -> int -> t -> elt
  end with type elt = S.t = struct
    type elt = S.t
    (* sizeがセグ木の要素数，dataは要素すべてをモノイドの演算で畳み込んだもの *)
    type t = { size : int; data : elt; body : body lazy_t }
    and body = Leaf | Node of t * t

    let make_node left right =
      { size = left.size + right.size;
        data = S.op left.data right.data;
        body = lazy (Node (left, right)) }

    let rec make n =
      assert (1 <= n);
      { size = n;
        data = S.e;
        body = lazy
          begin match n with
          | 1 -> Leaf
          | n -> Node (make (n / 2), make ((n + 1) / 2))
          end }

    let rec update i f t =
      assert (0 <= i && i < t.size);
      match t with
      | { body = lazy Leaf } -> { t with data = f t.data }
      | { body = lazy (Node (left, right)) } ->
          if i < left.size then make_node (update i f left) right
          else make_node left (update (i - left.size) f right)

    let rec update_range l r f t =
      assert (0 <= l && l < r && r <= t.size);
      match t with
      | { body = lazy Leaf } -> { t with data = f t.data }
      | { body = lazy (Node (left, right)) } ->
          if l <= 0 && t.size <= r then
            { t with
              data = f t.data;
              body = lazy
                (Node
                  (update_range 0 left.size f left,
                   update_range 0 right.size f right)) }
          else if r <= left.size then
            make_node (update_range l r f left) right
          else if left.size <= l then
            make_node left (update_range (l - left.size) (r - left.size) f right)
          else
            make_node
              (update_range l left.size f left)
              (update_range 0 (r - left.size) f right)

    let rec query l r t =
      assert (0 <= l && l < r && r <= t.size);
      match t with
      | { body = lazy Leaf } -> t.data
      | { body = lazy (Node (left, right)) } ->
          if l <= 0 && t.size <= r then t.data
          else if r <= left.size then query l r left
          else if left.size <= l then query (l - left.size) (r - left.size) right
          else S.op (query l left.size left) (query 0 (r - left.size) right)
  end
end

module MaxSegTree = SegTree.Make (struct
  type t = int
  let e = min_int
  let op = max
end)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let hs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun h -> h in
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@
  MaxSegTree.query 0 (n + 1) @@
  Array.fold_left (fun st (h, a) ->
    MaxSegTree.update h (fun _ ->
      a + MaxSegTree.query 0 h st) st) (MaxSegTree.update 0 (fun _ -> 0) @@ MaxSegTree.make (n + 1)) @@
  Array.init n @@ fun i -> hs.(i), as_.(i)

Score : 100 points

Problem Statement

There are N flowers arranged in a row.
For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively.
Here, h_1, h_2, \ldots, h_N are all distinct.

Taro is pulling out some flowers so that the following condition is met:

The heights of the remaining flowers are monotonically increasing from left to right.

Find the maximum possible sum of the beauties of the remaining flowers.

Constraints

All values in input are integers.

1 \leq N \leq 2 × 10^5

1 \leq h_i \leq N

h_1, h_2, \ldots, h_N are all distinct.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N
a_1 a_2 \ldots a_N

Output

Print the maximum possible sum of the beauties of the remaining flowers.

Sample Input 1

4
3 1 4 2
10 20 30 40

Sample Output 1

60

We should keep the second and fourth flowers from the left.
Then, the heights would be 1, 2 from left to right, which is monotonically increasing, and the sum of the beauties would be 20 + 40 = 60.

Sample Input 2

1
1
10

Sample Output 2

10

The condition is met already at the beginning.

Sample Input 3

5
1 2 3 4 5
1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

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

Sample Output 4

31

We should keep the second, third, sixth, eighth and ninth flowers from the left.


let a, b, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = Printf.printf "%d\n" @@ if c >= 1 then min (c - 1) (a + b) + 1 + b else b

Score : 200 points

Problem Statement

Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

0 \leq A,B,C \leq 10^9

A,B and C are integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9


let s = Scanf.scanf " %s" @@ fun v -> v in
print_int @@
  Array.(
    init (String.length s) (fun i -> if s.[i]='2' then 1 else 0)
    |> fold_left (+) 0)

Score : 100 points

Problem Statement

You are given an integer N that has exactly four digits in base ten.
How many times does 2 occur in the base-ten representation of N?

Constraints

1000 \leq N \leq 9999

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

1222

Sample Output 1

3

2 occurs three times in 1222. By the way, this contest is held on December 22 (JST).

Sample Input 2

3456

Sample Output 2

0

Sample Input 3

9592

Sample Output 3

1


let rec fix f x = f (fix f) x
let factors n = (* O(sqrt n) *)
  let m,r = ref n,ref [] in
  for i=2 to (2+int_of_float (sqrt @@ float_of_int n)) do
    if !m mod i = 0 then (
      let k = ref 0 in
      while !m mod i = 0 do
        k := !k + 1; m := !m / i;
      done;
      r := (i,!k) :: !r
    )
  done;
  if !m>1 then (!m,1)::!r else !r
let pow n k =
  let rec f a n = function
  | 0 -> a | 1 -> n*a | k when k mod 2 = 0 -> f a (n*n) (k/2) | k -> f (a*n) (n*n) (k/2)
  in f 1 n k
let n,p = Scanf.scanf " %d %d" @@ fun u v -> u,v
let () = print_int (factors p |> List.fold_left (fun u (m,k) ->
  u * (if k>=n then pow m (k/n) else 1)) 1)

Score : 300 points

Problem Statement

There are N integers a_1, a_2, ..., a_N not less than 1.
The values of a_1, a_2, ..., a_N are not known, but it is known that a_1 \times a_2 \times ... \times a_N = P.

Find the maximum possible greatest common divisor of a_1, a_2, ..., a_N.

Constraints

1 \leq N \leq 10^{12}

1 \leq P \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N P

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be 2 when, for example, a_1=2, a_2=6 and a_3=2.

Sample Input 2

5 1

Sample Output 2

1

As a_i are positive integers, the only possible case is a_1 = a_2 = a_3 = a_4 = a_5 = 1.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206


let (n, p) = Scanf.sscanf (read_line ()) "%d %d" @@ fun n p -> (n, p)

let rec prime_fact acc i n =
  if n = 0 then acc
  else if n < i * i then n :: acc
  else if n mod i = 0 then prime_fact (i :: acc) i (n / i)
  else prime_fact acc (i + 1) n

let prime_fact n =
  List.fold_left (fun acc i ->
    match acc with
      | [] -> [(i, 1)]
      | (v, cnt) :: xs -> if v = i then (v, cnt + 1) :: xs else (i, 1) :: (v, cnt) :: xs
  ) [] @@ prime_fact [] 2 n

let ps = prime_fact p

let rec pow n = function
  | 0 -> 1
  | i -> n * pow n (i - 1)

let () =
  let ans = List.fold_left (fun ans (v, cnt) ->
    ans * (pow v (cnt / n))
  ) 1 ps in
  Printf.printf "%d\n" ans


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

let () = print_endline @@ if Array.for_all (fun i -> i mod 2 = 0) a then "second" else "first"

Score : 500 points

Problem Statement

There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.

You and Lunlun the dachshund alternately perform the following operation (starting from you):

Choose one or more apples from the tree and eat them. Here, the apples chosen at the same time must all have different colors.

The one who eats the last apple from the tree will be declared winner. If both you and Lunlun play optimally, which will win?

Constraints

1 \leq N \leq 10^5

1 \leq a_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
a_2
:
a_N

Output

If you will win, print first; if Lunlun will win, print second.

Sample Input 1

2
1
2

Sample Output 1

first

Let Color 1 be red, and Color 2 be blue. In this case, the tree bears one red apple and two blue apples.

You should eat the red apple in your first turn. Lunlun is then forced to eat one of the blue apples, and you can win by eating the other in your next turn.

Note that you are also allowed to eat two apples in your first turn, one red and one blue (not a winning move, though).

Sample Input 2

3
100000
30000
20000

Sample Output 2

second


let () = print_endline @@ Scanf.scanf "%d\n" @@ function
  | 1 -> Scanf.scanf "%d\n" @@ fun a ->
      if a mod 2 = 0 then "second" else "first"
  | n ->
      let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d\n" @@ fun a -> a in
      Array.sort (fun i j -> compare j i) as_;
      if (as_.(0) - as_.(1)) mod 2 = 0 then "second" else "first"


let k, ans = ref 0, ref 0
let _ = String.iter (function 'B' -> incr k | _ -> ans := !ans + !k) @@ read_line (); Printf.printf "%d\n" !ans

Score : 300 points

Problem Statement

There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string S of length N.
If S_i=B, the i-th piece from the left is showing black;
If S_i=W, the i-th piece from the left is showing white.

Consider performing the following operation:

Choose i (1 \leq i < N) such that the i-th piece from the left is showing black and the (i+1)-th piece from the left is showing white, then flip both of those pieces. That is, the i-th piece from the left is now showing white and the (i+1)-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

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

S_i=B or W

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6


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

      (* let jf,jt = equal_range a (pw-v) in
      let f = ref true in
      rep jf jt (fun j ->
        if !f && i<>i32 j && 0L <= j && j <= alen a-1L
        && not used.(i) && not used.(i32 j)
        && v + a.(i32 j) = pw then (
          used.(i) <- true;
          used.(i32 j) <- true;
          res += 1L;
          (* printf "  %d,%d\n" i @@ i32 j; *)
          f := false
        )
      ); *)
      (* print_array string_of_bool used; *)
    ) mp
  ) pows;
  printf "%Ld\n" !res

Score : 600 points

Problem Statement

Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i.
He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2.
Note that a ball cannot belong to multiple pairs.
Find the maximum possible number of pairs that can be formed.

Here, a positive integer is said to be a power of 2 when it can be written as 2^t using some non-negative integer t.

Constraints

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

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of pairs such that the sum of the integers written on each pair of balls is a power of 2.

Sample Input 1

3
1 2 3

Sample Output 1

1

We can form one pair whose sum of the written numbers is 4 by pairing the first and third balls.
Note that we cannot pair the second ball with itself.

Sample Input 2

5
3 11 14 5 13

Sample Output 2

2


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

      (* let jf,jt = equal_range a (pw-v) in
      let f = ref true in
      rep jf jt (fun j ->
        if !f && i<>i32 j && 0L <= j && j <= alen a-1L
        && not used.(i) && not used.(i32 j)
        && v + a.(i32 j) = pw then (
          used.(i) <- true;
          used.(i32 j) <- true;
          res += 1L;
          (* printf "  %d,%d\n" i @@ i32 j; *)
          f := false
        )
      ); *)
      (* print_array string_of_bool used; *)
    ) a
  ) pows;
  printf "%Ld\n" !res


open Printf
open Scanf

let (++) = Int64.add
let (--) = Int64.sub
let ( ** ) = Int64.mul
let (//) = Int64.div
let (%%) = Int64.rem
let landl = Int64.logand
let lorl = Int64.logor
let lnotl = Int64.lognot
let lxorl = Int64.logxor
let lsll = Int64.shift_left
let lsrl = Int64.shift_right_logical
let long = Int64.of_int
let succl = Int64.succ
let predl = Int64.pred

let read_int _ = scanf " %d " (fun x -> x)
let read_long _ = scanf " %Ld " (fun x -> x)
let read_str _ = scanf " %s " (fun x -> x)
let read_double _ = scanf " %f " (fun x -> x)

let m = 1_000_000_007L

let rec gcd a b = if b = 0L then a else gcd b (a %% b)

let rec mod_pow a = function
  | 0L -> 1L
  | b -> (if b %% 2L = 0L then 1L else a) ** mod_pow (a ** a %% m) (b//2L) %% m

let () =
  let n = read_int () in
  let p = Array.init n read_int in
  Array.sort compare p;
  p.(n-1) <- p.(n-1) / 2;
  let total = Array.fold_left ( + ) 0 p in
  printf "%d\n" total

Score : 200 points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying N items at a department store. The regular price of the i-th item (1 \leq i \leq N) is p_i yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining N-1 items cost their regular prices. What is the total amount he will pay?

Constraints

2 \leq N \leq 10

100 \leq p_i \leq 10000

p_i is an even number.

Input

Input is given from Standard Input in the following format:

N
p_1
p_2
:
p_N

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The 7980-yen item gets the discount and the total is 4980 + 7980 / 2 + 6980 = 15950 yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is 4320 / 2 + 4320 + 4320 + 4320 = 15120 yen.


let () = Scanf.scanf "%d\n" @@ fun n ->
  let ps = Array.init n @@ fun _ -> Scanf.scanf "%d\n" @@ fun p -> p in
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 ps - (Array.fold_left max min_int ps + 1) / 2


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

    let rec loop i acc =
        if i + k > n then acc else
            loop (i + 1) (min acc (h.(i + k - 1) - h.(i)))
    in
    loop 0 max_int |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

In some other world, today is Christmas Eve.

There are N trees planted in Mr. Takaha's garden. The height of the i-th tree (1 \leq i \leq N) is h_i meters.

He decides to choose K trees from these trees and decorate them with electric lights. To make the scenery more beautiful, the heights of the decorated trees should be as close to each other as possible.

More specifically, let the height of the tallest decorated tree be h_{max} meters, and the height of the shortest decorated tree be h_{min} meters. The smaller the value h_{max} - h_{min} is, the better. What is the minimum possible value of h_{max} - h_{min}?

Constraints

2 \leq K < N \leq 10^5

1 \leq h_i \leq 10^9

h_i is an integer.

Input

Input is given from Standard Input in the following format:

N K
h_1
h_2
:
h_N

Output

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

Sample Input 1

5 3
10
15
11
14
12

Sample Output 1

2

If we decorate the first, third and fifth trees, h_{max} = 12, h_{min} = 10 so h_{max} - h_{min} = 2. This is optimal.

Sample Input 2

5 3
5
7
5
7
7

Sample Output 2

0

If we decorate the second, fourth and fifth trees, h_{max} = 7, h_{min} = 7 so h_{max} - h_{min} = 0. This is optimal.

There are not too many trees in these sample inputs, but note that there can be at most one hundred thousand trees (we just can't put a sample with a hundred thousand lines here).


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

let () =
  let n,k = get_2_i64 0  in
  let h = input_i64_array n in
  sort compare h;
  let n,k = i32 n,i32 k in
  let res = ref Int64.max_int in
  repi 0 (n-$k-$0) (fun i ->
    let l,r = h.(i),h.(i+$k-$1) in
    (* printf "  %Ld,%Ld\n" l r; *)
    if r-l < !res then res := r-l;
  );
  printf "%Ld\n" @@ !res


Scanf.(Array.(
  let n,x=scanf" %d %d"@@fun u v->u,v in
  let s,p=make 50 1,make 50 1 in
  init 49 (fun i->
    s.(i+1)<-2*s.(i)+3;
    p.(i+1)<-2*p.(i)+1) |> ignore;
  let rec f lv ofs =
    assert (lv-1>=0);
    let r=s.(lv-1) in
    if ofs=1 then 0
    else if ofs<=1+r   then f (lv-1) (ofs-1)
    else if ofs =2+r   then 1 + p.(lv-1)
    else if ofs<=2+r+r then 1 + p.(lv-1) + f (lv-1) (ofs-2-r)
    else if ofs =3+r+r then 1 + 2 * p.(lv-1)
    else failwith ""
  in print_int @@ f n x
));;

Score : 400 points

Problem Statement

In some other world, today is Christmas.

Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:

A level-0 burger is a patty.

A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) burger and another bun, stacked vertically in this order from the bottom.

For example, a level-1 burger and a level-2 burger look like BPPPB and BBPPPBPBPPPBB (rotated 90 degrees), where B and P stands for a bun and a patty.

The burger Mr. Takaha will make is a level-N burger. Lunlun the Dachshund will eat X layers from the bottom of this burger (a layer is a patty or a bun). How many patties will she eat?

Constraints

1 \leq N \leq 50

1 \leq X \leq ( the total number of layers in a level-N burger )

N and X are integers.

Input

Input is given from Standard Input in the following format:

N X

Output

Print the number of patties in the bottom-most X layers from the bottom of a level-N burger.

Sample Input 1

2 7

Sample Output 1

4

There are 4 patties in the bottom-most 7 layers of a level-2 burger (BBPPPBPBPPPBB).

Sample Input 2

1 1

Sample Output 2

0

The bottom-most layer of a level-1 burger is a bun.

Sample Input 3

50 4321098765432109

Sample Output 3

2160549382716056

A level-50 burger is rather thick, to the extent that the number of its layers does not fit into a 32-bit integer.


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

let () =
  let n = get_i64 0 in
  printf @@ if n=3L || n=5L || n=7L then "YES" else "NO"

Score : 100 points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now X years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

1 ≤ X ≤ 9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.