let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let n, k = Scanf.sscanf (read_line ()) "%d %d" @@ fun n k -> (n, k)
let a = read_line () |> split_string ~pattern:" " |> List.map int_of_string

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

let map = List.fold_left (fun map i ->
  let cnt = try IntMap.find i map with Not_found -> 0 in
  IntMap.add i (cnt + 1) map
) IntMap.empty a

let rec drop n acc = match (n, acc) with
  | (0, acc) -> acc
  | (_, []) -> []
  | (n, x :: xs) -> drop (n - 1) xs

let () =
  IntMap.bindings map
  |> List.sort (fun (_, a) (_, b) -> b - a)
  |> drop k
  |> List.map snd
  |> List.fold_left (+) 0
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.

He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.

Find the minimum number of balls that Takahashi needs to rewrite the integers on them.

Constraints

1 \leq K \leq N \leq 200000

1 \leq A_i \leq N

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of balls that Takahashi needs to rewrite the integers on them.

Sample Input 1

5 2
1 1 2 2 5

Sample Output 1

1

For example, if we rewrite the integer on the fifth ball to 2, there are two different integers written on the balls: 1 and 2.
On the other hand, it is not possible to rewrite the integers on zero balls so that there are at most two different integers written on the balls, so we should print 1.

Sample Input 2

4 4
1 1 2 2

Sample Output 2

0

Already in the beginning, there are two different integers written on the balls, so we do not need to rewrite anything.

Sample Input 3

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

Sample Output 3

3


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

    let rec loop i m mi =
        if i = n then mi else
            if abs a.(i) > abs m then loop (i + 1) a.(i) i
                                 else loop (i + 1) m mi
    in
    let mi = loop 0 0 0 in
    let m = a.(mi) in
    let adjust = Array.fold_left (fun acc v -> if v * m < 0 then acc + 1 else acc) 0 a in
    Printf.printf "%d\n" (adjust + n - 1);
    Array.iteri (fun i v ->
        if v * m < 0 then Printf.printf "%d %d\n" (mi + 1) (i + 1)) a;
    if m > 0 then for i = 0 to n - 2     do Printf.printf "%d %d\n" i (i + 1) done
             else for i = n - 1 downto 1 do Printf.printf "%d %d\n" i (i - 1) done

)

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

Score : 600 points

Problem Statement

Snuke has an integer sequence, a, of length N. The i-th element of a (1-indexed) is a_{i}.

He can perform the following operation any number of times:

Operation: Choose integers x and y between 1 and N (inclusive), and add a_x to a_y.

He would like to perform this operation between 0 and 2N times (inclusive) so that a satisfies the condition below. Show one such sequence of operations.
It can be proved that such a sequence of operations always exists under the constraints in this problem.

Condition: a_1 \leq a_2 \leq ... \leq a_{N}

Constraints

2 \leq N \leq 50

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{N}

Output

Let m be the number of operations in your solution. In the first line, print m.
In the i-th of the subsequent m lines, print the numbers x and y chosen in the i-th operation, with a space in between.
The output will be considered correct if m is between 0 and 2N (inclusive) and a satisfies the condition after the m operations.

Sample Input 1

3
-2 5 -1

Sample Output 1

2
2 3
3 3

After the first operation, a = (-2,5,4).

After the second operation, a = (-2,5,8), and the condition is now satisfied.

Sample Input 2

2
-1 -3

Sample Output 2

1
2 1

After the first operation, a = (-4,-3) and the condition is now satisfied.

Sample Input 3

5
0 0 0 0 0

Sample Output 3

0

The condition is satisfied already in the beginning.

Submitted source-code file size, in bytes.

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

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


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

Score : 100 points

Problem Statement

You are parking at a parking lot. You can choose from the following two fee plans:

Plan 1: The fee will be A×T yen (the currency of Japan) when you park for T hours.

Plan 2: The fee will be B yen, regardless of the duration.

Find the minimum fee when you park for N hours.

Constraints

1≤N≤20

1≤A≤100

1≤B≤2000

All input values are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

When the minimum fee is x yen, print the value of x.

Sample Input 1

7 17 120

Sample Output 1

119

If you choose Plan 1, the fee will be 7×17=119 yen.

If you choose Plan 2, the fee will be 120 yen.

Thus, the minimum fee is 119 yen.

Sample Input 2

5 20 100

Sample Output 2

100

The fee might be the same in the two plans.

Sample Input 3

6 18 100

Sample Output 3

100


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


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let rec sum n i len =
    if i > len then 0 else (n / (int_of_float (10. ** float_of_int (i-1)))) mod 10 + sum n (i+1) len in
  Printf.printf "%s\n" (if n mod (sum n 1 (String.length (string_of_int n))) = 0 then "Yes" else "No")

Score : 200 points

Problem Statement

An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.

Given an integer N, determine whether it is a Harshad number.

Constraints

1?N?10^8

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print Yes if N is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

f(12)=1+2=3. Since 12 is divisible by 3, 12 is a Harshad number.

Sample Input 2

57

Sample Output 2

No

f(57)=5+7=12. Since 57 is not divisible by 12, 12 is not a Harshad number.

Sample Input 3

148

Sample Output 3

No


open Printf
open Scanf

let id x = x

let n = scanf "%d" id

let () =
    let r = ref 0 in
    let s = string_of_int n in
    String.iter (fun c -> r := !r + (int_of_char c - int_of_char '0')) s;
    if n mod !r = 0 then
        print_endline "Yes"
    else
        print_endline "No"


let () = Scanf.scanf "%d\n" @@ fun n ->
  let fss =
    Array.to_list @@ Array.init n @@ fun _ ->
      Array.init 10 @@ fun _ ->
        Scanf.scanf "%d " @@ fun f -> f in
  let pss =
    Array.to_list @@ Array.init n @@ fun _ ->
      Array.init 11 @@ fun _ -> Scanf.scanf "%d " @@ fun p -> p in
  Array.init 1023 (fun opening ->
    let opening = opening + 1 in
    List.map2 (fun fs ps ->
      ps.(Array.fold_left ( + ) 0
        (Array.mapi (fun i f ->
          if f = 1 && (opening land (1 lsl i)) <> 0 then 1 else 0) fs))) fss pss
    |> List.fold_left ( + ) 0)
  |> Array.fold_left max min_int
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

Joisino is planning to open a shop in a shopping street.

Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those periods.

There are already N stores in the street, numbered 1 through N.

You are given information of the business hours of those shops, F_{i,j,k}. If F_{i,j,k}=1, Shop i is open during Period k on Day j (this notation is explained below); if F_{i,j,k}=0, Shop i is closed during that period. Here, the days of the week are denoted as follows. Monday: Day 1, Tuesday: Day 2, Wednesday: Day 3, Thursday: Day 4, Friday: Day 5. Also, the morning is denoted as Period 1, and the afternoon is denoted as Period 2.

Let c_i be the number of periods during which both Shop i and Joisino's shop are open. Then, the profit of Joisino's shop will be P_{1,c_1}+P_{2,c_2}+...+P_{N,c_N}.

Find the maximum possible profit of Joisino's shop when she decides whether her shop is open during each period, making sure that it is open during at least one period.

Constraints

1≤N≤100

0≤F_{i,j,k}≤1

For every integer i such that 1≤i≤N, there exists at least one pair (j,k) such that F_{i,j,k}=1.

-10^7≤P_{i,j}≤10^7

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
F_{1,1,1} F_{1,1,2} ... F_{1,5,1} F_{1,5,2}
:
F_{N,1,1} F_{N,1,2} ... F_{N,5,1} F_{N,5,2}
P_{1,0} ... P_{1,10}
:
P_{N,0} ... P_{N,10}

Output

Print the maximum possible profit of Joisino's shop.

Sample Input 1

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

Sample Output 1

8

If her shop is open only during the periods when Shop 1 is opened, the profit will be 8, which is the maximum possible profit.

Sample Input 2

2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1

Sample Output 2

-2

Note that a shop must be open during at least one period, and the profit may be negative.

Sample Input 3

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

Sample Output 3

23


open Printf
open Scanf

let solve k a b =
  if a <= b && a >= k then 1
  else if a <= b then -1
  else let i = (k - b + a - b - 1) / (a - b) in max 1 (2 * i - 1)

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

Score : 100 points

Problem Statement

ButCoder Inc. runs a programming competition site called ButCoder. In this site, a user is given an integer value called rating that represents his/her skill, which changes each time he/she participates in a contest. The initial value of a new user's rating is 0, and a user whose rating reaches K or higher is called Kaiden ("total transmission"). Note that a user's rating may become negative.

Hikuhashi is a new user in ButCoder. It is estimated that, his rating increases by A in each of his odd-numbered contests (first, third, fifth, ...), and decreases by B in each of his even-numbered contests (second, fourth, sixth, ...).

According to this estimate, after how many contests will he become Kaiden for the first time, or will he never become Kaiden?

Constraints

1 ≤ K, A, B ≤ 10^{18}

All input values are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

If it is estimated that Hikuhashi will never become Kaiden, print -1. Otherwise, print the estimated number of contests before he become Kaiden for the first time.

Sample Input 1

4000 2000 500

Sample Output 1

5

Each time Hikuhashi participates in a contest, his rating is estimated to change as 0 → 2000 → 1500 → 3500 → 3000 → 5000 → … After his fifth contest, his rating will reach 4000 or higher for the first time.

Sample Input 2

4000 500 2000

Sample Output 2

-1

Each time Hikuhashi participates in a contest, his rating is estimated to change as 0 → 500 → -1500 → -1000 → -3000 → -2500 → … He will never become Kaiden.

Sample Input 3

1000000000000000000 2 1

Sample Output 3

1999999999999999997

The input and output values may not fit into 32-bit integers.


let () = Scanf.scanf "%d %d\n" @@ function
  | 1 -> fun q ->
      for i = 0 to q - 1 do
        Printf.printf "%d\n" @@ Scanf.scanf "%d %d\n" min
      done
  | n -> fun q ->
      let up v = (v - 1) / n in
      let rec upn v = function
        | 0 -> v
        | n -> upn (up v) (n - 1) in
      let rec depth acc = function
        | 0 -> acc
        | v -> depth (1 + acc) (up v) in
      let depth = depth 0 in
      let rec lca v w =
        if v = w then v
        else lca (up v) (up w) in
      let lca v w =
        let dv = depth v in
        let dw = depth w in
        if dv <= dw
        then lca v (upn w (dw - dv))
        else lca (upn v (dv - dw)) w in
      for i = 0 to q - 1 do
        Scanf.scanf "%d %d\n" @@ fun v w ->
          Printf.printf "%d\n" @@ succ @@ lca (v - 1) (w - 1)
      done

Score : 100 points

Problem Statement

You are given an integer N. Consider an infinite N-ary tree as shown below:

Figure: an infinite N-ary tree for the case N = 3

As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.

Regarding this tree, process Q queries. The i-th query is as follows:

Find the index of the lowest common ancestor (see Notes) of Vertex v_i and w_i.

Notes

In a rooted tree, the lowest common ancestor (LCA) of Vertex v and w is the farthest vertex from the root that is an ancestor of both Vertex v and w. Here, a vertex is considered to be an ancestor of itself. For example, in the tree shown in Problem Statement, the LCA of Vertex 5 and 7 is Vertex 2, the LCA of Vertex 8 and 11 is Vertex 1, and the LCA of Vertex 3 and 9 is Vertex 3.

Constraints

1 ≤ N ≤ 10^9

1 ≤ Q ≤ 10^5

1 ≤ v_i < w_i ≤ 10^9

Input

Input is given from Standard Input in the following format:

N Q
v_1 w_1
:
v_Q w_Q

Output

Print Q lines. The i-th line (1 ≤ i ≤ Q) must contain the index of the lowest common ancestor of Vertex v_i and w_i.

Sample Input 1

3 3
5 7
8 11
3 9

Sample Output 1

2
1
3

The queries in this case correspond to the examples shown in Notes.

Sample Input 2

100000 2
1 2
3 4

Sample Output 2

1
1


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

let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let wds = Array.init n @@ fun _ ->
    Scanf.scanf "%d %d\n" @@ fun w d -> w, d in
  Printf.printf "%d\n" @@ lower_bound 0 (1 lsl 61) @@ fun x ->
    ( <= ) k @@ Array.fold_right (fun (w, d) -> ( + ) @@
      if x < w then 0
      else 1 + (x - w) / d) wds 0

Score : 100 points

Problem Statement

In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, …, N. Also, we will call the position that is p centimeters from the west end of the flowerbed Position p.

You will plant Flower i (1 ≤ i ≤ N) as follows: first, plant one at Position w_i, then plant one every d_i centimeters endlessly toward the east. That is, Flower i will be planted at the positions w_i, w_i + d_i, w_i + 2 d_i, … Note that more than one flower may be planted at the same position.

Find the position at which the K-th flower from the west is planted. If more than one flower is planted at the same position, they are counted individually.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^9

1 ≤ w_i ≤ 10^{18}

1 ≤ d_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
w_1 d_1
:
w_N d_N

Output

When the K-th flower from the west is planted at Position X, print the value of X. (The westmost flower is counted as the 1-st flower.)

Sample Input 1

2 6
20 10
25 15

Sample Output 1

50

Two kinds of flowers are planted at the following positions:

Flower 1: Position 20, 30, 40, 50, 60, …

Flower 2: Position 25, 40, 55, 70, 85, …

The sixth flower from the west is the Flower 1 planted at Position 50. Note that the two flowers planted at Position 40 are counted individually.

Sample Input 2

3 9
10 10
10 10
10 10

Sample Output 2

30

Three flowers are planted at each of the positions 10, 20, 30, … Thus, the ninth flower from the west is planted at Position 30.

Sample Input 3

1 1000000000
1000000000000000000 1000000000

Sample Output 3

1999999999000000000


let s = read_line ()
let _ = print_endline @@ if Str.string_match (Str.regexp "^A?KIHA?BA?RA?$") s 0 then "YES" else "NO"

Score : 300 points

Problem Statement

You are given a string S.

Takahashi can insert the character A at any position in this string any number of times.

Can he change S into AKIHABARA?

Constraints

1 \leq |S| \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If it is possible to change S into AKIHABARA, print YES; otherwise, print NO.

Sample Input 1

KIHBR

Sample Output 1

YES

Insert one A at each of the four positions: the beginning, immediately after H, immediately after B and the end.

Sample Input 2

AKIBAHARA

Sample Output 2

NO

The correct spell is AKIHABARA.

Sample Input 3

AAKIAHBAARA

Sample Output 3

NO


Score : 100 points

Problem Statement

We call a 4-digit integer with three or more consecutive same digits, such as 1118, good.

You are given a 4-digit integer N. Answer the question: Is N good?

Constraints

1000 ≤ N ≤ 9999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is good, print Yes; otherwise, print No.

Sample Input 1

1118

Sample Output 1

Yes

N is good, since it contains three consecutive 1.

Sample Input 2

7777

Sample Output 2

Yes

An integer is also good when all the digits are the same.

Sample Input 3

1234

Sample Output 3

No


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

  let n_bonacci nn n =
    let rec fib_aux n res prevs =
      if n <= 0 then (prevs, 0) else
      if n = 1 then (prevs, res)
      else
        let tl = List.tl prevs in
        let sum = List.fold_left (+) 0 prevs in
        fib_aux (n-1) (res+sum) (tl @ [res])
    in
    let n = n-nn+1 in
    fib_aux n 1 [2]
  in
  let lucas = n_bonacci 1 in
  let _, ans = lucas n in

  Printf.printf "%d\n" ans

Score : 200 points

Problem Statement

It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers.

You are given an integer N. Find the N-th Lucas number.

Here, the i-th Lucas number L_i is defined as follows:

L_0=2

L_1=1

L_i=L_{i-1}+L_{i-2} (i≥2)

Constraints

1≤N≤86

It is guaranteed that the answer is less than 10^{18}.

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the N-th Lucas number.

Sample Input 1

5

Sample Output 1

11

L_0=2

L_1=1

L_2=L_0+L_1=3

L_3=L_1+L_2=4

L_4=L_2+L_3=7

L_5=L_3+L_4=11

Thus, the 5-th Lucas number is 11.

Sample Input 2

86

Sample Output 2

939587134549734843


let luca = let rec f a b n = if n = 0 then a else f b (a+b) (n-1) in f 2 1
let () = Scanf.scanf "%d" luca |> Printf.printf "%d\n"


let words = Str.split (Str.regexp " ")
let chars s = List.init (String.length s) (String.get s)
let (>>) f g x = g (f x)

let [a; b; c; d] = read_line () |> chars |> List.map (Char.escaped >> int_of_string)

let ans =
  let rec solve bits =
    let sign = List.init 3 (fun i -> if bits land (1 lsl i) <> 0 then 1 else -1) in
    let x =
      List.combine sign [b; c; d]
      |> List.fold_left (fun acc pair -> acc + fst pair * snd pair) a
    in
    if x = 7 then bits else solve (bits + 1)
  in solve 0

let () =
  print_int a;
  print_string (if ans land 1 <> 0 then "+" else "-");
  print_int b;
  print_string (if ans land 2 <> 0 then "+" else "-");
  print_int c;
  print_string (if ans land 4 <> 0 then "+" else "-");
  print_int d;
  print_string "=7";
  print_newline ()

Score : 300 points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits A, B, C and D in this order, each between 0 and 9 (inclusive).

In the formula A op1 B op2 C op3 D = 7, replace each of the symbols op1, op2 and op3 with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

0≤A,B,C,D≤9

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

ABCD

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

0 - 2 + 9 - 0 = 7 is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7


open Batteries
(* bitの数字の2真数の時の右からn番目の数字が0か1か *)
let is_bit_one bit n = if bit land (1 lsl n) = 0 then false else true

let int_to_list bit n =
  let rec get i =
    match i with
    | i when i = n -> []
    | _ -> if is_bit_one bit i then i :: get (i+1) else get (i+1)
  in get 0

(* 文字列をcharのlistにする *)
let explode s = List.init (String.length s) (String.get s)

let abcd = read_line () |> explode |> List.map Char.escaped |> List.map int_of_string

let rec eval nums ops =
  match nums with
  | [] -> 0
  | first :: rest ->
    match ops with
    | [] -> first
    | f :: r -> if f = "+" then first + eval rest r else first - eval rest r

let rec get_eval_text nums ops =
  match nums with
  | [] -> ""
  | first :: rest ->
    match ops with
    | [] -> string_of_int first
    | f :: r -> if f = "+" then string_of_int first ^ "+" ^ get_eval_text rest r else string_of_int first ^ "-" ^ get_eval_text rest r

let get_ops bit n =
  let rec get i =
    match i with
    | i when i = n -> []
    | _ -> if is_bit_one bit i then "+" :: get (i+1) else "-" :: get (i+1)
  in get 0

let rec ans bit =
  match bit with
  | bit when bit >= 3 * 3 -> ""
  | _ -> if eval abcd (get_ops bit 3) = 7 then get_eval_text abcd (get_ops bit 3) else ans (bit+1)

let _ = print_endline @@ (ans 0) ^ "=7"


module A = Array
module C = Char
module I = Int64
module L = List
module Q = Queue

let pf = Printf.printf
let sf = Scanf.scanf
let ssf = Scanf.sscanf

let read_int () = sf "%d " (fun x -> x)
let read_float () = sf "%f " (fun x -> x)
let read_str () = sf "%s " (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())
let err s = raise (Failure s)

let range s t = A.init (t - s) @@ (+) s
let foreach fold_f init s t map_f =
  range s t |> A.map map_f |> A.fold_left fold_f init

let inf = int_of_float 1e18
let eps = 1e-11

module S = struct
  include String
  let of_array a = String.init (A.length a) (A.get a)
  let to_array s = A.init (String.length s) (String.get s)
end;;

let rec search vals str sum goal =
  match vals with
  | [] ->
     if sum = goal
     then Some str
     else None
  | x :: xs ->
     (* case + *)
     let case_plus = search xs (str ^ "+" ^ string_of_int x) (sum + x) goal in
     ( match case_plus with
       | None -> search xs (str ^ "-" ^ string_of_int x) (sum - x) goal
       | _ -> case_plus )

let () =
  let s = read_str () in
  let vals = S.to_array s |> A.map int_of_char |> A.to_list in
  let vals = L.map (fun x -> x - int_of_char '0') vals in
  let head = L.hd vals in
  let tail = L.tl vals in
  let res = search tail (string_of_int head) head 7 in
  match res with
  | None -> ()
  | Some x -> pf "%s=7\n" x


Scanf.scanf "%d %d" (fun h w ->
    let c = Array.init 10 (fun _ ->
        Array.init 10 (fun _ -> Scanf.scanf " %d" (fun c -> c)))
    in
    let d = Array.make 10 0 in
    for i = 1 to h do
        for j = 1 to w do
            Scanf.scanf " %d" (fun a ->
                if a >= 0 then d.(a) <- d.(a) + 1
            )
        done
    done;
    for k = 0 to 9 do
        for i = 0 to 9 do
            for j = 0 to 9 do
                c.(i).(j) <- min c.(i).(j) (c.(i).(k) + c.(k).(j))
            done
        done
    done;
    let rec loop i acc =
        if i = 10 then acc else loop (i + 1) (acc + d.(i) * c.(i).(1))
    in
    loop 0 0 |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

Joisino the magical girl has decided to turn every single digit that exists on this world into 1.

Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).

She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).

You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:

If A_{i,j}≠-1, the square contains a digit A_{i,j}.

If A_{i,j}=-1, the square does not contain a digit.

Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.

Constraints

1≤H,W≤200

1≤c_{i,j}≤10^3 (i≠j)

c_{i,j}=0 (i=j)

-1≤A_{i,j}≤9

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}

Output

Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.

Sample Input 1

2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

Sample Output 1

12

To turn a single 8 into 1, it is optimal to first turn 8 into 4, then turn 4 into 9, and finally turn 9 into 1, costing 6 MP.

The wall contains two 8s, so the minimum total MP required is 6×2=12.

Sample Input 2

5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

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

Sample Output 3

47


let () =
  Scanf.scanf "%d %d" @@ fun h w ->

  let c = Array.init 10 (fun _ -> Array.init 10 (fun _ -> Scanf.scanf " %d" ((+) 0))) in
  for k = 0 to 9 do
    for i = 0 to 9 do
      for j = 0 to 9 do
        c.(i).(j) <- min c.(i).(j) (c.(i).(k) + c.(k).(j))
  done done done;

  Array.init (h*w) (fun _ -> Scanf.scanf " %d" ((+) 0))
  |> Array.fold_left (fun s e ->
      if e = -1 then s else s + c.(e).(1)) 0
  |> Printf.printf "%d\n"


let x, y = Scanf.scanf "%s %s" @@ fun a b -> a, b
let ans  = if x > y then ">" else if x = y then "=" else "<"
let () = print_endline ans

Score : 100 points

Problem Statement

In programming, hexadecimal notation is often used.

In hexadecimal notation, besides the ten digits 0, 1, ..., 9, the six letters A, B, C, D, E and F are used to represent the values 10, 11, 12, 13, 14 and 15, respectively.

In this problem, you are given two letters X and Y. Each X and Y is A, B, C, D, E or F.

When X and Y are seen as hexadecimal numbers, which is larger?

Constraints

Each X and Y is A, B, C, D, E or F.

Input

Input is given from Standard Input in the following format:

X Y

Output

If X is smaller, print <; if Y is smaller, print >; if they are equal, print =.

Sample Input 1

A B

Sample Output 1

<

10 < 11.

Sample Input 2

E C

Sample Output 2

>

14 > 12.

Sample Input 3

F F

Sample Output 3

=

15 = 15.


let () = Scanf.scanf "%x %x" @@ fun x y ->
  print_endline @@
  match compare x y with
  | -1 -> "<"
  | 0  -> "="
  | 1  -> ">"


Scanf.scanf "%d %d %d" (fun n z w ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let a1 = abs (w - a.(n - 1)) in
    let a2 = if n = 1 then a1 else abs (a.(n - 1) - a.(n - 2)) in
    Printf.printf "%d\n" @@ max a1 a2
)

Score : 500 points

Problem Statement

We have a deck consisting of N cards. Each card has an integer written on it. The integer on the i-th card from the top is a_i.

Two people X and Y will play a game using this deck. Initially, X has a card with Z written on it in his hand, and Y has a card with W written on it in his hand. Then, starting from X, they will alternately perform the following action:

Draw some number of cards from the top of the deck. Then, discard the card in his hand and keep the last drawn card instead. Here, at least one card must be drawn.

The game ends when there is no more card in the deck. The score of the game is the absolute difference of the integers written on the cards in the two players' hand.

X will play the game so that the score will be maximized, and Y will play the game so that the score will be minimized. What will be the score of the game?

Constraints

All input values are integers.

1 \leq N \leq 2000

1 \leq Z, W, a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N Z W
a_1 a_2 ... a_N

Output

Print the score.

Sample Input 1

3 100 100
10 1000 100

Sample Output 1

900

If X draws two cards first, Y will draw the last card, and the score will be |1000 - 100| = 900.

Sample Input 2

3 100 1000
10 100 100

Sample Output 2

900

If X draws all the cards first, the score will be |1000 - 100| = 900.

Sample Input 3

5 1 1
1 1 1 1 1

Sample Output 3

0

Sample Input 4

1 1 1
1000000000

Sample Output 4

999999999


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 () =
  let n, z, w = Scanf.scanf "%d %d %d\n" (fun n z w -> n, z, w) in
  let as_ = Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  let as' = Array.init (n + 2) (function 0 -> z | 1 -> w | i -> as_.(i - 2)) in
  let solve = memoize (n * n) (fun self (i, j) ->
    if j = n + 1 then abs (as'.(i) - as'.(j)), abs (as'.(i) - as'.(j))
    else
      Array.init (n - j + 1) (fun k -> self (j, 1 + k + j))
      |> Array.fold_left (fun (z, w) (x, y) -> (max z x, min w y)) (min_int, max_int)) in
  Printf.printf "%d\n" @@ fst @@ solve (0, 1)


let a = Scanf.scanf "%s %s %s" @@ fun a b c -> Array.of_list [a; b; c]
let b = Scanf.scanf "%s %s %s" @@ fun a b c -> Array.of_list [a; b; c]
let ans = if a.(0) = b.(2) && a.(1) = b.(1) && a.(2) = b.(0) then "YES" else "NO"
let () = print_endline ans

Score : 100 points

Problem Statement

You are given a grid with 2 rows and 3 columns of squares.
The color of the square at the i-th row and j-th column is represented by the character C_{ij}.

Write a program that prints YES if this grid remains the same when rotated 180 degrees, and prints NO otherwise.

Constraints

C_{i,j}(1 \leq i \leq 2, 1 \leq j \leq 3) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

C_{11}C_{12}C_{13}
C_{21}C_{22}C_{23}

Output

Print YES if this grid remains the same when rotated 180 degrees; print NO otherwise.

Sample Input 1

pot
top

Sample Output 1

YES

This grid remains the same when rotated 180 degrees.

Sample Input 2

tab
bet

Sample Output 2

NO

This grid does not remain the same when rotated 180 degrees.

Sample Input 3

eye
eel

Sample Output 3

NO


let string_rev s =
  let len = String.length s in
  String.init len (fun i -> s.[len - 1 - i]);;
let str_eq s1 s2 = s1=s2;;
let f s1 s2 = if s1=(string_rev s2) then "YES" else "NO";;
let () = Scanf.scanf "%s %s" f |> Printf.printf "%s\n"


(* Vicfred
 * https://atcoder.jp/contests/abc077/tasks/abc077_b
 * implementation, math
 * *)
Scanf.scanf "%f\n" (fun x -> x)
|> sqrt
|> int_of_float
|> (fun x -> x * x)
|> Printf.printf "%d\n"

Score : 200 points

Problem Statement

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

Constraints

1 \leq N \leq 10^9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the largest square number not exceeding N.

Sample Input 1

10

Sample Output 1

9

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

Sample Input 2

81

Sample Output 2

81

Sample Input 3

271828182

Sample Output 3

271821169


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


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

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

let n = scan "%d" id
let a = scan_array ~sep: ' ' Int.of_string
let b = scan_array ~sep: ' ' Int.of_string
let c = scan_array ~sep: ' ' Int.of_string

let () =
  Array.sort Int.compare a;
  Array.sort Int.compare b;
  Array.sort Int.compare c;
  ArrayL.map b ~f:(fun v ->
      let i = lower_bound (Array.length a) (fun i -> v <= a.(i)) in
      let j = lower_bound (Array.length c) (fun i -> v <= c.(i)) in
      i * (Array.length c - j))
  |> Array.sum
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 \leq N \leq 10^5

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

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

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of different altars that Ringo can build.

Sample Input 1

2
1 5
2 4
3 6

Sample Output 1

3

The following three altars can be built:

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

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

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

Sample Input 2

3
1 1 1
2 2 2
3 3 3

Sample Output 2

27

Sample Input 3

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

Sample Output 3

87


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

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

let id = identity

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

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

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

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

let scan_array cnv = Array.of_list @@ scan_list cnv

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

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

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

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

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

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


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

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

let id = identity

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

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

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

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

let scan_array cnv = Array.of_list @@ scan_list cnv

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

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

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

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

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

let () =
  Array.sort Int.compare a;
  Array.sort Int.compare b;
  Array.sort Int.compare c;
  let lena = Array.length a in
  let lenb = Array.length b in
  let lenc = Array.length c in
  ListL.map (0 ++^ lena) ~f:(fun i ->
      match match Array.bsearch Int.ord b a.(i) with
        | `At i | `Just_after i -> Some (succ i)
        | `All_bigger -> Some 0
        | _ -> None
      with
      | Some i ->
        ListL.map (i ++^ lenb) ~f:(fun j ->
            match Array.bsearch Int.ord c b.(j) with
            | `At i | `Just_after i ->
              lenc - i - 1
            | `All_bigger -> lenc
            | _ -> 0)
        |> List.sum
      | None -> 0
    )
  |> List.sum
  |> Printf.printf "%d\n"


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

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

let id = identity

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

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

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

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

let scan_array cnv = Array.of_list @@ scan_list cnv

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

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

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

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

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

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


open Scanf
let id x = x
let read_int _ = scanf " %d" id
let () =
  let n = scanf " %d" id in
  let a = Array.init n read_int in
  let b = Array.init n read_int in
  let c = Array.init n read_int in
  Array.sort (-) a; Array.sort (-) b; Array.sort (-) c;
  let f u v =
    let res = Array.make n 0 in
    let rec g a i =
      if i >= n then ()
      else if a = n then (
        res.(i) <- n; g n (i+1)
      ) else if v.(i) <= u.(a) then (
        res.(i) <- a; g a (i+1)
      ) else g (a+1) i in
    g 0 0; res in
  let ab = f a b in
  let bc = f b c in
  Array.iteri (fun i e -> if i > 0 then ab.(i) <- e + ab.(i-1)) ab;
  Array.map (fun e -> if e = 0 then 0 else ab.(e-1)) bc
  |> Array.fold_left (+) 0 |> Printf.printf "%d\n"


Scanf.scanf "%d" (fun n ->
    let a = Array.init (n + 1) (fun i -> if i = n then max_int else Scanf.scanf " %d" (fun a -> a)) in
    let b = Array.init n (fun _ -> Scanf.scanf " %d" (fun b -> b)) in
    let c = Array.init (n + 1) (fun i -> if i = n then max_int else Scanf.scanf " %d" (fun c -> c)) in
    Array.sort compare a;
    Array.sort compare b;
    Array.sort compare c;
    let lower arr target =
        let rec bin left right =
            if left = right then left else
                let m = (left + right) / 2 in
                if arr.(m) < target then bin (m + 1) right
                                    else bin left m
        in
        bin 0 n
    in
    let rec loop i acc =
        if i = n then acc else
            let acc = acc + lower a b.(i) * (n - lower c (b.(i) + 1)) in
            loop (i + 1) acc
    in
    loop 0 0 |> Printf.printf "%d\n"
)


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

let rec add = ( + )

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

let rec sub = ( - )

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

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

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

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

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

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

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

let upper_bound_obligation_1 p_dec n =
  let s = p_dec (succ n) in if s then false else true

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

let upper_bound p_dec =
  lower_bound (upper_bound_obligation_1 p_dec)

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

let upper_bound p_dec =
  lower_bound (upper_bound_obligation_1 p_dec)

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  let bs = Array.init n (fun _ -> Scanf.scanf "%d " (fun b -> b)) in
  let cs = Array.init n (fun _ -> Scanf.scanf "%d " (fun c -> c)) in
  Array.sort compare as_;
  Array.sort compare bs;
  Array.sort compare cs;
  let cbs = Array.map (fun c -> lower_bound (fun j -> try c < bs.(j) with _ -> true) 0 n) cs in
  let bas = Array.map (fun b -> lower_bound (fun i -> try b < as_.(i) with _ -> true) 0 n) bs in
  let sum_ba = Array.make n 0 in
  sum_ba.(0) <- bas.(0);
  for i = 1 to n - 1 do
    sum_ba.(i) <- bas.(i) - bas.(i - 1) + sum_ba.(i - 1)
  done;
  let sum_cb = Array.make n 0 in
  for i = 0 to cbs.(0) - 1 do
    sum_cb.(0) <- sum_ba.(i) + sum_cb.(0)
  done;
  for i = 1 to n - 1 do
    for j = cbs.(i - 1) to cbs.(i) - 1 do
      sum_cb.(i) <- sum_ba.(j) + sum_cb.(i)
    done;
    sum_cb.(i) <- sum_cb.(i - 1) + sum_cb.(i)
  done;
  for i = 1 to n - 1 do
    sum_cb.(i) <- sum_cb.(i - 1) + sum_cb.(i);
  done;
  Printf.printf "%d\n" sum_cb.(n - 1)


Scanf.scanf "%d %d" (fun r g ->
    Printf.printf "%d\n" @@ g * 2 - r
)

Score : 100 points

Problem Statement

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

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

Let the current rating of the user be a.

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

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

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

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

Find the performance required to achieve it.

Constraints

0 \leq R, G \leq 4500

All input values are integers.

Input

Input is given from Standard Input in the following format:

R
G

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is 2002.

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

Sample Input 2

4500
0

Sample Output 2

-4500

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


let r = read_int ()
let g = read_int ()
let () = print_int (g * 2 - r)


Scanf.scanf "%d %d" @@ fun r g -> Printf.printf "%d\n" @@ 2 * g - r


let n = read_int ()
let k, ans = read_int (), ref max_int
let _ = for i = 0 to n do let x = ref 1 in for j = 1 to i do x := !x * 2 done; x := !x + (n - i) * k; ans := min !ans !x done; Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

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

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by K.

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

Constraints

1 \leq N, K \leq 10

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
K

Output

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

Sample Input 1

4
3

Sample Output 1

10

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

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

Sample Input 2

10
10

Sample Output 2

76

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

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

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


Scanf.scanf" %d %d"@@fun n k->
let rec f v = function
| 0 -> v
| i -> min (f (v*2) (i-1)) (f (v+k) (i-1))
in f 1 n |> print_int


let rec foldn n f v = if n = 0 then v else foldn (n-1) f (f v)
let () =
  let n, k = Scanf.scanf "%d %d" (fun n k -> n, k) in
  foldn n (fun a -> min (2*a) (a+k)) 1 |> Printf.printf "%d\n"


let s = read_line ()
let _ = print_endline @@ try Str.search_forward (Str.regexp "AC") s 0 |> ignore; "Yes" with _ -> "No"

Score : 100 points

Problem Statement

Snuke built an online judge to hold a programming contest.

When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring.
(The judge can return any two-character substring of S.)

Determine whether the judge can return the string AC as the verdict to a program.

Constraints

2 \leq |S| \leq 5

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If the judge can return the string AC as a verdict to a program, print Yes; if it cannot, print No.

Sample Input 1

BACD

Sample Output 1

Yes

The string AC appears in BACD as a contiguous substring (the second and third characters).

Sample Input 2

ABCD

Sample Output 2

No

Although the string ABCD contains both A and C (the first and third characters), the string AC does not appear in ABCD as a contiguous substring.

Sample Input 3

CABD

Sample Output 3

No

Sample Input 4

ACACA

Sample Output 4

Yes

Sample Input 5

XX

Sample Output 5

No


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let t, o = Array.fold_left (fun (t, o) a -> t * 3, o * if a mod 2 = 0 then 2 else 1) (1, 1) a_s
let _ = Printf.printf "%d\n" @@ t - o

Score : 200 points

Problem Statement

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

In particular, any integer sequence is similar to itself.

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

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

Constraints

1 \leq N \leq 10

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the number of integer sequences that satisfy the condition.

Sample Input 1

2
2 3

Sample Output 1

7

There are seven integer sequences that satisfy the condition:

1, 2

1, 4

2, 2

2, 3

2, 4

3, 2

3, 4

Sample Input 2

3
3 3 3

Sample Output 2

26

Sample Input 3

1
100

Sample Output 3

1

Sample Input 4

10
90 52 56 71 44 8 13 30 57 84

Sample Output 4

58921


open Scanf
open Printf

let () = sscanf (read_line ()) "%d %d %d" (fun a b c ->
  if a = b then c
  else if a = c then b
  else a
  )
  |> printf "%d\n"

Score : 100 points

Problem Statement

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

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

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

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

Constraints

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

A, B and C are integers.

The input satisfies the condition in the statement.

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

5 7 5

Sample Output 1

7

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

Sample Input 2

1 1 7

Sample Output 2

7

In this case, C is the one we seek.

Sample Input 3

-100 100 100

Sample Output 3

-100


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

let ans = if a = b then c
  else if a = c then b
    else a

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


Scanf.scanf "%d %d" (fun n k ->
    let xy = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
    let x, y = Array.fold_left (fun (xl, yl) (x, y) -> x :: xl, y :: yl) ([], []) xy in
    let x = Array.of_list x in
    let y = Array.of_list y in
    Array.sort compare x;
    Array.sort compare y;
    let rec loop1 i1 acc =
        let rec loop2 i2 x1 acc =
            let rec loop3 i3 x2 acc =
                let rec loop4 i4 y1 acc =
                    let count y2 =
                        Array.fold_left (fun acc (x, y) -> if x >= x1 && x <= x2 && y >= y1 && y <= y2 then acc + 1 else acc) 0 xy
                    in
                    if i4 >= n then acc else
                        let kk = count y.(i4) in
                        let acc = if kk >= k then min acc ((x2 - x1) * (y.(i4) - y1)) else acc  in
                        loop4 (i4 + 1) y1 acc
                in
                if i3 >= n - 1 then acc else loop3 (i3 + 1) x2 (loop4 (i3 + 1) y.(i3) acc)
            in
            if i2 >= n then acc else loop2 (i2 + 1) x1 (loop3 0 x.(i2) acc)
        in
        if i1 >= n - 1 then acc else loop1 (i1 + 1) (loop2 (i1 + 1) x.(i1) acc)
    in
    loop1 0 max_int |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

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

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

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

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

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

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

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

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

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

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

Sample Output 3

3999999996000000001

Watch out for integer overflows.


let inf = max_int
let rec for_fold a b f v = if a >= b then v else for_fold (a+1) b f (f v a)
let for_fold_min a b f = for_fold a b (fun x y -> min x (f y)) inf

let () =
  Scanf.scanf "%d %d" @@ fun n k ->
  let c = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
  Array.sort compare c;

  let xs = Array.map fst c in Array.sort (-) xs;
  let ys = Array.map snd c in Array.sort (-) ys;

  for_fold_min 0 n (fun i ->
    let ly = ys.(i) in
    for_fold_min i n (fun j ->
      let uy = ys.(j) in
      for_fold_min 0 n (fun h ->
        let lx = xs.(h) in

        let m, ux = Array.fold_left (fun (s, tx) (x, y) ->
          if ly <= y && y <= uy && lx <= x then
            (s+1, if s < k then x else tx)
          else
            (s, tx)) (0, -1) c
        in

        if m >= k then
          ((ux-lx)*(uy-ly))
        else
          inf)))
  |> Printf.printf "%d\n"


open Printf
open Scanf

let () =
  let s = scanf "%s " (fun x -> x) in
  let ls = String.length s in
  String.sub s 0 (ls - 8) |> printf "%s\n"

Score : 100 points

Problem Statement

Rng is going to a festival.

The name of the festival is given to you as a string S, which ends with FESTIVAL, from input. Answer the question: "Rng is going to a festival of what?" Output the answer.

Here, assume that the name of "a festival of s" is a string obtained by appending FESTIVAL to the end of s.
For example, CODEFESTIVAL is a festival of CODE.

Constraints

9 \leq |S| \leq 50

S consists of uppercase English letters.

S ends with FESTIVAL.

Input

Input is given from Standard Input in the following format:

S

Output

Print the answer to the question: "Rng is going to a festival of what?"

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE

This is the same as the example in the statement.

Sample Input 2

CODEFESTIVALFESTIVAL

Sample Output 2

CODEFESTIVAL

This string is obtained by appending FESTIVAL to the end of CODEFESTIVAL, so it is a festival of CODEFESTIVAL.

Sample Input 3

YAKINIKUFESTIVAL

Sample Output 3

YAKINIKU


let () =
  let s = read_line () in
  let ss = try String.sub s 0 4 with _ -> "" in
  (if ss = "YAKI" then "Yes" else "No") |> print_endline

Score : 100 points

Problem Statement

Ringo is giving a present to Snuke.

Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with YAKI in Japanese, and does not like other things.

You are given a string S representing the Japanese name of Ringo's present to Snuke. Determine whether S starts with YAKI.

Constraints

1 \leq |S| \leq 10

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S starts with YAKI, print Yes; otherwise, print No.

Sample Input 1

YAKINIKU

Sample Output 1

Yes

YAKINIKU starts with YAKI.

Sample Input 2

TAKOYAKI

Sample Output 2

No

TAKOYAKI (a Japanese snack. tako: octopus) does not start with YAKI.

Sample Input 3

YAK

Sample Output 3

No


open Printf
open Scanf

let () =
  let n2 = scanf "%d " (fun x -> x * x) in
  let a = scanf "%d " (fun x -> x) in
  printf "%d\n" (n2 - a)

Score : 100 points

Problem Statement

We have an N \times N square grid.

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

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

Constraints

1 \leq N \leq 100

0 \leq A \leq N^2

Inputs

Input is given from Standard Input in the following format:

N
A

Outputs

Print the number of squares that will be painted black.

Sample Input 1

3
4

Sample Output 1

5

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

Sample Input 2

19
100

Sample Output 2

261

Sample Input 3

10
0

Sample Output 3

100

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


open Printf
open Scanf

module L =
  struct
    include List

    let rec unfold f x =
      match f x with
        None -> []
      | Some (a, b) -> a :: unfold f b
  end

let () =
  let n = scanf "%d " (fun x -> x) in
  let k = scanf "%d " (fun x -> x) in
  let xs = L.unfold (fun b -> if b = 0 then None else let v = scanf "%d " (fun x -> x) in Some (v,b-1)) n in
  L.fold_left (fun s x -> s + 2 * (min x (k-x))) 0 xs |> printf "%d\n"

Score : 200 points

Problem Statement

There are N balls in the xy-plane. The coordinates of the i-th of them is (x_i, i).
Thus, we have one ball on each of the N lines y = 1, y = 2, ..., y = N.

In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B.
Then, he placed the i-th type-A robot at coordinates (0, i), and the i-th type-B robot at coordinates (K, i).
Thus, now we have one type-A robot and one type-B robot on each of the N lines y = 1, y = 2, ..., y = N.

When activated, each type of robot will operate as follows.

When a type-A robot is activated at coordinates (0, a), it will move to the position of the ball on the line y = a, collect the ball, move back to its original position (0, a) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

When a type-B robot is activated at coordinates (K, b), it will move to the position of the ball on the line y = b, collect the ball, move back to its original position (K, b) and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

Snuke will activate some of the 2N robots to collect all of the balls. Find the minimum possible total distance covered by robots.

Constraints

1 \leq N \leq 100

1 \leq K \leq 100

0 < x_i < K

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
K
x_1 x_2 ... x_N

Outputs

Print the minimum possible total distance covered by robots.

Sample Input 1

1
10
2

Sample Output 1

4

There are just one ball, one type-A robot and one type-B robot.

If the type-A robot is used to collect the ball, the distance from the robot to the ball is 2, and the distance from the ball to the original position of the robot is also 2, for a total distance of 4.

Similarly, if the type-B robot is used, the total distance covered will be 16.

Thus, the total distance covered will be minimized when the type-A robot is used. The output should be 4.

Sample Input 2

2
9
3 6

Sample Output 2

12

The total distance covered will be minimized when the first ball is collected by the type-A robot, and the second ball by the type-B robot.

Sample Input 3

5
20
11 12 9 17 12

Sample Output 3

74


let f s =
 let rec fiter ss =
  if String.length s=0
   then false
   else
    (if ss.[0]=='9'
     then true
     else fiter (String.sub ss 1 (String.length ss-1))) in fiter s;;
let () = Scanf.scanf "%s"
f
|> (fun a -> if a then "Yes" else "No")
|> Printf.printf "%s\n"

Score : 100 points

Problem Statement

It is September 9 in Japan now.

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

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


module CoordComp
  (* 座標の型 *)
  (Coord : sig
    type t
    val compare : t -> t -> int
  end) :
sig
  val compress :
    (* 座標のリスト *)
    Coord.t list ->
    (* 座標の数，圧縮する関数と解凍する関数を返す *)
    int * (Coord.t -> int) * (int -> Coord.t)
end = struct
  module IntMap = Map.Make (struct
    type t = int
    let compare = compare
  end)
  module CoordMap = Map.Make (Coord)

  let compress cs =
    let (n, comp, decomp) =
      List.fold_left (fun (n, comp, decomp) c ->
        if CoordMap.mem c comp then (n, comp, decomp)
        else (n + 1, CoordMap.add c n comp, IntMap.add n c decomp))
      (0, CoordMap.empty, IntMap.empty) cs in
    (n, (fun c -> CoordMap.find c comp), (fun n -> IntMap.find n decomp))
end

module WeightedDirectedGraph
  (Vertex : sig
    type t
    val compare : t -> t -> int
  end)
  (Weight : sig
    type t
    val zero : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  (* 配列版の実装 *)
  val raw_warshall_floyd :
    (* 頂点の数n *)
    int ->
    (* 辺のリスト *)
    (* 頂点は0からn-1まで整数でなくてはならない *)
    (int * int * Weight.t) list ->
    (* 辿り着けなければNoneを返す *)
    (int -> int -> Weight.t option)

  (* 座標圧縮により，頂点に様々な型を使えるようにしたバージョン *)
  val warshall_floyd :
    (* 辺のリスト *)
    (Vertex.t * Vertex.t * Weight.t) list ->
    (* 辿り着けなければNoneを返す *)
    (Vertex.t -> Vertex.t -> Weight.t option)
end =
struct
  module CC = CoordComp (Vertex)

  let raw_warshall_floyd n es =
    (* 準備 *)
    (* Noneで無限を表す *)
    let d = Array.make_matrix n n None in
    List.iter (fun (u, v, c) -> d.(u).(v) <- Some c) es;
    for v = 0 to n - 1 do
      d.(v).(v) <- Some Weight.zero
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
        for k = 0 to n - 1 do
          (* d.(j).(k) <- min d.(j).(k) (d.(j).(i) + d.(i).(k)) *)
          let open Weight in
          match d.(j).(k), d.(j).(i), d.(i).(k) with
          | _, None, _ -> ()
          | _, _, None -> ()
          (* d.(j).(k) <= d.(j).(i) + d.(i).(k) *)
          | Some djk, Some dji, Some dik when compare djk (dji + dik) <= 0 -> ()
          | _, Some dji, Some dik -> d.(j).(k) <- Some (dji + dik)
        done
      done
    done;
    fun u v ->
      if u < 0 || n <= u || v < 0 || n <= v
      then None
      else d.(u).(v)

  let warshall_floyd es =
    let (n, comp, _) =
      CC.compress @@
        List.concat @@
          List.map (fun (u, v, _) -> [u; v]) es in
    let d =
      raw_warshall_floyd n @@
        List.map (fun (u, v, c) -> (comp u, comp v, c)) es in
    fun u v ->
      try d (comp u) (comp v) with Not_found -> None
end

module Int = struct
  type t = int
  let zero = 0
  let ( + ) = ( + )
  let compare = compare
end

module G = WeightedDirectedGraph (Int) (Int)

let rec select acc trace = function
  | [] -> acc
  | x :: xs -> select ((trace, x, xs) :: acc) (x :: trace) xs
let select xs = select [] [] xs

let rec permutation = function
  | [] -> [[]]
  | xs ->
      List.concat @@ List.map (fun (xs, x, ys) -> List.map (fun xs -> x :: xs) (permutation (List.rev_append xs ys)))
      (select xs)

let () =
  let n, m, r = Scanf.scanf "%d %d %d\n" (fun n m r -> n, m, r) in
  let rs = Array.to_list @@ Array.init r (fun _ -> Scanf.scanf "%d " (fun r -> r - 1)) in
  let abcs = Array.to_list @@ Array.init m (fun _ -> Scanf.scanf "%d %d %d\n" (fun a b c -> a - 1, b - 1, c)) in
  let d =
    G.warshall_floyd @@
      List.rev_append (List.rev_map (fun (a, b, c) -> (b, a, c)) abcs) abcs in
  permutation rs
  |> List.map (fun (r :: rs) ->
      List.fold_left (fun (r, a) s -> (s, (r, s) :: a)) (r, []) rs
      |> snd
      |> List.map (fun (r, s) ->
          match d r s with
          | None -> max_int
          | Some d -> d)
      |> List.fold_left ( + ) 0)
  |> List.fold_left min max_int
  |> Printf.printf "%d\n"


Scanf.scanf "%d %d %d" (fun n m r ->
    let next_permutation list =
        let rec phase3 taddr = function
            | _  :: tl when tl == taddr -> []
            | hd :: tl                  -> hd :: phase3 taddr tl
            | []                        -> [] in

        let rec phase2 h2 taddr = function
            | h1 :: tl when h1 > h2 -> let lis = phase3 taddr tl in
                                       h1, h2 :: lis
            | h1 :: tl              -> let hh, lis = phase2 h2 taddr tl in
                                       hh, h1 :: lis
            | _                     -> failwith "??" in

        let rec phase1 list = function
            | h1 :: h2 :: tl when h1 > h2  -> let hh, lis = phase2 h2   tl list in
                                              List.rev_append tl (hh :: lis)
            | _  :: tl                     -> phase1 list tl
            | _                            -> list in

        let rev_list = List.rev list in
        phase1 rev_list rev_list
    in
    let ri = Array.init r (fun _ -> Scanf.scanf " %d" (fun r -> r - 1)) in
    let nei = Array.make n [] in
    for i = 1 to m do
        Scanf.scanf " %d %d %d" (fun a b c ->
            let a = a - 1 in
            let b = b - 1 in
            nei.(a) <- (c, b) :: nei.(a);
            nei.(b) <- (c, a) :: nei.(b);
        )
    done;
    let module S = Set.Make (struct type t = int * int let compare = compare end) in
    let dijkstra s g =
        let d = Array.make n max_int in
        d.(s) <- 0;
        let rec loop set =
            if S.is_empty set then () else
                let ((dd, cur) as m) = S.min_elt set in
                let set = S.remove m set in
                let set = List.fold_left (fun set (nc, nv) ->
                    if d.(nv) <= nc + dd then set else (
                        d.(nv) <- nc + dd;
                        S.add (nc + dd, nv) set
                    )
                ) set nei.(cur)
                in
                loop set
        in
        loop (S.singleton (0, s));
        d.(g)
    in
    let dist = Array.make_matrix r r max_int in
    for i = 0 to r - 1 do
        dist.(i).(i) <- 0;
        for j = i + 1 to r - 1 do
            let c = dijkstra ri.(i) ri.(j) in
            dist.(i).(j) <- c;
            dist.(j).(i) <- c;
        done
    done;
    let rec iota a = if a < 0 then [] else a :: iota (a - 1) in
    let rec fact a = if a = 0 then 1  else a *  fact (a - 1) in

    let calc l =
        match l with
        | [] -> 0
        | hd :: tl ->
                let rec loop prev sum = function
                    | [] -> sum
                    | x :: xs -> loop x (sum + dist.(prev).(x)) xs
                in
                loop hd 0 tl
    in

    let rec loop i lis acc =
        if i = 0 then acc else
            loop (i - 1) (next_permutation lis) (min acc (calc lis))
    in
    loop (fact r) (iota (r - 1)) max_int |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

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

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

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

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

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

Constraints

2≤N≤200

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

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

r_i≠r_j (i≠j)

1≤A_i,B_i≤N, A_i≠B_i

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

1≤C_i≤100000

Every town can be reached from every town by road.

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

2

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

Sample Input 2

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

Sample Output 2

4

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

Sample Input 3

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

Sample Output 3

3


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val warshall_floyd :
    (* 頂点の数n *)
    int ->
    (* 辺のリスト *)
    (* 頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 辿り着けなければinf，負閉路を含む経路があればneg_infを返す関数 *)
    (int -> int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let warshall_floyd n es =
    let d = Array.make_matrix n n Weight.inf in
    for v = 0 to n - 1 do
      d.(v).(v) <- Weight.zero
    done;
    es.fold (fun (u, v, c) () ->
      (* c < d.(u).(v) *)
      if 0 < Weight.compare d.(u).(v) c
      then d.(u).(v) <- c) ();
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
        for k = 0 to n - 1 do
          let open Weight in
          if
            (* 経路がない場合は更新しない *)
            0 < Weight.compare inf d.(j).(i)
            && 0 < Weight.compare inf d.(i).(k)
            (* d.(j).(i) + d.(i).(k) < d.(j).(k) *)
            && 0 < Weight.compare d.(j).(k) (d.(j).(i) + d.(i).(k))
          then d.(j).(k) <- d.(j).(i) + d.(i).(k)
        done
      done
    done;
    for i = 0 to n - 1 do
      (* 頂点iを通る負閉路がある *)
      if 0 < Weight.compare Weight.zero d.(i).(i) then
        for j = 0 to n - 1 do
          for k = 0 to n - 1 do
            (* 負閉路を通る経路があれば，最短距離を負の無限大で更新 *)
            let open Weight in
            if 0 < Weight.compare inf d.(j).(i) && 0 < Weight.compare inf d.(i).(k)
            then d.(j).(k) <- Weight.neg_inf
          done
        done
    done;
    fun u v -> try d.(u).(v) with _ -> Weight.inf
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let ( + ) = ( + )
  let inf = max_int
  let neg_inf = min_int
  let compare = compare
end)

let rec perm acc zs ys n xs =
  match n, xs with
  | 0, _ -> zs :: acc
  | _, [] -> acc
  | n, x :: xs -> perm (perm acc (x :: zs) [] (n - 1) (List.rev_append ys xs)) zs (x :: ys) n xs
let perm n = perm [] [] [] n

let () = Scanf.scanf "%d %d %d\n" @@ fun n m r ->
  let rs = Array.init r @@ fun _ -> Scanf.scanf "%d " pred in
  let abcs = Array.init m @@ fun _ -> Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c in
  let d = G.warshall_floyd n { G.fold = fun f -> Array.fold_right (fun ((a, b, c) as e) acc -> f (b, a, c) @@ f e acc) abcs } in
  Printf.printf "%d\n" @@
  List.fold_left (fun acc (r :: rs) ->
    min acc @@
    snd @@
    List.fold_left (fun (r, a) s -> (s, d r s + a)) (r, 0) rs) max_int @@
  perm r @@
  Array.to_list rs


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val warshall_floyd :
    (* 頂点の数n *)
    int ->
    (* 辺のリスト *)
    (* 頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 辿り着けなければinf，負閉路を含む経路があればneg_infを返す関数 *)
    (int -> int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let warshall_floyd n es =
    let d = Array.make_matrix n n Weight.inf in
    for v = 0 to n - 1 do
      d.(v).(v) <- Weight.zero
    done;
    es.fold (fun (u, v, c) () ->
      (* c < d.(u).(v) *)
      if 0 < Weight.compare d.(u).(v) c
      then d.(u).(v) <- c) ();
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
        for k = 0 to n - 1 do
          let open Weight in
          if
            (* 経路がない場合は更新しない *)
            0 < Weight.compare inf d.(j).(i)
            && 0 < Weight.compare inf d.(i).(k)
            (* d.(j).(i) + d.(i).(k) < d.(j).(k) *)
            && 0 < Weight.compare d.(j).(k) (d.(j).(i) + d.(i).(k))
          then d.(j).(k) <- d.(j).(i) + d.(i).(k)
        done
      done
    done;
    for i = 0 to n - 1 do
      (* 頂点iを通る負閉路がある *)
      if 0 < Weight.compare Weight.zero d.(i).(i) then
        for j = 0 to n - 1 do
          for k = 0 to n - 1 do
            (* 負閉路を通る経路があれば，最短距離を負の無限大で更新 *)
            let open Weight in
            if 0 < Weight.compare inf d.(j).(i) && 0 < Weight.compare inf d.(i).(k)
            then d.(j).(k) <- Weight.neg_inf
          done
        done
    done;
    fun u v -> try d.(u).(v) with _ -> Weight.inf
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let ( + ) = ( + )
  let inf = max_int
  let neg_inf = min_int
  let compare = compare
end)

let perm k xs =
  let rec perm_aux trace n k i xs ys acc =
    match k, i, xs with
    | 0, _, _ -> trace :: acc
    | _, 0, _ -> acc
    | _, _, [] -> perm_aux trace n k i (List.rev ys) [] acc
    | _, _, x :: xs ->
        perm_aux trace n k (i - 1) xs (x :: ys) @@
        perm_aux (x :: trace) (n - 1) (k - 1) (n - 1) xs ys acc in
  let n = List.length xs in
  perm_aux [] n k n xs [] []

let () = Scanf.scanf "%d %d %d\n" @@ fun n m r ->
  let rs = Array.init r @@ fun _ -> Scanf.scanf "%d " pred in
  let abcs = Array.init m @@ fun _ -> Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c in
  let d = G.warshall_floyd n { G.fold = fun f -> Array.fold_right (fun ((a, b, c) as e) acc -> f (b, a, c) @@ f e acc) abcs } in
  Printf.printf "%d\n" @@
  List.fold_left (fun acc (r :: rs) ->
    min acc @@
    snd @@
    List.fold_left (fun (r, a) s -> (s, d r s + a)) (r, 0) rs) max_int @@
  perm r @@
  Array.to_list rs


open Scanf
open Printf

let flip f x y = f y x

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

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

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

let rec pow2 n = if n <= 0 then 1 else 2 * pow2 (n-1)

let inf = 202020202020

let () =
  let [|n; m; r|] = read_ints 3 in
  let rs = read_ints r |> Array.map (fun x -> x - 1) in
  let graph = Array.init n @@ fun _ -> Array.make n inf in
  for_iter_ 0 m (fun _ ->
    let [|a; b; c|] = read_ints 3 in
    graph.(a-1).(b-1) <- c;
    graph.(b-1).(a-1) <- c);

  for_iter_ 0 n (fun i -> graph.(i).(i) <- 0);
  for_iter_ 0 n (fun l -> for_iter_ 0 n @@ fun j -> for_iter_ 0 n @@ fun k ->
    graph.(j).(k) <- min graph.(j).(k) @@ graph.(j).(l) + graph.(l).(k));

  let rgraph = Array.init r @@ fun _ -> Array.make r inf in
  for_iter_ 0 r (fun j ->
    for_iter_ 0 r (fun k -> rgraph.(j).(k) <- graph.(rs.(j)).(rs.(k))));

  let lim = pow2 r in
  let memo = Array.init r @@ fun _ -> Array.make lim inf in
  for_iter_ 0 r (fun j -> memo.(j).(pow2 j) <- 0);

  for_iter_ 0 lim (fun n ->
    for_iter_ 0 r (fun j ->
      if n land pow2 j > 0 then
        let n' = n lxor pow2 j in
        for_iter_ 0 r (fun k ->
          let b = pow2 k in
          if n' land b > 0 then
            memo.(j).(n) <- min memo.(j).(n) (memo.(k).(n') + rgraph.(k).(j)))));

  for_iter 0 r (fun i -> memo.(i).(lim - 1))
  |> List.fold_left min inf
  |> printf "%d\n"


let () = Scanf.scanf "%d %d\n" @@ fun x t ->
  Printf.printf "%d\n" @@ max 0 (x - t)

Score : 100 points

Problem Statement

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

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

Constraints

1≤X≤10^9

1≤t≤10^9

X and t are integers.

Input

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

X t

Output

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

Sample Input 1

100 17

Sample Output 1

83

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

Sample Input 2

48 58

Sample Output 2

0

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

Sample Input 3

1000000000 1000000000

Sample Output 3

0


let a = Scanf.scanf "%d " (fun x -> x) in
    let b = Scanf.scanf "%d\n" (fun x -> x ) in
        let c = a - b in
            if (c > 0) then
                Printf.printf "%d\n" c
            else
                Printf.printf "0\n";;


(* O(|s|) *)
let solve s =
  let n = String.length s in
  let rec loop i =
      if i < n then
        (print_char s.[i];
        loop (i + 2))
  in
    loop 0

let _ = read_line () |> solve

Score : 200 points

Problem Statement

You are given a string s consisting of lowercase English letters. Extract all the characters in the odd-indexed positions and print the string obtained by concatenating them. Here, the leftmost character is assigned the index 1.

Constraints

Each character in s is a lowercase English letter.

1≤|s|≤10^5

Input

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

s

Output

Print the string obtained by concatenating all the characters in the odd-numbered positions.

Sample Input 1

atcoder

Sample Output 1

acdr

Extract the first character a, the third character c, the fifth character d and the seventh character r to obtain acdr.

Sample Input 2

aaaa

Sample Output 2

aa

Sample Input 3

z

Sample Output 3

z

Sample Input 4

fukuokayamaguchi

Sample Output 4

fkoaaauh


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

    let swap a =
        let c = p.(a) in
        p.(a) <- p.(a + 1);
        p.(a + 1) <- c
    in

    let rec loop i acc =
        if i = n - 1 then acc else
            if p.(i) = i then (
                swap i;
                loop (i + 1) (acc + 1)
            ) else if i = n - 2 && p.(i + 1) = i + 1 then (
                swap i;
                loop (i + 1) (acc + 1)
            ) else loop (i + 1) acc
    in
    loop 0 0 |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

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

Operation: Swap two adjacent elements in the permutation.

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

Constraints

2≤N≤10^5

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

Input

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

N
p_1 p_2 .. p_N

Output

Print the minimum required number of operations

Sample Input 1

5
1 4 3 5 2

Sample Output 1

2

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

Sample Input 2

2
1 2

Sample Output 2

1

Swapping 1 and 2 satisfies the condition.

Sample Input 3

2
2 1

Sample Output 3

0

The condition is already satisfied initially.

Sample Input 4

9
1 2 4 9 5 8 7 3 6

Sample Output 4

3


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

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


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

Score : 100 points

Problem Statement

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

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

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

Constraints

1 \leq x \leq 1000

1 \leq a \leq 1000

1 \leq b \leq 1000

x, a and b are pairwise distinct.

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

Input

Input is given from Standard Input in the following format:

x a b

Output

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

Sample Input 1

5 2 7

Sample Output 1

B

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

Sample Input 2

1 999 1000

Sample Output 2

A


open Printf
open Scanf

let () =
  let x, a, b = scanf "%d %d %d\n" (fun x y z -> (x, y, z)) in
  let ax = abs (x - a) in
  let bx = abs (x - b) in
  (if ax < bx then "A" else "B") |> printf "%s\n"


let m = 1000000007

let () =
  let n = read_int () in
  let s1 = read_line () in
  read_line () |> ignore;
  let rec doit i ps =
    if i = n then ps
    else if i = n - 1 || s1.[i] <> s1.[i+1] then doit (i + 1) (true :: ps)
    else doit (i + 2) (false :: ps) in
  match doit 0 [] with
  | [] -> assert false
  | p :: ps ->
    let _, s = List.fold_left (fun (q, s) p ->
      match q, p with
      | true, true -> true, s * 2 mod m
      | true, false -> false, s * 2 mod m
      | false, true -> true, s
      | false, false -> false, s * 3 mod m)
      (if p then true, 3 else false, 6) ps in
    Printf.printf "%d\n" s

Score : 400 points

Problem Statement

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

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

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

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

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

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

Constraints

1 \leq N \leq 52

|S_1| = |S_2| = N

S_1 and S_2 consist of lowercase and uppercase English letters.

S_1 and S_2 represent a valid arrangement of dominoes.

Input

Input is given from Standard Input in the following format:

N
S_1
S_2

Output

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

Sample Input 1

3
aab
ccb

Sample Output 1

6

There are six ways as shown below:

Sample Input 2

1
Z
Z

Sample Output 2

3

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

Sample Input 3

52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn

Sample Output 3

958681902


module CharMap = Map.Make (Char)

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

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

Score : 300 points

Problem Statement

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

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

Constraints

4 \leq N \leq 10^5

1 \leq A_i \leq 10^9

A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

6
3 1 2 4 2 1

Sample Output 1

2

1 \times 2 rectangle can be formed.

Sample Input 2

4
1 2 3 4

Sample Output 2

0

No rectangle can be formed.

Sample Input 3

10
3 3 3 3 4 4 4 5 5 5

Sample Output 3

20


let n = read_line ()
let _ = print_endline @@ if n.[0] = n.[2] then "Yes" else "No"

Score : 100 points

Problem Statement

You are given a three-digit positive integer N.

Determine whether N is a palindromic number.

Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.

Constraints

100≤N≤999

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a palindromic number, print Yes; otherwise, print No.

Sample Input 1

575

Sample Output 1

Yes

N=575 is also 575 when read backward, so it is a palindromic number. You should print Yes.

Sample Input 2

123

Sample Output 2

No

N=123 becomes 321 when read backward, so it is not a palindromic number. You should print No.

Sample Input 3

812

Sample Output 3

No


let main () = Scanf.sscanf (read_line ()) "%d %d %d %d"
  (fun a b c d -> print_int(if b < c || d < a then 0
    else if b = d && a < c then d-c
    else if b = d && a > c then d-a
    else if a = c && b < d then c-b
    else if a = c && b > d then c-d
    else if a < c && b > d then d-c
    else if a > c && d > b then b-a
    else if a < c && b < d then (((b-a)+(d-c)) -(d-a)) else (((b-a)+(d-c)) -(b-c))))
let _ = main()

Score : 200 points

Problem Statement

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

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

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

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

Constraints

0≤A<B≤100

0≤C<D≤100

All input values are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

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

Sample Input 1

0 75 25 100

Sample Output 1

50

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

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

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

Sample Input 2

0 33 66 99

Sample Output 2

0

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

Sample Input 3

10 90 20 80

Sample Output 3

60


let main () = Scanf.sscanf (read_line ()) "%d %d %d %d"
  (fun a b c d -> print_int(if b < c || d < a then 0
    else if b = c then d-a
    else if a = d then b-c
    else if b = d && a < c then d-c
    else if b = d && a > c then d-a
    else if a = c && b < d then c-b
    else if a = c && b > d then c-d
    else if a < c && b > d then d-c
    else if a > c && d > b then b-a
    else if a < c && b < d then (((b-a)+(d-c)) -(d-a)) else (((b-a)+(d-c)) -(b-c))))
let _ = main()


let main () = Scanf.sscanf (read_line ()) "%d %d %d %d"
  (fun a b c d -> print_int(if b < c || d < a then 0
    else if a < c && b > d then d-c
    else if a > c && d > b then b-a
    else if a < c && b < d then (((b-a)+(d-c)) -(d-a)) else (((b-a)+(d-c)) -(b-c))))
let _ = main()


Scanf.scanf "%d" (fun n ->
    let t = Array.init n (fun _ -> Scanf.scanf " %d" (fun t -> t)) in
    let rec gcd a b = if b = 0 then a else gcd b (a mod b) in
    let lcm a b = a / gcd a b * b in

    let rec loop i acc =
        if i = n then acc else loop (i + 1) (lcm acc t.(i))
    in
    loop 1 t.(0) |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

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

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

Now, Dolphin starts all the clocks simultaneously.

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

Constraints

1≤N≤100

1≤T_i≤10^{18}

All input values are integers.

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

Input

Input is given from Standard Input in the following format:

N
T_1
:
T_N

Output

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

Sample Input 1

2
2
3

Sample Output 1

6

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

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

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

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

Sample Input 2

5
2
5
10
1000000000000000000
1000000000000000000

Sample Output 2

1000000000000000000


let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let lcm a b = a / gcd a b * b
let n = Scanf.scanf "%d" (fun x -> x)
let xs = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))
let () = Array.fold_left lcm 1 xs |> Printf.printf "%d\n"


Scanf.scanf "%d" (fun n ->
    let nei = Array.make n [] in
    for i = 1 to n - 1 do
        Scanf.scanf " %d %d %d" (fun a b c ->
            let a, b = a - 1, b - 1 in
            nei.(a) <- (c, b) :: nei.(a);
            nei.(b) <- (c, a) :: nei.(b);
        )
    done;
    Scanf.scanf " %d %d" (fun q k ->
        let k = k - 1 in
        let dist = Array.make n (max_int / n) in
        dist.(k) <- 0;
        let rec loop next = function
            | [] -> if next <> [] then loop [] next
            | hd :: tl ->
                    let cur = dist.(hd) in
                    let next = List.fold_left (fun next (c, v) ->
                        if dist.(v) > cur + c then (
                            dist.(v) <- cur + c;
                            v :: next
                        ) else next
                    ) next nei.(hd) in
                    loop next tl
        in
        loop [] [ k ];
        for i = 1 to q do
            Scanf.scanf " %d %d" (fun x y ->
                let x, y = x - 1, y - 1 in
                Printf.printf "%d\n" (dist.(x) + dist.(y))
            )
        done
    )
)

Score : 400 points

Problem Statement

You are given a tree with N vertices.

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

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

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

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

Constraints

3≤N≤10^5

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

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

The given graph is a tree.

1≤Q≤10^5

1≤K≤N

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

x_j≠y_j (1≤j≤Q)

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the responses to the queries in Q lines.

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

Sample Input 1

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

Sample Output 1

3
2
4

The shortest paths for the three queries are as follows:

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

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

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

Sample Input 2

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

Sample Output 2

5
14
22

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

Sample Input 3

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

Sample Output 3

17000000000


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

let () =
  Scanf.scanf "%d" @@ fun n ->
  let g = Array.init (n+1) (fun _ -> []) in
  for _ = 1 to n-1 do
    Scanf.scanf " %d %d %d" @@ fun a b c ->
    g.(a) <- (b, c) :: g.(a);
    g.(b) <- (a, c) :: g.(b);
  done;

  Scanf.scanf " %d %d" @@ fun q k ->

  let dist = Array.make (n+1) inf in
  dist.(k) <- 0;

  let rec loop pqi =
    if M.is_empty pqi then () else
    let (d, u) = M.min_elt pqi in
    let pqi' = M.remove (d,u) pqi in

    if d > dist.(u) then loop pqi' else
      g.(u) |> List.fold_left (fun pq (v, c) ->
        if d+c < dist.(v) then begin
          dist.(v) <- d+c;
          M.add (d+c, v) pq
        end else pq) pqi'
    |> loop
  in loop (M.singleton (0, k));

  for _ = 1 to q do
    Scanf.scanf " %d %d" @@ fun x y ->
    dist.(x) + dist.(y) |> Printf.printf "%d\n"
  done


module MakeBinaryHeap (M : sig type t val compare : t -> t -> int end) = struct

  type t = { node : M.t array; mutable size : int }

  let make n (init : M.t) = { node = Array.make n init; size = 0 }

  let empty_p t = if t.size = 0 then true else false

  let pop t =
    if t.size <= 0 then failwith "out of size" else
    let rec max_heapify i =
      let l = 2*i in
      let r = 2*i + 1 in
      let m = if l <= t.size && M.compare t.node.(l) t.node.(i) > 0 then l else i in
      let m = if r <= t.size && M.compare t.node.(r) t.node.(m) > 0 then r else m in
      if m = i then ()
      else begin
        let tmp = t.node.(i) in
        t.node.(i) <- t.node.(m);
        t.node.(m) <- tmp;
        max_heapify m
      end in
    let ret = t.node.(1) in
    t.node.(1) <- t.node.(t.size);
    t.size <- t.size - 1;
    max_heapify 1;
    ret

  let push x t =
    let parent i = int_of_float (floor (float_of_int i) /. 2.) in
    let rec doit i =
      let p = parent i in
      if i <= 1 || M.compare t.node.(p) t.node.(i) >= 0 then ()
      else begin
        let tmp = t.node.(i) in
        t.node.(i) <- t.node.(p);
        t.node.(p) <- tmp;
        doit p
      end in
    t.size <- t.size + 1;
    t.node.(t.size) <- x;
    doit t.size

end

module H = MakeBinaryHeap(struct type t = int * int let compare (_, x) (_, y) = y - x end)

let dijkstra t n k =
  let reached_p = Array.make n false in
  let d = Array.make n max_int in
  d.(k) <- 0;
  let h = H.make 10000 (0, 0) in
  H.push (k, 0) h;
  while not (H.empty_p h) do
    let (u, x) = H.pop h in
    reached_p.(u) <- true;
    if x > d.(u) then ()
    else
      Array.iteri (fun v c ->
        if c = max_int then ()
        else begin
          let x = d.(u) + c in
          if not reached_p.(v) && x < d.(v) then begin
            d.(v) <- x;
            H.push (v, x) h;
          end
        end) t.(u);
  done;
  d

let () =
  let n = Scanf.scanf "%d " (fun i -> i) in
  let t = Array.make_matrix n n max_int in
  for _ = 1 to n - 1 do
    let a, b, c = Scanf.scanf "%d %d %d " (fun a b c -> a, b, c) in
    let a, b = a - 1, b - 1 in
    t.(a).(b) <- c;
    t.(b).(a) <- c;
  done;
  let q, k = Scanf.scanf "%d %d " (fun q k -> q, k) in
  let k = k - 1 in
  let d = dijkstra t n k in
  for _ = 0 to q - 1 do
    let x, y = Scanf.scanf "%d %d " (fun x y -> x, y) in
    let x, y = x - 1, y - 1 in
    Printf.printf "%d\n" (d.(x) + d.(y))
  done