(* O(n^2) *)
let solve r g b n =
  let rec find_g acc g0 m =
    if g0 * g > m then
      acc
    else
      find_g
        (acc + if (m - g0 * g) mod b = 0 then 1 else 0)
        (g0 + 1)
        m in
  let rec count acc r0 =
    if r0 * r > n then
      acc
    else
      count (find_g acc 0 (n - r0 * r)) (r0 + 1)
  in
    count 0 0

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

let _ =
  match read_ints () with
  | [r; g; b; n] -> solve r g b n |> string_of_int |> print_endline
  | _ -> assert false


open Printf open Scanf
open Array

let split2 s t =
  let ls,lt = String.(length s,length t) in
  if ls<lt then [s]
  else if ls=lt then (
    if s=t then ["";""] else [s]
  ) else (
    let res = Str.split (Str.regexp_string t) s in
    let res = if String.sub s 0 lt = t then ""::res else res in
    let res = if String.sub s (ls-lt) lt = t then
      List.rev @@ ""::List.rev res else res in
    res
  )

let count_substr s t =
  List.length (split2 s t) - 1

let () = scanf " %d" @@ fun n ->
  let arr = init n (fun _ -> scanf " %s" @@ fun s -> s)
  in
  let kba,kbx,kxa,kab = ref 0,ref 0,ref 0,ref 0 in
  iter (fun s ->
    let bx = s.[0] = 'B' in
    let xa = s.[String.length s-1] = 'A' in
    let ba = bx && xa in
    if ba then incr kba
    else if bx then incr kbx
    else if xa then incr kxa;
    kab := !kab + count_substr s "AB"
  ) arr;
  let kba,kbx,kxa,kab = !kba,!kbx,!kxa,!kab in
  print_int @@ kab +
    if kba >= 1 then (
      let pair_ba = kba - 1 in
      let add,kbx =
        if kbx > 0 then 1,kbx-1 else 0,kbx in
      let add,kxa =
        if kxa > 0 then add+1,kxa-1 else add,kxa in
      pair_ba + add + min kbx kxa
    ) else
      min kbx kxa

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

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4

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 Printf open Scanf
open Array

let count_substr s t =
  let ln = String.length in
  init (ln s - ln t + 1) (fun i ->
    if init (ln t) (fun j -> s.[i+j] = t.[j])
    |> fold_left (&&) true then 1 else 0
  ) |> fold_left (+) 0

let () = scanf " %d" @@ fun n ->
  let arr = init n (fun _ -> scanf " %s" @@ fun s -> s)
  in
  let kba,kbx,kxa,kab = ref 0,ref 0,ref 0,ref 0 in
  iter (fun s ->
    let bx = s.[0] = 'B' in
    let xa = s.[String.length s-1] = 'A' in
    let ab = bx && xa in
    if ab then incr kab
    else if bx then incr kbx
    else if xa then incr kxa;
    kab := !kab + count_substr s "AB"
  ) arr;
  let kba,kbx,kxa,kab = !kba,!kbx,!kxa,!kab in
  print_int @@ kab +
    if kba >= 1 then (
      (* B-A^B-A^...^B-A *)
      let pair_ba = kba - 1 in
      (* B-A^B-A^...^B-A ^ B- *)
      let add,kbx =
        if kbx > 0 then 1,kbx-1 else 0,kbx in
      (* -A ^ B-A^B-A^...^B-A*)
      let add,kxa =
        if kxa > 0 then add+1,kxa-1 else add,kxa in
      pair_ba + add + min kbx kxa
    ) else
      (* -A^B- ... -A^B- *)
      min kbx kxa


let a, b, t = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = Printf.printf "%d\n" @@ t / a * b

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


(* O(1) *)
let solve a b t = t / a * b

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

let _ =
  match read_ints () with
  | [a; b; c] -> solve a b c |> string_of_int |> print_endline
  | _ -> ()


let s, b, m = Array.fold_left (fun (s, b, m) x -> (s + abs x, b <> (x < 0), min m (abs x))) (0, false, 1000000000) (Array.init (read_int()) (fun _ -> Scanf.scanf " %d" (fun i -> i))) in print_int (s + if b then -2 * m else 0)

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \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 value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

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


(* O(n) *)
let solve n a_s =
  let abs_s = List.map abs a_s in
  let mi = List.fold_left min max_int abs_s in
  let sum = List.fold_left (+) 0 abs_s in
  if mi = 0 then
    sum
  else
    let neg_count = List.fold_left (fun acc a -> if a < 0 then acc + 1 else acc) 0 a_s in
    if neg_count mod 2 = 0 then
      sum
    else
      sum - mi * 2

let read_ints () = read_line () |> Str.split (Str.regexp " ") |> List.map int_of_string
let _ =
  let n = read_int () in
  read_ints () |> solve n |> string_of_int |> print_endline


let () =
  Scanf.scanf "%d %s %d" @@ fun n s k ->
  Array.init n (fun i -> if s.[i] = s.[k-1] then s.[i] else '*')
  |> Array.iter print_char

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


let solve n = 1

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let s = Scanf.scanf "%s\n" (fun s -> s) in
  let k = Scanf.scanf "%d\n" (fun k -> k) in
  let c = String.get s k in
  for i = 0 to n - 1 do
    let c' = String.get s i in
    print_char @@ if c = c' then c else '*'
  done


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let s = read_line () |> split_string
let () = Printf.printf "%d\n" @@ snd @@ List.fold_left (fun (b, sum) ch -> (b || ch = "#", sum + if b && ch = "#" then 1 else 0)) (false, 0) s

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


open Scanf
open Printf

let (a,b) = sscanf (read_line ()) "%d %d" (fun x y -> (x,y));;

printf "%d\n" (if a > b then a + max (a-1) b else b + max a (b-1))

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let h_max = ref 0 in
  let res = ref 0 in
  for i = 0 to n - 1 do
    let h =
      Scanf.scanf (if i <> n - 1 then "%d " else "%d\n") (fun h -> h) in
    if h >= !h_max then (res := !res + 1; h_max := h);
  done;
  print_int !res

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


(* O(|s|) *)
let s = read_line ()
let ans = ref max_int
let cs = [|'0'; '1'|]
let cnt1, cnt2 = ref 0, ref 0
let _ =
  String.iteri (fun i c -> if c <> cs.(i mod 2) then incr cnt1) s;
  String.iteri (fun i c -> if c = cs.(i mod 2) then incr cnt2) s;
  min !cnt1 !cnt2 |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


type bin = I of int | O of int

let _ =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let prev = ref (I 0) in
  let res = ref [] in
  for i = 0 to n - 1 do
    let d = Scanf.scanf (if i <> n - 1 then "%1d" else "%1d\n") (fun d -> d) in
    if i = 0 then
      begin
        prev := if d = 0 then O 1 else I 1;
      end
    else
      begin
        match !prev, d with
        | (I i), 1 -> prev := I (i+1)
        | (O o), 0 -> prev := O (o+1)
        | (I i), 0 -> (prev := O 1; res := (I i)::!res)
        | (O o), 1 -> (prev := I 1; res := (O o)::!res)
        | _ -> failwith "hoge"
      end
  done;
  let ct_of = function I i -> i | O o -> o in
  let input = Array.of_list (!prev::!res) in
  let l = Array.length input in
  let res = ref 0 in
  let i, j, k' = ref 0, ref 0, ref k in
  let temp = ref 0 in
  while !i < l do
(*    Printf.printf "(i:%d, j:%d, k':%d)" !i !j !k';*)
    let d = input.(!j) in
    let j' = match d with | I _ -> min (!j + 2 * !k') (l - 1) | O _ -> min (!j + 2 * !k' - 1) (l - 1) in
    for p = !j to j' do
      temp := !temp + (ct_of input.(p))
    done;
    j := j';
    res := max !res !temp;
    let i' = match input.(!i) with | I _ -> min (!i+2) (l - 1) | O _ -> min (!i+1) (l - 1) in
    k' := 1;
    for p = !i to i' do
      temp := !temp - (ct_of input.(p))
    done;
    i := i';
    if !i = l - 1 then i := l + 10;
  done;
  !res |> print_int

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


let () =
  Scanf.scanf "%d %d %s" @@ fun n k s ->
  let s = Array.init n (fun i -> i, s.[i]) in
  let t = Array.make 101010 0 in
  let ans, _, _, _, _ =
    Array.fold_left (fun (ans, cur, cs, ti, p) (i, x) ->
      match p, x with
      | '1', '1' -> (max ans (cur+1), cur+1, cs+1, ti, '1')
      | '0', '0' -> (max ans (cur+1), cur+1, cs+1, ti, '0')
      | '0', '1' -> begin
        t.(ti) <- cs;
        (max ans (cur+1), cur+1, 1, ti+1, '1')
      end
      | _ (* 1, 0 *) -> begin
        if ti < k then
          (max ans (cur+1), cur+1, cs+1, ti, '0')
        else
          (max ans (cur+1-t.(ti-k)), cur+1-t.(ti-k), cs+1, ti, '0')
      end) (0,0,0,0,'1') s
  in
  Printf.printf "%d\n" ans


let calc s k =
  if k = 0 then Array.fold_left (fun v (_, x) -> if x = '1' then v+1 else v) 0 s else
  let t = Array.make 101010 0 in
  let ans, _, _, _, _ =
    Array.fold_left (fun (ans, cur, cs, ti, p) (i, x) ->
      match p, x with
      | '1', '1' -> (max ans (cur+1), cur+1, cs+1, ti, '1')
      | '0', '0' -> (max ans (cur+1), cur+1, cs+1, ti, '0')
      | '0', '1' -> begin
        t.(ti) <- cs;
        (max ans (cur+1), cur+1, 1, ti+1, '1')
      end
      | _ (* 1, 0 *) -> begin
        if ti < k then
          (max ans (cur+1), cur+1, cs+1, ti, '0')
        else
          (max ans (cur+1-t.(ti-k)), cur+1-t.(ti-k), cs+1, ti, '0')
      end) (0,0,0,0,'1') s
  in
  ans
let () =
  Scanf.scanf "%d %d %s" @@ fun n k s ->
  let s = Array.init n (fun i -> i, s.[i]) in
  max (calc s k) (calc (Array.map (fun (i, x) -> i, (if x = '0' then '1' else '0')) s) (k-1))
  |> Printf.printf "%d\n"


let () = Scanf.scanf "%d %d %d %d %d %d" @@ fun a b c d e k ->
  print_endline @@
  if e - a <= k then "Yay!" else ":("

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


let () = Printf.printf "%d\n" @@
  Scanf.scanf "%d %d %d %d %d" @@ fun a b c d e ->
  let h, s = List.fold_left (fun (x, s) y -> max x ((10 - y mod 10) mod 10), s + (y + 9) / 10 * 10) (0, 0) [a;b;c;d;e] in
  s - h

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


let n = read_int()
let a = read_int()
let b = read_int()
let c = read_int()
let d = read_int()
let e = read_int()
let l = [a; b; c; d; e]

let f lst n =
  let l_min = List.fold_right min lst max_int in
  if n mod l_min = 0 then (n / l_min) + 4
  else (n / l_min) + 5

let () = print_int (f l n)

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

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


let () = Scanf.scanf "%d %d %d %d %d %d" @@ fun n a b c d e ->
  let m = List.fold_left min max_int [ a; b; c; d; e ] in
  Printf.printf "%d\n" @@ (n + m - 1) / m + 4


Printf.printf "%c\n" @@ match input_char stdin with
| 'A' -> 'T'
| 'T' -> 'A'
| 'C' -> 'G'
| 'G' -> 'C'

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


let helix =
  Scanf.scanf "%c" (fun b ->
  print_endline @@
  if b == 'A' then "T"
  else if b == 'T' then "A"
  else if b == 'G' then "C"
  else "G")
;;


let () = Scanf.scanf "%s" @@ fun s ->
  let ss = Array.init (String.length s) @@ fun i -> String.get s i in
  let f = fun (maximum, prev) i ->
    match (i = 0, ss.(i) = 'A' || ss.(i) = 'T' || ss.(i) = 'C' || ss.(i) = 'G') with
    | (true, true) -> (1, 1)
    | (true, false) -> (0, 0)
    | (false, true) -> (max maximum (prev + 1), prev + 1)
    | (false, false) -> (max maximum 0, 0) in
  let fin_pair = List.fold_left f (0, 0) @@ List.init (String.length s) Fun.id in
  Printf.printf "%d\n" @@ fst fin_pair

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

S is a string of length between 1 and 10 (inclusive).

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


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

let () =
        Str.split (Str.regexp "[B|D|E|F|H|I|J|K|L|M|N|O|P|Q|R|S|U|V|W|X|Y|Z]") (read_line ())
        |> List.max
        |> String.length
        |> Printf.printf "%d\n"


(* O(n) *)
let rec fold_btw f a i n = if i >= n then a else fold_btw f (f a i) (i + 1) n
let fold_int f a n = fold_btw f a 0 n

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

(* O(1) *)
let is_acgt_char = function
| 'A' | 'C' | 'G' | 'T' -> true
| _ -> false

(* O(|s|) *)
let is_acgt_string s = List.for_all is_acgt_char (string_to_chars s)

(* O(|s|^3) *)
let solve s =
  let n = String.length s in
  fold_int
    (fun acc_i i ->
      fold_btw
        (fun acc_j j ->
          let len = j - i in
          if is_acgt_string (String.sub s i len) then
            max acc_j len
          else
            acc_j)
        acc_i
        (i + 1)
        (n + 1))
    0
    n

let _ = read_line () |> solve |> string_of_int |> print_endline


open Printf
open Scanf

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

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

let m = 1_000_000_007L

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

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

let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

let rec max_len m accum = function
  | [] -> max m accum
  | c :: rest when c = 'A' || c = 'C' || c = 'G' || c = 'T' ->
    max_len m (accum+1) rest
  | _ :: rest -> max_len (max m accum) 0 rest

let () =
  let s = read_str () in
  printf "%d\n" (max_len 0 0 @@ explode s)


let solve s n =
  let t = Array.make (n + 1) 0 in
  for i = 0 to n - 1 do
    t.(i+1) <- if String.get s i = 'A' && (i + 1) < n then
                 if String.get s (i + 1) = 'C' then t.(i) + 1 else t.(i)
               else t.(i)
  done;
  fun (i, j) -> t.(j-1) - t.(i-1)

let _ =
  let n, q = Scanf.scanf "%d %d\n" (fun n q -> n, q) in
  let s = Scanf.scanf "%s\n" (fun s -> s) in
  let queries = ref [] in
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d\n" (fun l r -> queries := (l, r)::!queries)
  done;
  let solver = solve s n in
  List.fold_left (fun acc query -> (solver query)::acc) [] !queries
  |> List.iter (fun n -> print_int n; print_endline "")

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


let solve s n =
  let t = Array.make n 0 in
  for i = 0 to n - 2 do
    t.(i+1) <- if (String.sub s i 2) = "AC" then t.(i) + 1 else t.(i)
  done;
  t.(n - 1) <- t.(n - 2);
  fun (i, j) -> t.(j-1) - t.(i-1)

let _ =
  let n, q = Scanf.scanf "%d %d\n" (fun n q -> n, q) in
  let s = Scanf.scanf "%s\n" (fun s -> s) in
  let queries = ref [] in
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d\n" (fun l r -> queries := (l, r)::!queries)
  done;
  let solver = solve s n in
  List.fold_left (fun acc query -> (solver query)::acc) [] !queries
  |> List.iter (fun n -> print_int n; print_endline "")


Scanf.scanf "%d" (fun n ->
    let b = Array.init n (fun _ -> Scanf.scanf " %d" (fun b -> b)) in
    let search b =
        let k = Array.length b in
        let rec loop i =
            if i < 0 then None else
                if b.(i) = i + 1 then Some i else loop (i - 1)
        in
        loop (k - 1)
    in
    let remove b x =
        let k = Array.length b in
        let b2 = Array.make (k - 1) 0 in
        let rec loop i j =
            if i = k then b2 else
                if i = x then loop (i + 1) j else (
                    b2.(j) <- b.(i);
                    loop (i + 1) (j + 1)
                )
        in
        loop 0 0
    in
    let rec loop b i history =
        if i = 0 then history else
            match search b with
            | Some x -> loop (remove b x) (i - 1) ((x + 1) :: history)
            | None -> []
    in
    let k = loop b n [] in
    if k = [] then print_endline "-1" else
        List.iter (Printf.printf "%d\n") k
)

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


let rec dfs ans left bs s n =
  if bs = [] && left = [] then Some ans
  else if s > n then None
  else
    begin
      match bs with
      | [] -> Some ans
      | b::bs ->
         if b < s then None
         else if b = s then
           begin
             match dfs (b::ans)
                     [] (List.fold_left (fun acc l -> l::acc) bs left)
                     1 (n - 1) with
             | None -> dfs ans (b::left) bs (s + 1) n
             | Some ans -> Some ans
           end
         else dfs ans (b::left) bs (s + 1) n
    end

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let bs = Array.make n 0 in
  for i = 0 to n - 1 do
    Scanf.scanf (if i <> n - 1 then "%d " else "%d\n") (fun b -> bs.(i) <- b)
  done;
  dfs [] [] (Array.to_list bs) 1 n
  |> (function | None -> print_int (-1)
               | Some ans -> List.iter (fun n -> print_endline @@ string_of_int n) ans)


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

let rec solve acc = function
  | [] -> acc
  | bs ->
      select bs
      |> List.rev
      |> List.mapi (fun i x -> i, x)
      |> List.rev
      |> List.find (fun (i, (hd, b, tl)) -> i + 1 = b)
      |> (fun (_, (hd, b, tl)) -> solve (b :: acc) (List.rev_append hd tl))
let solve = solve []

let () = Scanf.scanf "%d\n" @@ fun n ->
  let bs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun b -> b in
  try List.iter (Printf.printf "%d\n") @@ solve @@ Array.to_list bs
  with Not_found -> print_endline "-1"


let n = read_int ()
let s = read_line ()
let m = 1_000_000_007
let cs = Array.make 128 0
let _ =
  String.iter (fun c -> cs.(Char.code c) <- cs.(Char.code c) + 1) s;
  Array.fold_left (fun ans c -> ans * (c + 1) mod m) 1 cs - 1 |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


let () = Scanf.scanf "%d %d %d" @@ fun n m c ->
  let bs = Array.to_list @@ Array.init m @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let ass = Array.to_list @@ Array.init n @@ fun _ ->
    Array.to_list @@ Array.init m @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let ans = List.length @@
    List.filter (( < ) 0) @@
    List.map (List.fold_left2 (fun acc b a -> acc + b * a) c bs) ass in
  Printf.printf "%d\n" ans

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


let n, m, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let bs = Array.init m @@ fun _ -> Scanf.scanf " %d" (+) 0
let abss = Array.init n @@ fun _ -> Array.init m @@ fun i -> Scanf.scanf " %d" @@ fun a -> a * bs.(i)
let _ = Array.fold_left (fun ans ab_s -> ans + if Array.fold_left (+) c ab_s > 0 then 1 else 0) 0 abss |> Printf.printf "%d\n"


(* O(min {a, b}) *)
let solve a b k =
  let rec find acc n =
    if acc >= k then
      n + 1
    else
      find (if a mod n = 0 && b mod n = 0 then acc + 1 else acc) (n - 1)
  in
    find 0 (min a b)

let _ = Scanf.scanf "%d %d %d" (fun a b k -> solve a b k) |> string_of_int |> print_endline

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


(* 素集合データ構造 *)
module UnionFind : sig
  type t

  (* 1要素だけを含む集合を作る *)
  val make : unit -> t
  (* 与えられた集合同士が同一かどうか判定する *)
  val equal : t -> t -> bool
  (* 与えられた集合同士を合併する *)
  val unite : t -> t -> unit
  (* 与えられた集合に属する要素の数を求める *)
  val cardinal : t -> int
end = struct
  (* type t = node ref
     and node = Either int t
     みたいなのがやりたくて，OCamlの実行時表現はintとそれ以外を区別できるので
     省メモリのためにこうしている *)
  type t = Obj.t ref

  let make () = ref (Obj.repr 1)

  let rec find uf =
    if Obj.is_int !uf
    then uf
    else begin
      let root = find (Obj.magic !uf) in
      uf := Obj.repr root; root
    end

  let equal uf uf' = find uf == find uf'

  let unite uf uf' =
    let root = find uf in
    let root' = find uf' in
    if root != root' then begin
      let card : int = Obj.magic !root in
      let card' : int = Obj.magic !root' in
      let root, root' =
        if card <= card'
        then root, root'
        else root', root in
      root := Obj.repr (card + card');
      root' := Obj.repr root
    end

  let cardinal uf = Obj.magic @@ ( ! ) @@ find uf
end

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let abs = Array.init m @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> a - 1, b - 1 in
  let uf = Array.init n @@ fun _ -> UnionFind.make () in
  let ans = Array.make (m + 1) (n * (n - 1) / 2) in
  for i = m - 1 downto 0 do
    let (a, b) = abs.(i) in
    ans.(i) <- ans.(i + 1) -
      if UnionFind.equal uf.(a) uf.(b)
      then 0
      else begin
        let n = UnionFind.cardinal uf.(a) in
        let m = UnionFind.cardinal uf.(b) in
        UnionFind.unite uf.(a) uf.(b); n * m
      end
  done;
  for i = 1 to m do
    Printf.printf "%d\n" ans.(i)
  done

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


module UnionFind : sig
  type t
  val make : int -> t
  val find : t -> int -> int
  val size : t -> int -> int
  val unite : t -> int -> int -> unit
  val is_same : t -> int -> int -> bool
end = struct
  type t = { rank: int array; parent: int array; size: int array }

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

  let rec find uf i =
    if uf.parent.(i) = i then i
    else begin
      let j = find uf uf.parent.(i) in
      uf.parent.(i) <- j; j
    end

  let size uf i = uf.size.(find uf i)

  let unite uf i j =
    let x = find uf i in
    let y = find uf j in
    if x = y then ()
    else if uf.rank.(x) < uf.rank.(y) then begin
      uf.parent.(x) <- y;
      uf.size.(y) <- uf.size.(y) + uf.size.(x)
    end
    else begin
      uf.parent.(y) <- x;
      uf.size.(x) <- uf.size.(x) + uf.size.(y);
      if uf.rank.(x) = uf.rank.(y) then uf.rank.(x) <- uf.rank.(y) + 1
    end

  let is_same uf i j = find uf i = find uf j
end

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

let () =
  let ans = Array.make (m + 1) 0 in
  let uf = UnionFind.make n in
  ans.(m) <- (n * (n - 1)) / 2;
  for i = m - 1 downto 0 do
    let (a, b) = ab.(i) in
    if UnionFind.is_same uf a b then
      ans.(i) <- ans.(i + 1)
    else begin
      ans.(i) <- ans.(i + 1) - (UnionFind.size uf a) * (UnionFind.size uf b);
      UnionFind.unite uf a b;
    end
  done;
  for i = 1 to m do
    Printf.printf "%d\n" ans.(i)
  done


(* O(m α(n)) *)
let n, m = Scanf.scanf " %d %d" @@ fun a b -> a, b
let ab_s = Array.init m @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a - 1, b - 1
let ab_s = Array.init m (fun i -> ab_s.(m - 1 - i))
let ps = Array.make n @@ -1
let rec find x =
  if ps.(x) < 0 then x
  else let y = find ps.(x) in ps.(x) <- y; y
let unite x y =
  let x = find x in
  let y = find y in
  if x = y then false
  else
    (if ps.(x) < ps.(y) then (ps.(x) <- ps.(x) + ps.(y); ps.(y) <- x)
    else (ps.(y) <- ps.(y) + ps.(x); ps.(x) <- y);
    true)
let size x = -ps.(find x)
let _ =
  let f acc (a, b) =
    let x, y = size a, size b in
    (List.hd acc - if unite a b then x * y else 0) :: acc in
  Array.sub ab_s 0 @@ m - 1 |> Array.fold_left f [n * (n - 1) / 2] |> List.iter @@ fun v -> Printf.printf "%d\n" v


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

let rec qsort ls =
  if ls = [] then []
  else
    let p, tl = (List.hd ls), (List.tl ls) in
    let left = List.filter ((>=) p) tl in
    let right = List.filter ((<) p) tl in
    (qsort left) @ p::(qsort right)

let (>>=) x f =
  match x with
  | None -> None
  | Some x -> f x

(* TODO: グラフ理論関連の自作ライブラリを実装する
   e.g. 強連結成分分解, graphの行列表現, graphの連結リスト表現, etc...
 *)

module MyIO = struct
  let rec str_of_list acc str_of =function
    | [] -> acc
    | x::[] -> (str_of x) ^ "; " ^ acc
    | x::xs -> str_of_list ((str_of x) ^ "; " ^ acc) str_of xs

  let str_of_list str_of ls = "[" ^ (str_of_list "" str_of (List.rev ls)) ^ "]"

  let str_of_pair str_of (a, b) = "(" ^ (str_of a) ^ ", " ^ (str_of b) ^ ")"

  let read_n_integers_fast n delim =
    let rec inner ct acc =
    if ct >= n then acc
    else
      let i = if ct = n-1 then Scanf.scanf "%d" (fun d -> d)
              else Scanf.scanf ("%d" ^^ delim) (fun d -> d) in
      inner (ct + 1) (i::acc)
  in inner 0 []

  let read_n_integers n delim = List.rev @@ read_n_integers_fast n delim

  let read_bits () =
    let rec inner acc =
      try
        let acc' = (Scanf.scanf "%1d" (fun i -> i::acc)) in
        inner acc'
      with e -> acc
    in List.rev @@ inner []
end

(* O(log n) version of UnionFind *)
module UnionFindInt : sig
  type t_
  type t = t_ array
  val create   : int list -> t
  val root_of  : t -> int -> int
  val unite    : t -> int -> int -> unit
  val is_same  : t -> int -> int -> bool
  val grp_of   : t -> int -> int list
  val len_of   : t -> int -> int
end = struct
  type t_ = {parent : int option; t : int; length: int}
  type t = t_ array
  let create ilist =
    let a = Array.make (List.length ilist) {parent = None; t = 0; length = 1} in
    let rec inner ct = function
      | [] -> a
      | l::ls -> a.(ct) <- {a.(ct) with t = l}; inner (ct + 1) ls
    in inner 0 ilist
  let root_of t i =
    let rec inner acc i =
      match t.(i).parent with
      | None -> List.iter (fun j -> t.(j) <- {t.(j) with parent = Some i; length = t.(i).length}) acc; i
      | Some i' -> inner (i::acc) i'
    in inner [] i
  let is_same t i1 i2 =
    if i1 = i2 then true else let r1, r2 = root_of t i1, root_of t i2 in r1 = r2
  let unite t i1 i2 =
    if is_same t i1 i2 then () else
      let r1, r2 = root_of t i1, root_of t i2 in
      let l' = t.(r1).length + t.(r2).length in
      t.(r2) <- { t.(r2) with parent = Some r1; length = l'};
      t.(r1) <- { t.(r1) with length = l'}
  let grp_of t i = Array.to_list t |> List.filter (fun j -> is_same t i j.t) |> List.map (fun j -> j.t)
  let len_of t i = t.(i).length
end
(********* Myutil ************)

let calc uf islands a b =
  let la, lb = UnionFindInt.len_of uf (UnionFindInt.root_of uf a),
               UnionFindInt.len_of uf (UnionFindInt.root_of uf b) in
  la * lb

let _ =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> (n, m)) in
  let answer = Array.make (m + 1) (n * (n - 1) / 2) in
  let bridge = Array.make m (0, 0) in
  for i=0 to m - 1 do Scanf.scanf "%d %d\n" (fun a b -> bridge.(i) <- (a-1, b-1)) done;
  let islands = range 0 n in
  let uf = UnionFindInt.create islands in
  let buf = ref 0 in
  for i = m - 1 downto 0 do
    let a, b = bridge.(i) in
    (if UnionFindInt.is_same uf a b then ()
     else
       begin
         buf := !buf + (calc uf islands a b);
         UnionFindInt.unite uf a b;
       end);
    answer.(i) <- answer.(i) - !buf
  done;
  for i = 1 to m do Printf.printf "%d\n" answer.(i) done


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

let rec qsort ls =
  if ls = [] then []
  else
    let p, tl = (List.hd ls), (List.tl ls) in
    let left = List.filter ((>=) p) tl in
    let right = List.filter ((<) p) tl in
    (qsort left) @ p::(qsort right)

let (>>=) x f =
  match x with
  | None -> None
  | Some x -> f x

(* TODO: グラフ理論関連の自作ライブラリを実装する
   e.g. 強連結成分分解, graphの行列表現, graphの連結リスト表現, etc...
 *)

module MyIO = struct
  let rec str_of_list acc str_of =function
    | [] -> acc
    | x::[] -> (str_of x) ^ "; " ^ acc
    | x::xs -> str_of_list ((str_of x) ^ "; " ^ acc) str_of xs

  let str_of_list str_of ls = "[" ^ (str_of_list "" str_of (List.rev ls)) ^ "]"

  let str_of_pair str_of (a, b) = "(" ^ (str_of a) ^ ", " ^ (str_of b) ^ ")"

  let read_n_integers_fast n delim =
    let rec inner ct acc =
    if ct >= n then acc
    else
      let i = if ct = n-1 then Scanf.scanf "%d" (fun d -> d)
              else Scanf.scanf ("%d" ^^ delim) (fun d -> d) in
      inner (ct + 1) (i::acc)
  in inner 0 []

  let read_n_integers n delim = List.rev @@ read_n_integers_fast n delim

  let read_bits () =
    let rec inner acc =
      try
        let acc' = (Scanf.scanf "%1d" (fun i -> i::acc)) in
        inner acc'
      with e -> acc
    in List.rev @@ inner []
end

(* O(log n) version of UnionFind *)
module UnionFindInt : sig
  type t_
  type t = t_ array
  val create   : int list -> t
  val root_of  : t -> int -> int
  val unite    : t -> int -> int -> unit
  val is_same  : t -> int -> int -> bool
  val grp_of   : t -> int -> int list
end = struct
  type t_ = {parent : int option; t : int}
  type t = t_ array
  let create ilist =
    let a = Array.make (List.length ilist) {parent = None; t = 0} in
    let rec inner ct = function
      | [] -> a
      | l::ls -> a.(ct) <- {a.(ct) with t = l}; inner (ct + 1) ls
    in inner 0 ilist
  let root_of t i =
    let rec inner acc i =
      match t.(i).parent with
      | None -> List.iter (fun j -> t.(j) <- {t.(j) with parent = Some i}) acc; i
      | Some i' -> inner (i::acc) i'
    in inner [] i
  let is_same t i1 i2 =
    if i1 = i2 then true else let r1, r2 = root_of t i1, root_of t i2 in r1 = r2
  let unite t i1 i2 =
    if is_same t i1 i2 then () else let r1, r2 = root_of t i1, root_of t i2 in t.(r2) <- { t.(r2) with parent = Some r1}
  let grp_of t i = Array.to_list t |> List.filter (fun j -> is_same t i j.t) |> List.map (fun j -> j.t)
end
(********* Myutil ************)

let count uf islands a b =
  List.fold_left (fun (sizea, sizeb) l ->
      if UnionFindInt.is_same uf a l then (sizea + 1, sizeb)
      else if UnionFindInt.is_same uf b l then (sizea, sizeb + 1)
      else (sizea, sizeb)
    ) (0, 0) islands

let solve n edges =
  let islands = range 0 n in
  let uf = UnionFindInt.create islands in
  List.map (fun (a, b) ->
      if UnionFindInt.is_same uf a b then 0
      else
        let la, lb = count uf islands a b in
        UnionFindInt.unite uf a b; la * lb
    ) edges

let _ =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> (n, m)) in
  let edges = ref [] in
  for i=1 to m do
    Scanf.scanf "%d %d\n" (fun a b -> edges := ((a-1, b-1)::!edges));
  done;
  let anslist = solve n !edges |> List.rev in
  ignore @@
    List.fold_left (fun acc l -> Printf.printf "%d\n" (acc + l); (acc + l)) 0 anslist


let rec find x uf =
  if uf.(x) < 0 then x else
  let x' = find uf.(x) uf in
  uf.(x) <- x'; x'
let unite x y uf =
  let x, y = find x uf,find y uf in
  if x <> y then
    if uf.(x) < uf.(y) then ((
      uf.(x) <- uf.(x) + uf.(y);
      uf.(y) <- x
    )) else ((
      uf.(y) <- uf.(x) + uf.(y);
      uf.(x) <- y
    ))
let () =
  Scanf.scanf "%d %d" @@ fun n m ->
  let es = Array.init m (fun _ -> Scanf.scanf " %d %d" (fun x y -> x-1, y-1)) in
  let uf = Array.make n (-1) in
  Array.fold_right (fun (x, y) (v, stk) ->
    let x, y = find x uf, find y uf in
    if x = y then (v, v::stk)
    else ((
      let xc, yc = uf.(x), uf.(y) in
      unite x y uf;
      (v - xc * yc, v::stk)
    ))) es (n*(n-1)/2, [])
  |> snd |> List.iter (Printf.printf "%d\n")


let _ = Scanf.scanf " %s" @@ fun s ->
    print_endline @@ if String.sub s 5 2 < "05" then "Heisei" else "TBD"

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


let () = Scanf.scanf "%d/%d/%d" @@ fun y m d ->
    print_endline @@
        if y > 2019 || m > 4
        then "TBD"
        else "Heisei"


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

    let arr = Array.make 4 0 in

    let calc_cost cost arr =
        let enl k q =
            if k = 0 then 100000 else abs (k - q)
        in
        cost + (enl arr.(0) a) + (enl arr.(1) b) + (enl arr.(2) c)
    in

    let rec loop i c cost min_cost =
        if i = n then min min_cost (calc_cost cost arr) else
            if c = 4 then min_cost else (
                arr.(c) <- arr.(c) + l.(i);
                let newcost = if c = 3 || arr.(c) = l.(i) then cost else cost + 10 in
                let mi = loop (i + 1) 0 newcost min_cost in
                arr.(c) <- arr.(c) - l.(i);
                loop i (c + 1) cost mi
            )
    in
    loop 0 0 0 max_int |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


open Scanf
open Printf

let (n,a,b,c) = sscanf (read_line ()) "%d %d %d %d" (fun n a b c -> (n,a,b,c))
let list =
let rec input_list n l =
match n with
  0 -> l
| x -> input_list (x-1) (sscanf (read_line ()) "%d" (fun x -> x):: l)
in input_list n [];;

let ans = ref 3000;;

let rec loop a_in b_in c_in mp l =
match l with
  [] ->
  if (a_in * b_in * c_in = 0) then 3000
  else
  let tmp = abs(a - a_in) + abs(b - b_in) + abs(c - c_in) + mp - 30 in
  let _ = ans := min !ans tmp in
  (*let _ = printf "%d %d %d\n" a_in b_in c_in in
  let _ = printf "tmp = %d\n" tmp in*)
  tmp
  | x::rest ->
  let a_use = loop (a_in + x) b_in c_in (mp+10) rest in
  let b_use = loop a_in (b_in + x) c_in (mp+10) rest in
  let c_use = loop a_in b_in (c_in + x) (mp+10) rest in
  loop a_in b_in c_in mp rest;;

let _ = loop 0 0 0 0 list in printf ("%d\n") !ans;;


(*
 * forall l r (p : forall n, l < n <= r -> bool),
 *   ( exists m,
 *     l < m <= r /\ forall n H, p n H = true <-> m <= n ) ->
 *   { m |
 *     l < m <= r /\ forall n H, p n H = true <-> m <= n }
 *)
let rec lower_bound l r p =
  if r <= 1 + l
  then r
  else let m = (l + r) / 2 in
       if p m
       then lower_bound l m p
       else lower_bound m r p

(*
 * forall l r (p : forall n, l <= n < r -> bool),
 *   ( exists m,
 *     l <= m < r /\ forall n H, p n H = true <-> n <= m ) ->
 *   { m |
 *     l <= m < r /\ forall n H, p n H = true <-> n <= m }
 *)
let rec upper_bound l r p =
  if r <= 1 + l
  then l
  else let m = (l + r) / 2 in
       if p m
       then upper_bound m r p
       else upper_bound l m p

let () = Scanf.scanf "%d %d %d\n" @@ fun a b q ->
  let ss = Array.make (a + 2) 0 in
  let ts = Array.make (b + 2) 0 in
  ss.(0) <- -123456789012345;
  ss.(a + 1) <- 123456789012345;
  for i = 1 to a do
    Scanf.scanf "%d\n" @@ Array.set ss i
  done;
  ts.(0) <- -123456789012345;
  ts.(b + 1) <- 123456789012345;
  for i = 1 to b do
    Scanf.scanf "%d\n" @@ Array.set ts i
  done;
  for i = 1 to q do
    Scanf.scanf "%d\n" @@ fun x ->
      let ls = upper_bound 0 (a + 2) @@ fun i -> ss.(i) <= x in
      let rs = lower_bound (-1) (a + 1) @@ fun i -> x <= ss.(i) in
      let lt = upper_bound 0 (b + 2) @@ fun i -> ts.(i) <= x in
      let rt = lower_bound (-1) (b + 1) @@ fun i -> x <= ts.(i) in
      Printf.printf "%d\n" @@ List.fold_left min max_int
      [ x - min ss.(ls) ts.(lt);
        max ss.(rs) ts.(rt) - x;
        2 * min ss.(rs) ts.(rt) - x - max ts.(lt) ss.(ls);
        x - 2 * max ts.(lt) ss.(ls) + min ss.(rs) ts.(rt) ]
  done

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


let () = Scanf.scanf "%d %d" @@ fun a b ->
  Printf.printf "%d\n" @@ if b mod a = 0 then a + b else b - a

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


open Printf
open Scanf

let read_int _ = scanf " %d " (fun x -> x)

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

let () =
  let n = read_int () in
  let x::xs = Array.init n read_int |> Array.to_list in
  let res = List.fold_left (fun a v -> gcd a v) x xs in
  printf "%d\n" res

Score : 300 points

Problem Statement

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

Initially, the health of Monster i is A_i.

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

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

A random alive monster attacks another random alive monster.

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

4
2 10 8 40

Sample Output 1

2

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

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000


let rec gcd n m =
  if m = 0 then n
  else gcd m (n mod m)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@ Array.fold_left gcd 0 as_


let rec seq a b = if a > b then [] else a :: seq (a+1) b
let (>>=) x f = List.map f x |> List.concat

let len = 50
let costs = [|0;2;5;5;4;5;6;3;7;6|]

let cmp xs ys =
  let lx = List.fold_left (fun s (x, i) -> s+i) 0 xs in
  let ly = List.fold_left (fun s (y, i) -> s+i) 0 ys in
  if lx <> ly then lx - ly
  else
  let rec f xs ys =
    match xs, ys with
    | [], [] -> 0
    | _::_, [] -> -1
    | [], _::_ -> 1
    | ((x,i)::xs), ((y,j)::ys) ->
        if x <> y then x - y
        else if i <> j then i - j
        else f xs ys
  in f xs ys

let () =
  Scanf.scanf "%d %d" @@ fun n m ->
  let a = Array.init m (fun _ ->
    Scanf.scanf " %d" (fun x -> (costs.(x), -x, x)))
  |> Array.to_list
  |> List.sort compare
  in
  let ca, _, va = List.hd a in
  let la = max 0 (n - len) / ca in
  let ma = la * ca in

  let rec f th = function
    | [] -> if th = 0 then [[]] else []
    | (c, _, x) :: xs ->
        seq 0 (th / c) >>= fun i ->
          List.map (fun y -> (x, i) :: y) (f (th - i * c) xs)
  in

  let be =
    f (n - ma) a |> List.fold_left (fun ans xs ->
      let xs = List.sort (fun x y -> compare y x) xs in
      if cmp ans xs >= 0 then ans else xs) []
  in
  ((va, la) :: be) |> List.sort (fun x y -> compare y x)
  |> List.iter (fun (x, i) -> for n = 1 to i do Printf.printf "%d" x done);
  print_newline ()

Score : 400 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^4

1 \leq M \leq 9

1 \leq A_i \leq 9

A_i are all different.

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

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_M

Output

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

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

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

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

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

Sample Input 3

15 3
5 4 6

Sample Output 3

654


let () =
    let input = Array.init 3 (fun _ -> Scanf.scanf "%d %d\n" (fun a b -> (a, b))) in
    let junc = Array.init 5 (fun _ -> 0) in
    Array.iter (fun (j1, j2) -> junc.(j1) <- junc.(j1) + 1; junc.(j2) <- junc.(j2) + 1) input;
    print_endline @@ if Array.fold_left (fun acc j -> acc || j > 2) false junc
        then "NO"
        else "YES"

Score : 200 points

Problem Statement

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

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

Constraints

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

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

No two roads connect the same pair of towns.

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

Input

Input is given from Standard Input in the following format:

a_1 b_1
a_2 b_2
a_3 b_3

Output

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

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

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

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES


Scanf.scanf " %d %d %d" @@ fun k a b ->
  print_int @@
    if b-a<=2 then k+1
    else
      let q = max 0 ((k-a+1)/2) in
      (b-a-2)*q + k + 1

Score : 400 points

Problem Statement

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

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

Exchange A biscuits to 1 yen.

Exchange 1 yen to B biscuits.

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

Constraints

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

K,A and B are integers.

Input

Input is given from Standard Input in the following format:

K A B

Output

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

Sample Input 1

4 2 6

Sample Output 1

7

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

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

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

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

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

Sample Input 2

7 3 4

Sample Output 2

8

Sample Input 3

314159265 35897932 384626433

Sample Output 3

48518828981938099


open Scanf
open Printf
open Array

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

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

Score : 600 points

Problem Statement

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

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

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

He only changes direction at a point with integer coordinate.

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

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

Put a stone in one of Snuke's ears.

Remove a stone from one of Snuke's ears.

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

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

L
A_1
:
A_L

Output

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

Sample Input 1

4
1
0
2
3

Sample Output 1

1

Assume that Snuke walks as follows:

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

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

Sample Input 2

8
2
0
0
2
1
3
4
1

Sample Output 2

3

Sample Input 3

7
314159265
358979323
846264338
327950288
419716939
937510582
0

Sample Output 3

1


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


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


let () =
  Scanf.scanf "%d" @@ fun l ->
  let a = Array.init (l+1) @@ fun i ->
    if i = 0 then 0
    else Scanf.scanf " %d" ((+) 0)
  in

  let dp = Array.init (l+1) (fun _ -> Array.make (l+1) 0) in

  for i = 1 to l do
    dp.(0).(i) <- dp.(0).(i-1) + a.(i);
  done;

  for i = 1 to l do
    dp.(1).(i) <- min dp.(0).(i) @@
      dp.(1).(i-1) + if a.(i) = 0 then 2 else a.(i) mod 2;
  done;

  for i = 1 to l do
    dp.(2).(i) <- min dp.(1).(i) @@
      dp.(2).(i-1) + (a.(i) + 1) mod 2;
  done;

  for i = 1 to l do
    dp.(3).(i) <- min dp.(2).(i) @@
      dp.(3).(i-1) + if a.(i) = 0 then 2 else a.(i) mod 2;
  done;

  for i = 1 to l do
    dp.(4).(i) <- min dp.(3).(i) @@ dp.(4).(i-1) + a.(i);
  done;

  Printf.printf "%d\n" dp.(4).(l)


Scanf.scanf "%d" (fun n ->
    let l = Array.init n (fun _ -> Scanf.scanf " %d" (fun l -> l)) in
    Array.sort compare l;
    let sum = Array.fold_left (+) 0 l - l.(n - 1) in
    print_endline @@ if sum > l.(n - 1) then "Yes" else "No"
)

Score : 200 points

Problem Statement

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

You can use the following theorem:

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

Constraints

All values in input are integers.

3 \leq N \leq 10

1 \leq L_i \leq 100

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Output

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

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

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

Sample Input 2

4
3 8 4 1

Sample Output 2

No

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

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No


let () =
  let a = Scanf.scanf "%d" (fun n -> Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))) in
  let sum = Array.fold_left (fun acc x -> acc + x ) 0 a in
  let max = Array.fold_left (fun acc x -> if acc > x then acc else x) 0 a in
  let res = sum - max in
  if res > max then print_endline "Yes" else print_endline "No"


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

Score : 100 points

Problem Statement

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

Question 1: Are you subscribing to Newspaper X?

Question 2: Are you subscribing to Newspaper Y?

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

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

Write a program to answer this question.

Constraints

1 \leq N \leq 100

0 \leq A \leq N

0 \leq B \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

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

Sample Input 1

10 3 5

Sample Output 1

3 0

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

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

Sample Input 2

10 7 5

Sample Output 2

5 2

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

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

Sample Input 3

100 100 100

Sample Output 3

100 100


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


let () = Scanf.scanf "%d\n" @@ fun n ->
  let abs = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
  Array.sort (fun (a, b) (a', b') -> compare (a' + b') (a + b)) abs;
  Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 @@ Array.init n @@ fun i ->
    if i mod 2 = 0 then fst abs.(i) else ~- (snd abs.(i))

Score : 400 points

Problem Statement

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

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

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

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

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

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

Sample Input 1

3
10 10
20 20
30 30

Sample Output 1

20

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

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

Sample Input 2

3
20 10
20 20
20 30

Sample Output 2

20

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

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

Sample Input 3

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

Sample Output 3

-2999999997

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


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

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

Score : 500 points

Problem Statement

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

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

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

Restore the original rooted tree.

Notes

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

Constraints

3 \leq N

1 \leq M

N + M \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

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

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

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

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2


let rec fix f x = f (fix f) x;;
Scanf.(Array.(scanf " %d %d" @@ fun n m ->
  let e = make n [] in
  let e_rev = make n [] in
  init (n-1+m) (fun i -> scanf " %d %d" @@ fun u v ->
    let u,v = u-1,v-1 in
    e.(u) <- v :: e.(u);
    e_rev.(v) <- u :: e_rev.(v)
  ) |> ignore;
  let root = fst @@ fold_left (fun (root,i) ls ->
    (if List.length ls = 0 then i else root),i+1
  ) (0,0) e_rev in
  let q = Queue.create () in
  let v_left = init n (fun i -> List.length e_rev.(i)) in
  Queue.add root q;
  let par = make n 0 in
  while not @@ Queue.is_empty q do
    let i = Queue.pop q in
    List.iter (fun j ->
      v_left.(j) <- v_left.(j) - 1;
      if v_left.(j) = 0 then (
        par.(j) <- i + 1;
        Queue.add j q;
      )
    ) e.(i)
  done;
  iter (Printf.printf "%d\n") par
))


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


Scanf.scanf " %d %d %d" @@ fun u v _ -> print_int @@ u*v

Score : 100 points

Problem Statement

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

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

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

Constraints

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

All values in input are integers.

The area of the triangle ABC is an integer.

Input

Input is given from Standard Input in the following format:

|AB| |BC| |CA|

Output

Print the area of the triangle ABC.

Sample Input 1

3 4 5

Sample Output 1

6

This triangle has an area of 6.

Sample Input 2

5 12 13

Sample Output 2

30

This triangle has an area of 30.

Sample Input 3

45 28 53

Sample Output 3

630

This triangle has an area of 630.


Printf.printf "%d\n" (Scanf.scanf "%d %d" (fun a b -> a * b / 2))


Scanf.(Array.(scanf " %d" @@ fun n ->
  let a = make 2000000 false in
  let col n = if n mod 2 = 0 then n/2 else 3*n+1 in
  let rec f i x = if a.(x) then i else
    (a.(x) <- true; f (i+1) (col x))
  in print_int @@ f 1 n))

Score : 200 points

Problem Statement

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

The first term s is given as input.

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

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

Find the minimum integer m that satisfies the following condition:

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

Constraints

1 \leq s \leq 100

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum integer m that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

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

Sample Input 2

7

Sample Output 2

18

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

Sample Input 3

54

Sample Output 3

114


Scanf.scanf "%d" (fun n ->
    let h = Array.init n (fun _ -> Scanf.scanf " %d" (fun h -> h)) in
    let m = Array.fold_left max 0 h in

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

Score : 300 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

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

Sample Input 1

4
1 2 2 1

Sample Output 1

2

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

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

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

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let tds = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun t d -> t - 1, d in
  Array.sort (fun (_, d) (_, d') -> compare d' d) tds;
  let q = Queue.create () in
  let s = Stack.create () in
  let sum = ref 0 in
  let kind = ref 0 in
  let card = Hashtbl.create n in
  for i = 0 to k - 1 do
    sum := !sum + snd tds.(i);
    Hashtbl.replace card (fst tds.(i))
      (1 + try Hashtbl.find card (fst tds.(i)) with Not_found -> 0);
    if Hashtbl.find card (fst tds.(i)) = 1
    then incr kind
    else Stack.push (snd tds.(i)) s
  done;
  for i = k to n - 1 do
    Hashtbl.replace card (fst tds.(i))
      (1 + try Hashtbl.find card (fst tds.(i)) with Not_found -> 0);
    if Hashtbl.find card (fst tds.(i)) = 1 then Queue.push (snd tds.(i)) q
  done;
  let sat = ref (!sum + !kind * !kind) in
  while not (Stack.is_empty s) && not (Queue.is_empty q) do
    sum := !sum + Queue.pop q - Stack.pop s;
    incr kind;
    sat := max !sat (!sum + !kind * !kind)
  done;
  Printf.printf "%d\n" !sat

Score : 400 points

Problem Statement

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

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

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

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

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

Constraints

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

1 \leq t_i \leq N

1 \leq d_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
t_1 d_1
t_2 d_2
.
.
.
t_N d_N

Output

Print the maximum satisfaction that you can obtain.

Sample Input 1

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

Sample Output 1

26

If you eat Sushi 1,2 and 3:

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

The variety bonus is 2*2=4.

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

Sample Input 2

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

Sample Output 2

25

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

Sample Input 3

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

Sample Output 3

4900000016

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


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


let s = read_line ()
let n = String.length s
let _ = for i = 0 to n - 1 do let k = min (n - 1) @@ n + i - 8 in
  if String.(sub s 0 i ^ sub s (k + 1) (n - 1 - k)) = "keyence" then (print_endline "YES"; exit 0) done; print_endline "NO"

Score : 200 points

Problem Statement

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

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

Constraints

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

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES


let s = read_line ()
let n = String.length s
let _ =
  for i = 0 to n - 1 do
    for j = i to n do if String.sub s 0 i ^ String.sub s j (n - j) = "keyence" then (print_endline "YES"; exit 0) done done;
  print_endline "NO"


let () =
  let s = read_line () in
  print_endline @@ if
    List.exists (( = ) "keyence") @@
    List.concat @@ Array.to_list @@ Array.init (String.length s + 1) @@ fun i ->
      Array.to_list @@ Array.init (String.length s + 1) @@ fun j ->
        if j < i then "" else String.sub s 0 i ^ String.sub s j (String.length s - j)
  then "YES" else "NO"


Printf.printf "%d\n" @@ Scanf.scanf "%d %d %d" @@ fun n h w -> (n+1-h)*(n+1-w)

Score : 100 points

Problem Statement

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

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

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

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
H
W

Output

Print the answer.

Sample Input 1

3
2
3

Sample Output 1

2

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

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

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

Sample Input 2

100
1
1

Sample Output 2

10000

Sample Input 3

5
4
2

Sample Output 3

8


Scanf.(scanf " %d %d %d" @@ fun n a b -> Array.(
  init n (fun _ -> scanf " %d" @@ fun v -> v)
  |> fold_left (fun (p,q,r) v ->
    if v<=a then (p+1,q,r)
    else if v<=b then (p,q+1,r)
    else (p,q,r+1)) (0,0,0)
  |> (fun (p,q,r) -> print_int @@ min p (min q r))))

Score : 200 points

Problem Statement

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

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

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

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

Constraints

3 \leq N \leq 100

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

1 \leq A < B < 20

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A B
P_1 P_2 ... P_N

Output

Print the answer.

Sample Input 1

7
5 15
1 10 16 2 7 20 12

Sample Output 1

2

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

Sample Input 2

8
3 8
5 5 5 10 10 10 15 20

Sample Output 2

0

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

Sample Input 3

3
5 6
5 6 10

Sample Output 3

1