(* O(n) (n = |s|) *)
let string_to_char_array s = Array.init (String.length s) (fun i -> s.[i])

(* O(n) (n = |cs|) *)
let char_array_to_string cs = String.init (Array.length cs) (fun i -> cs.(i))

(* O(n * log(n)) (n = |s|) *)
let string_sort cmp s =
  let cs = string_to_char_array s in
  Array.sort cmp cs;
  char_array_to_string cs

(* O(n * log(n)) (n = max {|s|, |t|}) *)
let solve s t =
  if string_sort compare s < string_sort (fun x y -> compare x y * -1) t then
    "Yes"
  else
    "No"

let _ =
  let s = read_line () in
  let t = read_line () in
  solve s t |> print_endline

Score : 200 points

Problem Statement

You are given strings s and t, consisting of lowercase English letters.
You will create a string s' by freely rearranging the characters in s.
You will also create a string t' by freely rearranging the characters in t.
Determine whether it is possible to satisfy s' < t' for the lexicographic order.

Notes

For a string a = a_1 a_2 ... a_N of length N and a string b = b_1 b_2 ... b_M of length M, we say a < b for the lexicographic order if either one of the following two conditions holds true:

N < M and a_1 = b_1, a_2 = b_2, ..., a_N = b_N.

There exists i (1 \leq i \leq N, M) such that a_1 = b_1, a_2 = b_2, ..., a_{i - 1} = b_{i - 1} and a_i < b_i. Here, letters are compared using alphabetical order.

For example, xy < xya and atcoder < atlas.

Constraints

The lengths of s and t are between 1 and 100 (inclusive).

s and t consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If it is possible to satisfy s' < t', print Yes; if it is not, print No.

Sample Input 1

yx
axy

Sample Output 1

Yes

We can, for example, rearrange yx into xy and axy into yxa. Then, xy < yxa.

Sample Input 2

ratcode
atlas

Sample Output 2

Yes

We can, for example, rearrange ratcode into acdeort and atlas into tslaa. Then, acdeort < tslaa.

Sample Input 3

cd
abc

Sample Output 3

No

No matter how we rearrange cd and abc, we cannot achieve our objective.

Sample Input 4

w
ww

Sample Output 4

Yes

Sample Input 5

zzz
zzz

Sample Output 5

No


let ans, a_s = ref 0, Array.init (read_int ()) @@ fun _ -> Scanf.scanf " %d" (+) 0
let f (p, c) a = a, if a <> p then (ans := !ans + if p > c then c else c - p; 1) else c + 1
let _ = Array.(sort (-) a_s; f (fold_left f (a_s.(0), 0) a_s) 0) |> ignore; Printf.printf "%d\n" !ans

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

Score : 300 points

Problem Statement

You are given a sequence of positive integers of length N, a = (a_1, a_2, ..., a_N).
Your objective is to remove some of the elements in a so that a will be a good sequence.

Here, an sequence b is a good sequence when the following condition holds true:

For each element x in b, the value x occurs exactly x times in b.

For example, (3, 3, 3), (4, 2, 4, 1, 4, 2, 4) and () (an empty sequence) are good sequences, while (3, 3, 3, 3) and (2, 4, 1, 4, 2) are not.

Find the minimum number of elements that needs to be removed so that a will be a good sequence.

Constraints

1 \leq N \leq 10^5

a_i is an integer.

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of elements that needs to be removed so that a will be a good sequence.

Sample Input 1

4
3 3 3 3

Sample Output 1

1

We can, for example, remove one occurrence of 3. Then, (3, 3, 3) is a good sequence.

Sample Input 2

5
2 4 1 4 2

Sample Output 2

2

We can, for example, remove two occurrences of 4. Then, (2, 1, 2) is a good sequence.

Sample Input 3

6
1 2 2 3 3 3

Sample Output 3

0

Sample Input 4

1
1000000000

Sample Output 4

1

Remove one occurrence of 10^9. Then, () is a good sequence.

Sample Input 5

8
2 7 1 8 2 8 1 8

Sample Output 5

5

Submitted source-code file size, in bytes.

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

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


open Batteries

module Intmap = Map.Make(Int)

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

  let intmap = Intmap.empty in
  let intmap = List.fold_left (fun accum x -> Intmap.modify_opt x (fun v_opt -> match v_opt with
        Some v -> Some (v+1)
      | None -> Some 1
    ) accum) intmap a_lst
  in
  let assoc = Intmap.bindings intmap in
  let ans = List.map (fun (i,c) -> if i < c then c-i else if i > c then c else 0) assoc |> List.fold_left (+) 0 in

  Printf.printf "%d\n" ans


open Scanf
open Printf

let flip f x y = f y x

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

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

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

let () =
  let n = read_int () in
  let xs = read_ints n in
  let cs = Array.make 100002 0 in
  flip List.iter xs (fun x ->
    let i = min 100001 x in cs.(i) <- cs.(i) + 1);
  for_iter 0 100002 (fun i -> if i <= cs.(i) then cs.(i) - i else cs.(i))
  |> List.fold_left (+) 0
  |> printf "%d\n"


open Scanf
open Printf

let flip f x y = f y x

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

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

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

let list_of_string str =
  let len = String.length str in
  let rec f i = if i >= len then [] else str.[i] :: f (i+1) in
  f 0

let lim_width = 16002
let cp = lim_width / 2

let swt ax = match ax with 'X' -> 'Y' | 'Y' -> 'X'

let rec parse ax acc xs =
  match xs with
  | [] -> if acc = 0 then [] else [(acc, ax)]
  | (x::xs') ->
      if x = 'T' then
        if acc = 0 then parse (swt ax) 0 xs'
        else (acc, ax) :: parse (swt ax) 0 xs'
      else parse ax (acc+1) xs'

let () =
  let s0::_ as s = read_line () |> list_of_string in
  let [xp; yp] = read_ints 2 in
  let f_first = s0 = 'F' in
  let steps = parse 'X' 0 s in
  let xs' = steps |> List.filter (fun z -> snd z = 'X') |> List.map fst in
  let (x0, xs) = match xs' with
  | (z::zs) when f_first -> (z, zs)
  | _                    -> (0, xs') in
  let ys = steps |> List.filter (fun z -> snd z = 'Y') |> List.map fst in

  let dp = Array.make lim_width 0 in
  let bak = Array.make lim_width 0 in

  let result = List.for_all (fun (ss, src, dst) ->
    Array.fill dp 0 lim_width 0; dp.(src) <- 1;
    List.iter (fun s ->
      Array.fill bak 0 lim_width 0;
      for_iter_ 0 lim_width (fun i ->
        if dp.(i) = 1 then (
          if i-s >= 0        then bak.(i-s) <- 1;
          if i+s < lim_width then bak.(i+s) <- 1
        ));
      for_iter_ 0 lim_width (fun i -> dp.(i) <- bak.(i));
    ) ss;
    dp.(dst) = 1) [(xs, cp+x0, cp+xp); (ys, cp, cp+yp)] in

  print_endline @@ if result then "Yes" else "No"

Score : 500 points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.

This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

|x|, |y| \leq |s|

Input

Input is given from Standard Input in the following format:

s
x y

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No


open Scanf
open Printf

let flip f x y = f y x

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

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

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

let list_of_string str =
  let len = String.length str in
  let rec f i = if i >= len then [] else str.[i] :: f (i+1) in
  f 0

let lim_width = 16010
let cp = lim_width / 2

type axis = X | Y

let swt ax = match ax with X -> Y | Y -> X

let rec parse ax acc xs =
  match xs with
  | [] -> if acc = 0 then [] else [(acc, ax)]
  | (x::xs') ->
      if x = 'T' then
        if acc = 0 then parse (swt ax) 0 xs'
        else (acc, ax) :: parse (swt ax) 0 xs'
      else parse ax (acc+1) xs'

let () =
  let hs::_ as s = list_of_string @@ read_line () in
  let [xp; yp] = read_ints 2 in
  let f_first = hs = 'F' in
  let steps = parse X 0 s in
  let xs' = steps |> List.filter (fun z -> snd z = X) |> List.map fst in
  let (x0, xs) = match xs' with
  | (y::ys) when f_first -> (y, ys)
  | _                    -> (0, xs') in
  let ys = steps |> List.filter (fun t -> snd t = Y) |> List.map fst in

  let dp = Array.make lim_width false in
  let bak = Array.make lim_width false in

  let result = List.for_all (fun (ss, src, dst) ->
    Array.fill dp 0 lim_width false; dp.(src) <- true;
    List.iter (fun x ->
      Array.fill bak 0 lim_width false;
      for_iter_ 0 lim_width (fun i ->
        if dp.(i) then
          if i >= x          then bak.(i-x) <- true;
          if i+x < lim_width then bak.(i+x) <- true);
      for_iter_ 0 lim_width (fun i ->
        dp.(i) <- bak.(i));
    ) ss;
    dp.(dst)) [(xs, cp+x0, cp+xp); (ys, cp, cp+yp)] in

  print_endline @@ if result then "Yes" else "No"


open Batteries

module IntSet = Set.Make (struct
  let compare = Pervasives.compare

  type t = int
end)

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

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

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

let read_list () =
  read_line () |> String.split_on_char ' '
  |> List.map (fun s -> int_of_string s)

let rec read_list_nl n =
  if n = 0 then [] else (read_line () |> int_of_string) :: read_list_nl (n - 1)

(* a**x *)
let pow a x =
  let rec aux acc = function 0 -> acc | n -> aux (acc * a) (n - 1) in
  aux 1 x

let rec pow2 n = if n mod 2 = 0 then 1 + pow2 (n / 2) else 0

let rec f d a n = if n > d then 0 else 1 + f d a (n + a)

let rec total acc = function [] -> acc | x :: rest -> total (acc + x) rest

let () =
  let _ = read_int () in
  let ans =
    read_list () |> List.map pow2
    |> List.fold_left (fun x acc -> if acc > x then x else acc) 32
  in
  print_int ans;
  print_newline ()

Score : 200 points

Problem Statement

There are N positive integers written on a blackboard: A_1, ..., A_N.

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer X on the blackboard by X divided by 2.

Find the maximum possible number of operations that Snuke can perform.

Constraints

1 \leq N \leq 200

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible number of operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, [8, 12, 40] are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, [4, 6, 20] are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, [2, 3, 10] are written on the blackboard.
Now, there is an odd number 3 on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number 5 on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8


let cnt n =
  let rec f n' c = if n' mod 2 = 1 then c else f (n' / 2) (c + 1) in
  f n 0

let solve n =
  let rec f i ans =
    if i > n then ans
    else let tmp = Scanf.scanf "%d " cnt in f (i + 1) (min ans tmp)
  in
  f 1 max_int

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


open Scanf
open Printf

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

let rec calc x = if x mod 2 = 1 then 0 else 1 + calc (x/2)

let () =
  let n = read_int () in
  read_ints n |> List.map calc |> List.fold_left min 100 |> printf "%d\n"


(* O(n log n) *)
Scanf.scanf " %d %d" @@ fun n k ->
  let balls = Array.make n 0 in
  for i = 1 to n do
    let a = Scanf.scanf " %d" @@ (+) 0 in
    balls.(a - 1) <- balls.(a - 1) + 1
  done;
  Array.sort (-) balls;
  Array.sub balls 0 @@ n - k |> Array.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 %d %d" (fun n a b ->
    min b (a * n) |> Printf.printf "%d\n"
)

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 solve n =
  let rec f x sum = if x < 1 then sum else f (x / 10) (x mod 10 + sum) in
  if n mod f n 0 = 0 then "Yes" else "No"

let () = solve (read_int ()) |> print_endline

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


let n, m = Scanf.scanf " %d %d" @@ fun a b -> a, b
let csts = Array.init n @@ fun _ -> Scanf.scanf " %d %d %d" @@ fun s t c -> c, s, t
let acc = Array.make 100002 0
let _ = Array.(sort compare csts; fold_left (fun (c0, t0) (c, s, t) -> if c0 = c && t0 = s then acc.(t0 + 1) <- acc.(t0 + 1) + 1 else acc.(s) <- acc.(s) + 1; acc.(t + 1) <- acc.(t + 1) - 1; c, t) (0, 0) csts |> ignore; iteri (fun i a -> if i > 0 then acc.(i) <- acc.(i) + acc.(i - 1)) acc; fold_left max 0 acc) |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

Joisino is planning to record N TV programs with recorders.

The TV can receive C channels numbered 1 through C.

The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i.

Here, there will never be more than one program that are broadcast on the same channel at the same time.

When the recorder is recording a channel from time S to time T (including time S but not T), it cannot record other channels from time S-0.5 to time T (including time S-0.5 but not T).

Find the minimum number of recorders required to record the channels so that all the N programs are completely recorded.

Constraints

1≤N≤10^5

1≤C≤30

1≤s_i<t_i≤10^5

1≤c_i≤C

If c_i=c_j and i≠j, either t_i≤s_j or s_i≥t_j.

All input values are integers.

Input

Input is given from Standard Input in the following format:

N C
s_1 t_1 c_1
:
s_N t_N c_N

Output

When the minimum required number of recorders is x, print the value of x.

Sample Input 1

3 2
1 7 2
7 8 1
8 12 1

Sample Output 1

2

Two recorders can record all the programs, for example, as follows:

With the first recorder, record Channel 2 from time 1 to time 7. The first program will be recorded. Note that this recorder will be unable to record other channels from time 0.5 to time 7.

With the second recorder, record Channel 1 from time 7 to time 12. The second and third programs will be recorded. Note that this recorder will be unable to record other channels from time 6.5 to time 12.

Sample Input 2

3 4
1 3 2
3 4 4
1 4 3

Sample Output 2

3

There may be a channel where there is no program to record.

Sample Input 3

9 4
56 60 4
33 37 2
89 90 3
32 43 1
67 68 3
49 51 3
31 32 3
70 71 1
11 12 3

Sample Output 3

2


let s = read_line ()
let t = "AKIHABARA"
let rec f u i = if i >= String.length t then u = s
  else if t.[i] = 'A' then f (u ^ "A") (i + 1) || f u (i + 1) else f (u ^ String.make 1 t.[i]) (i + 1)
let _ = print_endline @@ if f "" 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


Scanf.scanf "%d" (fun n ->
    let hp = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun h p -> h, p)) in
    Array.sort (fun (h1, p1) (h2, p2) -> compare (h1 + p1, h1) (h2 + p2, h2)) hp;

    let rec loop i dp =
        if i = n then dp else (
            let h, p = hp.(i) in
            let dp2 = Array.copy dp in
            for j = 1 to n do
                if dp.(j - 1) <= h then dp2.(j) <- min dp.(j) (dp.(j - 1) + p)
            done;
            loop (i + 1) dp2
        )
    in
    let init = Array.make (n + 1) max_int in
    init.(0) <- 0;
    let dp = loop 0 init in

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

Score : 700 points

Problem Statement

In the final of CODE FESTIVAL in some year, there are N participants.
The height and power of Participant i is H_i and P_i, respectively.

Ringo is hosting a game of stacking zabuton (cushions).

The participants will line up in a row in some order, and they will in turn try to add zabuton to the stack of zabuton.
Initially, the stack is empty.
When it is Participant i's turn, if there are H_i or less zabuton already stacked, he/she will add exactly P_i zabuton to the stack. Otherwise, he/she will give up and do nothing.

Ringo wants to maximize the number of participants who can add zabuton to the stack.
How many participants can add zabuton to the stack in the optimal order of participants?

Constraints

1 \leq N \leq 5000

0 \leq H_i \leq 10^9

1 \leq P_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 P_1
H_2 P_2
:
H_N P_N

Output

Print the maximum number of participants who can add zabuton to the stack.

Sample Input 1

3
0 2
1 3
3 4

Sample Output 1

2

When the participants line up in the same order as the input, Participants 1 and 3 will be able to add zabuton.

On the other hand, there is no order such that all three participants can add zabuton. Thus, the answer is 2.

Sample Input 2

3
2 4
3 1
4 1

Sample Output 2

3

When the participants line up in the order 2, 3, 1, all of them will be able to add zabuton.

Sample Input 3

10
1 3
8 4
8 3
9 1
6 4
2 3
4 2
9 2
8 3
0 1

Sample Output 3

5


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 () =
  let s = read_str () in
  let n = S.length s in
  let res =
    foreach (||) false 0 (n - 2) (fun i ->
              s.[i] = s.[i+1] && s.[i] = s.[i+2] ) in
  let ans = if res then "Yes" else "No" in
  pf "%s\n" ans

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


Scanf.scanf "%d" (fun n ->
    let rec loop i l0 l1 =
        if i = n then l0 else
            loop (i + 1) l1 (l0 + l1)
    in
    loop 0 2 1 |> Printf.printf "%d\n"
)

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


(*
ocamlfind ocamlopt -package batteries -linkpkg main.ml -o a.out
*)
open Batteries

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

let rec f lst n =
        match lst with
                  [] -> 0
                | first :: [] -> 0
                | first :: second :: rest ->
                        let luca = first + second in
                                if n = 0 then
                                        luca
                                else
                                        f (luca :: lst) (n - 1)

let () =
        (
                if n = 0 then
                        2
                else
                if n = 1 then
                        1
                else
                        f [1; 2] (n - 2)
        )
        |> Printf.printf "%d\n"


let lucas n =
  let rec f i pre now =
    if i = n then now else f (i + 1) now (pre + now)
  in
  if n = 0 then 2 else f 1 2 1

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


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

let rec lucas n =
  let rec lucas_pair n =
    match n with
    | 0 -> (2,0)
    | 1 -> (1,2)
    | m -> let (i,j) = lucas_pair (n-1) in (i+j,i)
  in let (i,_) = lucas_pair n in i

let ans = lucas n

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


type op =
  | Plus
  | Minus
  | Id

let print_op = function
    Plus -> print_char '+'
  | Minus -> print_char '-'
  | Id -> ()

(* list_all 2 [true; false];;
 * - : bool list list =
 * [[true; true]; [false; true]; [true; false]; [false; false]] *)
(* olに含まれる要素で作れる長さnのリストすべてを返す *)
let rec list_all : int -> 'a list -> 'a list list  = fun n ol ->
  if n > 0 then
    List.fold_right (fun l ans ->
        List.fold_right
          (fun o xs ->
             (o :: l) :: xs)
          ol ans)
      (list_all (n - 1) ol) []
  else
    [[]]

let calc_op l opss =
  let rec loop ans =
    (function
      | (x :: xs, o :: os) ->
      (match o with
          Plus -> loop (ans + x) (xs, os)
        | Minus -> loop (ans - x) (xs, os)
        | Id -> loop x (xs, os))
      | _ -> ans)
  in
  loop 0 (l, opss)

let ic c = int_of_char c - int_of_char '0'

let () =
  let (a, b, c, d) = Scanf.sscanf (input_line stdin) "%c%c%c%c" (fun a b c d -> (ic a, ic b, ic c, ic d)) in
  let ops_lists = list_all 3 [Plus; Minus] in
  let ops_lists' = List.map (fun ops -> Id :: ops) ops_lists in
  let rec solve = function
      [] -> failwith "Not found"
    | ops :: opss ->
      if calc_op [a;b;c;d] ops = 7 then
        ops
      else
        solve opss
  in
  let ans = solve ops_lists' in
  List.iter2 (fun x op ->
      print_op op;
      print_int x) [a;b;c;d] ans;
  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


let id x = x
let n = Scanf.scanf "%s\n" id
let a = (int_of_char n.[0]) - 48
let b = (int_of_char n.[1]) - 48
let c = (int_of_char n.[2]) - 48
let d = (int_of_char n.[3]) - 48
let oplist = [1;0]

let i2op i = if i = 1 then (+) else (-)
let i2c i = if i = 1 then '+' else '-'

let rec loop3 op1 op2 l =
  match l with
  | [] -> []
  | op3 :: rest ->
     if (i2op op3) ((i2op op2) ((i2op op1) a b) c) d = 7 then (op1,op2,op3) :: loop3 op1 op2 rest
       else loop3 op1 op2 rest

let rec loop2 op1 l =
  match l with
  | [] -> []
  | op2 :: rest -> (loop3 op1 op2 oplist) @ loop2 op1 rest

let rec loop1 l =
  match l with
  | [] -> []
  | op1 :: rest -> (loop2 op1 oplist) @ loop1 rest

let (op1,op2,op3) = List.hd (loop1 oplist)
let (op1,op2,op3) = (i2c op1,i2c op2,i2c op3)

let () =
  Printf.printf "%d%c%d%c%d%c%d=7\n" a op1 b op2 c op3 d


(* quite naive implementation *)
let rec dikjstra ( +. ) ( < ) q edge d =
  match q with
  | [] -> ()
  | u :: q ->
      let u, q =
        List.fold_left (fun (u, q') u' ->
          if d.(u) < d.(u') then (u, u' :: q')
          else (u', u :: q')) (u, []) q in
      List.iter (fun (v, c) ->
        if c +. d.(u) < d.(v) then
          d.(v) <- c +. d.(u)) (edge u);
      dikjstra ( +. ) ( < ) q edge d

let () =
  let h, w = Scanf.scanf "%d %d\n" (fun h w -> h, w) in
  let css =
    Array.init 10 (fun _ ->
      Array.init 10 (fun i ->
        Scanf.scanf "%d " (fun c -> c))) in
  let css' =
    Array.init 10 (fun i ->
      Array.to_list @@ Array.init 10 (fun j -> (j, css.(j).(i)))) in
  let ass =
    Array.init h (fun _ ->
      Array.init w (fun _ ->
        Scanf.scanf "%d " (fun a -> a))) in
  let cost = Array.make 10 1145141919 in
  cost.(1) <- 0;
  dikjstra ( + ) ( < ) [1; 2; 3; 4; 5; 6; 7; 8; 9; 0] (fun i -> css'.(i)) cost;
  Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 @@ Array.map (fun as_ ->
    Array.fold_left ( + ) 0 @@ Array.map (function -1 -> 0 | n -> cost.(n)) as_) ass

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


Scanf.scanf "%c %c" (fun x y ->
    print_endline @@ if x < y then "<" else
                     if x > y then ">" else "="
)

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 id x = x
let (x,y) = Scanf.scanf "%c %c\n" (fun x y -> (x,y))

let ans = if x = y then '=' else
    if x < y then '<' else '>'

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


let x, y, z = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let n = ref 1
let _ =
  while !n * y + (!n + 1) * z <= x do incr n done;
  Printf.printf "%d\n" @@ !n - 1

Score : 200 points

Problem Statement

We have a long seat of width X centimeters.
There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters.

We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two people, and between the end of the seat and a person.

At most how many people can sit on the seat?

Constraints

All input values are integers.

1 \leq X, Y, Z \leq 10^5

Y+2Z \leq X

Input

Input is given from Standard Input in the following format:

X Y Z

Output

Print the answer.

Sample Input 1

13 3 1

Sample Output 1

3

There is just enough room for three, as shown below:

Figure

Sample Input 2

12 3 1

Sample Output 2

2

Sample Input 3

100000 1 1

Sample Output 3

49999

Sample Input 4

64146 123 456

Sample Output 4

110

Sample Input 5

64145 123 456

Sample Output 5

109


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 (1, 2)

Score : 300 points

Problem Statement

Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is YES or NO.

When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases.

Then, he rewrote the code to correctly solve each of those M cases with 1/2 probability in 1900 milliseconds, and correctly solve each of the other N-M cases without fail in 100 milliseconds.

Now, he goes through the following process:

Submit the code.

Wait until the code finishes execution on all the cases.

If the code fails to correctly solve some of the M cases, submit it again.

Repeat until the code correctly solve all the cases in one submission.

Let the expected value of the total execution time of the code be X milliseconds. Print X (as an integer).

Constraints

All input values are integers.

1 \leq N \leq 100

1 \leq M \leq {\rm min}(N, 5)

Input

Input is given from Standard Input in the following format:

N M

Output

Print X, the expected value of the total execution time of the code, as an integer. It can be proved that, under the constraints in this problem, X is an integer not exceeding 10^9.

Sample Input 1

1 1

Sample Output 1

3800

In this input, there is only one case. Takahashi will repeatedly submit the code that correctly solves this case with 1/2 probability in 1900 milliseconds.

The code will succeed in one attempt with 1/2 probability, in two attempts with 1/4 probability, and in three attempts with 1/8 probability, and so on.

Thus, the answer is 1900 \times 1/2 + (2 \times 1900) \times 1/4 + (3 \times 1900) \times 1/8 + ... = 3800.

Sample Input 2

10 2

Sample Output 2

18400

The code will take 1900 milliseconds in each of the 2 cases, and 100 milliseconds in each of the 10-2=8 cases. The probability of the code correctly solving all the cases is 1/2 \times 1/2 = 1/4.

Sample Input 3

100 5

Sample Output 3

608000


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

let rec maximize z w xs =
  select xs
  |> List.map (function
        | (_, x, []) -> abs (x - w)
        | (_, x, ys) -> minimize x w ys)
  |> List.fold_left max min_int
and minimize z w ys =
  select ys
  |> List.map (function
        | (_, y, []) -> abs (z - y)
        | (_, y, xs) -> maximize z y xs)
  |> List.fold_left max min_int

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
  Printf.printf "%d\n" @@ maximize z w (Array.to_list as_)

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


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

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

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

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

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

module G = FlowNetwork (struct
  type t = int
  let inf = max_int
  let zero = 0
  let ( + ) = ( + )
  let ( - ) = ( - )
  let compare = compare
end)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.to_list @@
    Array.init n @@ fun _ ->
      Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@ ( - ) (List.fold_right (fun a -> ( + ) @@ max 0 a) as_ 0) @@
    fst @@ G.max_flow n 0 1 @@ List.concat @@ List.mapi (fun i a ->
      ( if a = 0 then []
        else if a < 0 then [(0, i + 2, ~- a, 0)]
        else [(i + 2, 1, a, 0)] ) @
      List.concat @@ Array.to_list @@ Array.init n @@ fun j ->
        if i < j && (j + 1) mod (i + 1) = 0 then [(i + 2, j + 2, max_int, 0)]
        else []) as_

Score : 700 points

Problem Statement

We have N gemstones labeled 1 through N.

You can perform the following operation any number of times (possibly zero).

Select a positive integer x, and smash all the gems labeled with multiples of x.

Then, for each i, if the gem labeled i remains without getting smashed, you will receive a_i yen (the currency of Japan).
However, a_i may be negative, in which case you will be charged money.

By optimally performing the operation, how much yen can you earn?

Constraints

All input values are integers.

1 \leq N \leq 100

|a_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum amount of money that can be earned.

Sample Input 1

6
1 2 -6 4 5 3

Sample Output 1

12

It is optimal to smash Gem 3 and 6.

Sample Input 2

6
100 -100 -100 -100 100 -100

Sample Output 2

200

Sample Input 3

5
-1 -2 -3 -4 -5

Sample Output 3

0

It is optimal to smash all the gems.

Sample Input 4

2
-1000 100000

Sample Output 4

99000


let s1 = read_line ()
let s2 = read_line ()
let _ = print_endline @@ if s1.[0] = s2.[2] && s1.[1] = s2.[1] && s1.[2] = s2.[0] then "YES" else "NO"

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 () =
  let a, b = Scanf.scanf "%s %s" (fun a b -> a, b) in
  Printf.printf "%s\n" @@ if a.[0] = b.[2] && a.[1] = b.[1] && a.[2] = b.[0] then "YES" else "NO"


let ()=Scanf.scanf"%f"(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


open Scanf
open Printf

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

let n = scanf "%d\n" (fun x -> x)
let a_ = input_array n
let b_ = input_array n
let c_ = input_array n

let rec lower_bound' arr (first, last) n =
    let mid = (first+last)/2
    in if last - first <= 1
        then if (arr.(first) < n) then last else first
        else if (arr.(mid) < n)
            then lower_bound' arr (mid, last)  n
            else lower_bound' arr (first, mid) n

let lower_bound arr n = if arr.(Array.length arr - 1) < n
    then Array.length arr
    else lower_bound' arr (0, Array.length arr - 1) n

let upper_bound arr n = lower_bound arr (n+1)

let _ = Array.sort Pervasives.compare a_; Array.sort Pervasives.compare c_;
    Array.fold_left (fun s x -> s + lower_bound a_ x * (n - upper_bound c_ x)) 0 b_
    |> print_int
    |> print_newline

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


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 dijkstra :
    (* 隣接リスト *)
    (Vertex.t -> (Vertex.t * Weight.t) list) ->
    (* 始点 *)
    Vertex.t ->
    (* 始点から辿り着けなければNoneを返す *)
    (Vertex.t -> Weight.t option)
end =
struct
  module WMap = Map.Make (Weight)
  module VMap = Map.Make (Vertex)

  (* ダイクストラ法のメインループ *)
  (* d に入っていない頂点への距離は無限大とみなす *)
  let rec dijkstra_aux e (d, q) =
    match WMap.min_binding q with
    | exception Not_found -> d
    | (w, us) ->
        dijkstra_aux e @@ List.fold_left (fun (d, q) u ->
          if Weight.compare (VMap.find u d) w < 0
          (* 既に頂点uを訪れていた *)
          then (d, q)
          (* w = d.(u) *)
          else List.fold_left (fun (d, q) (v, c) ->
            let open Weight in
            if
              (* d.(v) <= d.(u) + c *)
              try Weight.compare (VMap.find v d) (w + c) <= 0
              with Not_found -> false (* d.(v) は無限大 *)
            then (d, q)
            else
              VMap.add v (w + c) d,
              WMap.add (w + c) (v :: try WMap.find (w + c) q with Not_found -> []) q)
          (d, q) (e u)) (d, WMap.remove w q) us

  let dijkstra e s =
    let d =
      dijkstra_aux e
        (VMap.singleton s Weight.zero, WMap.singleton Weight.zero [s]) in
    fun t -> try Some (VMap.find t d) 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 () = Scanf.scanf "%d\n" @@ fun k ->
  let Some d = G.dijkstra (fun i -> [((i + 1) mod k, 1); (i * 10 mod k, 0)]) 1 0 in
  Printf.printf "%d\n" @@ 1 + d

Score : 700 points

Problem Statement

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

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

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

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36


Scanf.scanf "%d" (fun k ->
    let arr = Array.make k max_int in

    let deq = Array.make (2 * k) 0 in

    let rec loop f l =
        if f <= l then (
            let num = deq.(f) in
            let f = f + 1 in
            let cost = arr.(num) in
            let next = (num * 10) mod k in
            let f = if cost < arr.(next) then (
                arr.(next) <- cost;
                let f = f - 1 in
                deq.(f) <- next;
                f
            ) else f in
            let next = (num + 1) mod k in
            let l = if cost + 1 < arr.(next) then (
                arr.(next) <- cost + 1;
                let l = l + 1 in
                deq.(l) <- next;
                l
            ) else l
            in
            loop f l
        ) else f, l
    in
    arr.(1) <- 1;
    deq.(k) <- 1;
    ignore (loop k k);
    Printf.printf "%d\n" arr.(0)
)


Scanf.scanf "%d" (fun k ->
    let arr = Array.make k (-1) in

    let deq = Array.make (2 * k) 0 in

    let rec loop f l =
        if f <= l then (
            let num = deq.(f) in
            let f = f + 1 in
            let cost = arr.(num) in
            let next = (num * 10) mod k in
            if arr.(next) < 0 || arr.(next) > cost then (
                arr.(next) <- cost;
                let f = f - 1 in
                deq.(f) <- next;
                loop f l
            );
            let next = (num + 1) mod k in
            if arr.(next) < 0 || arr.(next) > cost + 1 then (
                arr.(next) <- cost + 1;
                let l = l + 1 in
                deq.(l) <- next;
                loop f l
            );
        )
    in
    arr.(1) <- 1;
    deq.(k) <- 1;
    loop k k;
    Printf.printf "%d\n" arr.(0)
)


module IntWeightedDirectedGraphByArray = struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  (* 辺の重さがごく小さい場合は，Mapをキュー代わりに使うより配列を使った方が効率的
     時間計算量はO(E+VW)，空間計算量はO(E+W) *)
  let dijkstra_special :
    (* 頂点数n *)
    int ->
    (* 辺の重さの上限W *)
    int ->
    (* 頂点uを受け取って，
       uから伸びる辺の終点vと重さwの組みのリストを返す関数
       辺の重さwはW以下でなくてはならない *)
    (int -> (int * int) church_list) ->
    (* 始点 *)
    int ->
    (* 始点から辿り着けなければinfを返す関数
       この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
    (int -> int)
  = fun n mw es s ->
    (* 各頂点への最短距離を格納するやつ *)
    let d = Array.make n max_int in
    (* キュー *)
    let q = Array.make (mw + 1) [] in
    (* ヒープの最小要素の重み *)
    let w = ref 0 in
    (* ヒープの最小要素がどのインデックスに対応するか *)
    let i = ref 0 in
    (* ヒープに格納されている要素の数 *)
    let m = ref 1 in
    d.(s) <- 0;
    q.(0) <- [s];
    let rec dijkstra_aux t =
      (* 既に終点までの距離が分かっているので返す *)
      if !m <= 0 || d.(t) <= !w then d.(t) else
      match q.(!i) with
      (* ヒープには重さがwの要素は無かった *)
      | [] ->
          incr w;
          incr i;
          if mw < !i then i := 0;
          dijkstra_aux t
      (* ヒープには重さwの要素uが存在する *)
      | u :: us ->
          (* ヒープから重さwの要素を削除する *)
          q.(!i) <- us;
          decr m;
          if !w <= d.(u) then
            (* 未だ頂点uを訪れていない *)
            (es u).fold (fun (v, c) () ->
              if !w + c < d.(v) then begin
                d.(v) <- !w + c; (* 頂点vの重さを緩和 *)
                (* ヒープにvを追加する *)
                incr m;
                let j = !i + c - if !i + c <= mw then 0 else mw + 1 in
                q.(j) <- v :: q.(j)
              end) ();
          dijkstra_aux t in
    dijkstra_aux
end

let () = Scanf.scanf "%d" @@ fun k ->
  Printf.printf "%d\n" @@
  succ @@
  IntWeightedDirectedGraphByArray.dijkstra_special k 1 (fun i ->
    { IntWeightedDirectedGraphByArray.fold = fun f acc -> f ((i + 1) mod k, 1) @@ f (i * 10 mod k, 0) acc }) 1 0


let () = Scanf.scanf "%d %d" (fun x y-> y*2 -x ) |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

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

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

Let the current rating of the user be a.

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

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

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

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

Find the performance required to achieve it.

Constraints

0 \leq R, G \leq 4500

All input values are integers.

Input

Input is given from Standard Input in the following format:

R
G

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is 2002.

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

Sample Input 2

4500
0

Sample Output 2

-4500

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


let n = read_int ()
let k, ans = read_int (), ref 1
let _ = for _ = 1 to n do ans := min (!ans + k) (2 * !ans) 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.


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let rec f acc i = if i >= n then acc else min (f (2 * acc) (i + 1)) @@ f (acc + k) (i + 1)
let _ = Printf.printf "%d\n" @@ f 1 0


open Printf
open Scanf

let () =
  let n = scanf "%d " (fun x -> x) in
  let rec read i =
    if i = 0 then []
    else let v = scanf "%d " (fun x -> x) in
         v :: read (i - 1) in
  let ls = read n in
  let rec expt3 n =
    if n = 0 then 1 else 3 * (expt3 (n - 1)) in
  expt3 n - (List.fold_left (fun a x -> if x mod 2 = 0 then a * 2 else a) 1 ls) |> printf "%d\n"

Score : 200 points

Problem Statement

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

In particular, any integer sequence is similar to itself.

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

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

Constraints

1 \leq N \leq 10

1 \leq A_i \leq 100

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the number of integer sequences that satisfy the condition.

Sample Input 1

2
2 3

Sample Output 1

7

There are seven integer sequences that satisfy the condition:

1, 2

1, 4

2, 2

2, 3

2, 4

3, 2

3, 4

Sample Input 2

3
3 3 3

Sample Output 2

26

Sample Input 3

1
100

Sample Output 3

1

Sample Input 4

10
90 52 56 71 44 8 13 30 57 84

Sample Output 4

58921


let f a b c = if a=b then c else (if a=c then b else a);;
Scanf.scanf "%d %d %d"
f
|> Printf.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


open Printf
open Scanf

let () =
  let a, b, c = scanf "%d %d %d " (fun x y z -> (x, y, z)) in
  (if a = b then c else if b = c then a else b) |> printf "%d\n"


(* n: int ref *)
let n = ref 0

(* k: int ref *)
let k = ref 0

(* pos: (int * int) list ref *)
let pos = ref []

(* sort_x: ('a * 'a) list -> ('a * 'a) list *)
let sort_x lst =
  List.sort (fun (x1, _) (x2, _) -> if x1 < x2 then -1 else 1) lst

(* sort_y: ('a * 'a) list -> ('a * 'a) list *)
let sort_y lst =
  List.sort (fun (_, y1) (_, y2) -> if y1 < y2 then -1 else 1) lst

(* minimum: 'a list -> 'a *)
let minimum lst =
  List.fold_left min max_int lst

(* soi: int -> string *)
let soi = string_of_int
(* pr: int -> unit *)
let pr x = print_endline (soi x)

(* calc_area: (int * int) list -> int *)
let calc_area lst = match lst with
  | [] -> 0
  | _ ->
    (* let _ = if List.length lst <> !k then failwith "err" in *)
    let h (x1, x2, y1, y2) (x, y) =
      (min x1 x, max x2 x, min y1 y, max y2 y)
    in
    let (x_min, x_max, y_min, y_max) =
      List.fold_left h (max_int, min_int, max_int, min_int) lst
    in
    (x_max - x_min) * (y_max - y_min)

(* heads: int -> 'a list -> 'a list *)
let rec heads len l = match l with
  | _ when len = 0 -> []
  | [] -> raise Not_found
  | x :: xs -> x :: (heads (len - 1) xs)

(* get_k_areas: ('a * 'a) list -> int list *)
let rec get_k_areas lst = match lst with
  | [] -> []
  | _ :: xs ->
    if List.length lst < !k then
      []
    else
      let l = heads !k lst in
      (calc_area l) :: (get_k_areas xs)

(* get_areas_on_x: unit -> int list *)
let get_areas_on_x () =
  !pos
  |> sort_x
  |> get_k_areas

(* get_areas_on_y: unit -> int list *)
let get_areas_on_y () =
  !pos
  |> sort_y
  |> get_k_areas

(* main: unit -> int *)
let main () =
  let sq_lst1 = get_areas_on_x () in
  let min1 = minimum sq_lst1 in
  let sq_lst2 = get_areas_on_y () in
  let min2 = minimum sq_lst2 in
  min min1 min2

(* subst: int -> int -> (int * int) list -> unit *)
let subst n_ k_ lst =
  n := n_;
  k := k_;
  pos := lst

(* start: int -> int -> (int * int) list -> unit *)
let start n_ k_ lst =
  subst n_ k_ lst;
  main ()
  |> string_of_int
  |> print_endline

(* test: unit -> unit *)
(*
let test () =
  subst 4 4 [(1, 4); (3, 3); (6, 2); (8, 1)];
  assert (main () == 21);
  subst 4 2 [(0, 0); (1, 1); (2, 2); (3, 3)];
  assert (main () == 1);
  subst 4 3 [(-1000000000, -1000000000);
             (1000000000, 1000000000);
             (-999999999, 999999999);
             (999999999, -999999999)];
  assert (main () == 3999999996000000001)

let _ = test ()
*)
(* read_2int: (int -> int -> 'a) -> 'a *)
let rec read_2int cont =
  Scanf.sscanf (read_line ()) "%d %d" cont

let _ = if true then
  read_2int (fun n_ k_ ->
    let rec h cont acc =
      if List.length acc = n_ then cont acc
      else read_2int (fun a b -> h cont ((a, b) :: acc))
    in
    h (start n_ k_) [])

Score : 400 points

Problem Statement

We have N points in a two-dimensional plane.

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

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

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

Find the minimum possible area of such a rectangle.

Constraints

2 \leq K \leq N \leq 50

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

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

4 4
1 4
3 3
6 2
8 1

Sample Output 1

21

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

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

Sample Input 2

4 2
0 0
1 1
2 2
3 3

Sample Output 2

1

Sample Input 3

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

Sample Output 3

3999999996000000001

Watch out for integer overflows.


let () = Scanf.scanf "%d" (fun n ->
  begin
    List.concat @@ Array.to_list @@ Array.init 3500 (fun h ->
    Array.to_list @@ Array.init (3500 - h) (fun w -> (h + 1, h + w + 1))) end
  |> List.find (fun (h, w) ->
      4 * h * w > n * w + n * h && (n * h * w) mod (4 * h * w - n * w - n * h) = 0)
  |> (fun (h, w) -> Printf.printf "%d %d %d\n" h ((n * h * w) / (4 * h * w - n * w - n * h)) w))

Score : 300 points

Problem Statement

You are given an integer N.

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

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

Constraints

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

Inputs

Input is given from Standard Input in the following format:

N

Outputs

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

h n w

Sample Input 1

2

Sample Output 1

1 2 2

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

Sample Input 2

3485

Sample Output 2

872 1012974 1539173474040

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

Sample Input 3

4664

Sample Output 3

3498 3498 3498


let population_count : int -> int = fun bits ->
  List.fold_left (fun bits (mask, shamt) ->
    (mask land bits) + (mask land (bits lsr shamt))) bits
    [ (0x5555555555555555, 1);
      (0x3333333333333333, 2);
      (0x0f0f0f0f0f0f0f0f, 4);
      (0x00ff00ff00ff00ff, 8);
      (0x0000ffff0000ffff, 16);
      (0x00000000ffffffff, 32) ]

module ABSet = Set.Make (struct
  type t = int * int
  let compare (a, b) (a', b') =
    compare (population_count a, -b, a) (population_count a', -b', a')
end)

let () =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let abs = Array.init n (fun _ -> Scanf.scanf "%d %d\n" (fun a b -> a, b)) in
  Array.fold_left (fun m (a, b) ->
    ABSet.fold (fun (a', b') m ->
      if (a lor a') <= k then begin
        match ABSet.split (a lor a', b + b') m with
        | _, true, _ -> m
        | minor, false, _ ->
            if ABSet.for_all (fun (a'', b'') -> a'' land lnot (a lor a') <> 0 || b'' < b + b') minor then ABSet.add (a lor a', b + b') m else m end else m) m m) (ABSet.singleton (0, 0)) abs
  |> (fun m -> ABSet.fold (fun (_, b) b' -> max b b') m 0)
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

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

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

Find the maximum possible sum of utilities of purchased integers.

Constraints

1 \leq N \leq 10^5

0 \leq K < 2^{30}

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

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

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N K
A_1 B_1
:
A_N B_N

Outputs

Print the maximum possible sum of utilities of purchased integers.

Sample Input 1

3 5
3 3
4 4
2 5

Sample Output 1

8

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

Sample Input 2

3 6
3 3
4 4
2 5

Sample Output 2

9

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

Sample Input 3

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

Sample Output 3

32


let inf = 101010101010101010
let _ = Scanf.scanf "%d" @@ fun n ->
  let a = Array.init (n+1) (fun i ->
    if i = 0 then (0, inf) else Scanf.scanf " %d %d" (fun x y -> -x, y)) in
  Array.sort compare a;
  Array.fold_left (fun (s, (x',y')) (x,y) ->
    s + min (x-x') (y-y'), (x,y)) (snd a.(0), a.(0)) a
  |> fst |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

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

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

Find the maximum possible number of players in the game.

Constraints

1 \leq N \leq 10^5

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

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

If i ≠ j, A_i ≠ A_j.

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

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Outputs

Print the maximum possible number of players in the game.

Sample Input 1

3
4 7
2 9
6 2

Sample Output 1

8

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

Sample Input 2

5
1 10
3 6
5 2
4 4
2 8

Sample Output 2

7

Sample Input 3

2
1 1000000000
1000000000 1

Sample Output 3

1000000001


let s = read_line ()
let _ = print_endline @@ if String.length s >= 4 && String.sub s 0 4 = "YAKI" then "Yes" else "No"

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


Scanf.scanf "%d %d %d" (fun n m k ->
    let rec loop_a a =
        let rec loop_b b =
            if b > n then loop_a (a + 1) else
                if a * n + b * m - 2 * a * b = k then true else loop_b (b + 1)
        in
        if a > m then false else
            loop_b 0
    in
    print_endline @@ if loop_a 0 then "Yes" else "No"
)

Score : 200 points

Problem Statement

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

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

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

Constraints

1 \leq N,M \leq 1000

0 \leq K \leq NM

Input

Input is given from Standard Input in the following format:

N M K

Output

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

Sample Input 1

2 2 2

Sample Output 1

Yes

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

Sample Input 2

2 2 1

Sample Output 2

No

Sample Input 3

3 5 8

Sample Output 3

Yes

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

Sample Input 4

7 9 20

Sample Output 4

No


Scanf.scanf "%d %d %d" (fun n m k ->
    let rec loop_a a =
        let rec loop_b b =
            if b = n then loop_a (a + 1) else
                if a * n + b * m - 2 * a * b = k then true else loop_b (b + 1)
        in
        if a = m then false else
            loop_b 0
    in
    print_endline @@ if loop_a 0 then "Yes" else "No"
)


open Printf
open Scanf

let () =
  let n, m, k = scanf "%d %d %d " (fun x y z -> (x, y, z)) in
  let rec loop i j =
    if i > n then "No"
    else if j > m then loop (i+1) 0
    else if m * i + n * j - 2 * i * j = k then "Yes"
    else loop i (j+1) in
  loop 0 0 |> printf "%s\n"


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

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.


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

let slv k xs =
    List.map (fun x -> min x (abs (x-k))) xs
    |> (List.fold_left (+) 0)
    |> ( * ) 2

let rec inp n = match n with
    | 0 -> []
    | _ -> Scanf.scanf "%d " id :: (inp (n-1))

let () =
    slv k (inp n) |> Printf.printf "%d"

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 a, b, c, d, e, f = Scanf.scanf " %d %d %d %d %d %d" @@ fun a b c d e f -> a, b, c, d, e, f
let ws = Array.make (f + 1) false
let ss = Array.make (f + 1) false
let (<@) (w, s) (w2, s2) = (w2 + s2) * s < (w + s) * s2
let ans = ref (f, 0)
let _ =
  for i = 0 to f / 100 do
    for j = 0 to f / 100 do let w = 100 * i * a + 100 * j * b in if w <= f then ws.(w) <- true done done;
  for i = 0 to f do
    for j = 0 to f do if i * c + j * d <= f then ss.(i * c + j * d) <- true done done;
  for i = 0 to f do
    for j = 0 to f do if ws.(i) && ss.(j) && i + j <= f && 100 * j <= i * e then (ans := if !ans <@ (i, j) then i, j else !ans) done done;
  let w, s = !ans in Printf.printf "%d %d\n" (w + s) @@ s

Score : 300 points

Problem Statement

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

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

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

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

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

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

Snuke will make sugar water with the highest possible density.

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

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

Constraints

1 \leq A < B \leq 30

1 \leq C < D \leq 30

1 \leq E \leq 100

100A \leq F \leq 3 000

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

Inputs

Input is given from Standard Input in the following format:

A B C D E F

Outputs

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

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

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

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

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

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

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

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

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934


let kFMax = 3000 in
let kWMax = 30 in
Scanf.scanf " %d %d %d %d %d %d" @@ fun a b c d e f ->
  let ans = ref (0., 0, 0) in
  let water = Array.make (kWMax + 1) false in
  for i = 0 to kWMax do
    for j = 0 to kWMax do
      let w = a * i + b * j in
      if w <= kWMax then water.(w) <- true
    done
  done;
  let sugar = Array.make (kFMax + 1) false in
  for i = 0 to kFMax do
    for j = 0 to kFMax do
      let s = c * i + d * j in
      if s <= kFMax then sugar.(s) <- true
    done
  done;
  for w = 1 to kWMax do
    if water.(w) then
      for s = 0 to kFMax do
        if sugar.(s) then
          let w_s = w * 100 + s in
          if w_s <= f && w * e >= s then
            let c = 100. *. float s /. (float w +. float s) in
            ans := max !ans (c, w_s, s)
      done
  done;
  let _, w_s, s = !ans in
  Printf.printf "%d %d\n" w_s s


open Scanf
open Printf

let flip f x y = f y x

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

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

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

let inf = 20202020202020

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

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

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

  let edges =
    let rec f a b =
      if a >= n then []
      else if b >= n then f (a+1) (a+2)
      else (a, b, mtx.(a).(b)) :: f a (b+1) in
    List.sort (fun (_,_,w0) (_,_,w1) -> w0-w1) @@ f 0 1 in

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

Score : 500 points

Problem Statement

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

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

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

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

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

Constraints

1 \leq N \leq 300

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

A_{i, i} = 0

Inputs

Input is given from Standard Input in the following format:

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

Outputs

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

Sample Input 1

3
0 1 3
1 0 2
3 2 0

Sample Output 1

3

The network below satisfies the condition:

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

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

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

Sample Input 2

3
0 1 3
1 0 1
3 1 0

Sample Output 2

-1

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

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

Sample Input 3

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

Sample Output 3

82

Sample Input 4

3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0

Sample Output 4

3000000000


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

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

Score : 700 points

Problem Statement

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

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

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

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

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

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

Constraints

1 \leq N \leq 1 000

1 \leq P_i \leq i - 1

0 \leq X_i \leq 5 000

Inputs

Input is given from Standard Input in the following format:

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

Outputs

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

Sample Input 1

3
1 1
4 3 2

Sample Output 1

POSSIBLE

For example, the following allocation satisfies the condition:

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

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

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

There are also other possible allocations.

Sample Input 2

3
1 2
1 2 3

Sample Output 2

IMPOSSIBLE

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

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

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

Sample Input 3

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

Sample Output 3

POSSIBLE

Sample Input 4

1

0

Sample Output 4

POSSIBLE


let id x = x
let c1 = Scanf.scanf "%c" id
let c2 = Scanf.scanf "%c\n" id

let ans = if c1='9'||c2='9' then "Yes" else "No"

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

Score : 100 points

Problem Statement

It is September 9 in Japan now.

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

Constraints

10≤N≤99

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

29

Sample Output 1

Yes

The one's digit of 29 is 9.

Sample Input 2

72

Sample Output 2

No

72 does not contain 9.

Sample Input 3

91

Sample Output 3

Yes


(* O(n) *)
open Hashtbl
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let h = create n
let _ =
  Array.iter (fun a -> try let c = find h a in replace h a @@ c + 1 with _ -> add h a 1) a_s;
  fold (fun _ c acc -> acc + if c mod 2 = 0 then 0 else 1) h 0 |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are playing the following game with Joisino.

Initially, you have a blank sheet of paper.

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

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

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

Constraints

1≤N≤100000

1≤A_i≤1000000000(=10^9)

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

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

Sample Input 1

3
6
2
6

Sample Output 1

1

The game proceeds as follows:

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

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

6 is written on the sheet, so erase 6.

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

Sample Input 2

4
2
5
5
2

Sample Output 2

0

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

Sample Input 3

6
12
22
16
22
18
12

Sample Output 3

2


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 select xs f acc =
  let rec select acc trace = function
    | [] -> acc
    | x :: xs -> select (f trace x xs acc) (x :: trace) xs in
  select acc [] xs

let perm n xs f =
  let rec perm trace n xs acc =
    match n, xs with
    | 0, _ -> f trace acc
    | _, [] -> acc
    | _, _ ->
        select xs (fun xs x ys ->
          perm (x :: trace) (n - 1) @@ List.rev_append xs ys) acc in
  perm [] 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" @@
  perm r (Array.to_list rs) (fun (r :: rs) acc ->
    min acc @@
    snd @@
    List.fold_left (fun (r, a) s -> (s, d r s + a)) (r, 0) rs) max_int

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


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 warshall_floyd ( + ) min loop n d =
  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) + loop d.(i).(i) + d.(i).(k))
      done
    done
  done

let () =
  let n, m, r = Scanf.scanf "%d %d %d\n" (fun n m r -> n, m, r) in
  let rs = Array.init r (fun _ -> Scanf.scanf "%d%c" (fun r _ -> r - 1)) 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 = Array.make_matrix n n 100001 in
  for i = 0 to n - 1 do
    d.(i).(i) <- 0
  done;
  Array.iter (fun (a, b, c) ->
    d.(a).(b) <- c;
    d.(b).(a) <- c) abcs;
  warshall_floyd ( + ) min (fun _ -> 0) n d;
  (Array.to_list rs
  |> permutation
  |> List.map (fun (r :: rs) ->
      List.fold_left (fun (r, a) s -> (s, (r, s) :: a)) (r, []) rs
      |> snd
      |> List.map (fun (r, s) -> d.(r).(s))
      |> List.fold_left ( + ) 0)
  |> List.fold_left min max_int
  |> Printf.printf "%d\n")


let x, t = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = max 0 @@ x - t |> Printf.printf "%d\n"

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 f a b = if b>a then 0 else a-b;;
Scanf.scanf "%d %d"
f
|> Printf.printf "%d\n"


open Printf
open Scanf

let id x = x

let s = read_line ()

let () =
  for i = 0 to String.length s - 1 do
    if i mod 2 = 0 then print_char s.[i]
  done;
  print_newline ()

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


let () =
  let s = read_line () in
  print_endline @@ String.init ((String.length s + 1) / 2) (fun i -> s.[2 * i])


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let cs = Array.make 100001 0
let ans = ref 0
let _ = Array.iter (fun a -> cs.(a) <- cs.(a) + 1) a_s;
  for x = 1 to 100000 - 1 do ans := max !ans @@ cs.(x - 1) + cs.(x) + cs.(x + 1) done;
  Printf.printf "%d\n" !ans

Score : 300 points

Problem Statement

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

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

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

Maximize this count by making optimal choices.

Constraints

1≤N≤10^5

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

a_i is an integer.

Input

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

N
a_1 a_2 .. a_N

Output

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

Sample Input 1

7
3 1 4 1 5 9 2

Sample Output 1

4

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

Sample Input 2

10
0 1 2 3 4 5 6 7 8 9

Sample Output 2

3

Sample Input 3

1
99999

Sample Output 3

1


(* O(n) *)
let kMax = 100000
let n = Scanf.scanf " %d" @@ (+) 0
let ns = Array.make (kMax + 10) 0
let ans = ref 0
let _ =
  for i = 0 to n - 1 do
    let a = Scanf.scanf " %d" @@ (+) 0 in
    ns.(a) <- ns.(a) + 1
  done;
  for i = 0 to kMax - 1 do
    ans := max !ans @@ ns.(i) + ns.(i + 1) + ns.(i + 2)
  done;
  Printf.printf "%d\n" !ans


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

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  Array.fold_left (fun m a ->
    IntMap.add a (1 + try IntMap.find a m with Not_found -> 0) m) IntMap.empty as_
  |> (fun m -> IntMap.fold (fun a n m ->
      IntMap.add (a - 1) (n + try IntMap.find (a - 1) m with Not_found -> 0) m
      |> IntMap.add (a + 1) (n + try IntMap.find (a + 1) m with Not_found -> 0)) m m)
  |> IntMap.bindings
  |> List.map snd
  |> List.fold_left max 0
  |> Printf.printf "%d\n"