open Array
let () =
  let arr = List.concat (to_list (init 3 @@ fun _ -> Scanf.scanf "%d %d %d\n" @@ fun a b c -> [a; b; c])) in
  let n = read_int () in
  let brr = Array.init n @@ fun _ -> Scanf.scanf "%d\n" @@ fun d -> d in
  let check = Array.make_matrix 3 3 false in
  for i = 0 to n-1 do
    let x = brr.(i) in
    if List.mem x arr then List.iteri (fun i a -> if a = x then check.(i / 3).(i mod 3) <- true) arr
  done;
  let ans = ref false in
  for i = 0 to 2 do
    if check.(i).(0) && check.(i).(1) && check.(i).(2) then ans := true (* 横 *)
    else if check.(0).(i) && check.(1).(i) && check.(2).(i) then ans := true (* たて *)
  done;
  if check.(0).(0) && check.(1).(1) && check.(2).(2) then ans := true;
  if check.(0).(2) && check.(1).(1) && check.(2).(0) then ans := true;
  print_endline (if !ans then "Yes" else "No")

Score : 200 points

Problem Statement

We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.

The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the N numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

1 \leq A_{i, j} \leq 100

A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))

1 \leq N \leq 10

1 \leq b_i \leq 100

b_i \neq b_j (i \neq j)

Input

Input is given from Standard Input in the following format:

A_{1, 1} A_{1, 2} A_{1, 3}
A_{2, 1} A_{2, 2} A_{2, 3}
A_{3, 1} A_{3, 2} A_{3, 3}
N
b_1
\vdots
b_N

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.


open Array
let () =
  let arr = List.concat (to_list (init 3 @@ fun _ -> Scanf.scanf "%d %d %d\n" @@ fun a b c -> [a; b; c])) in
  let n = read_int () in
  let check = Array.make_matrix 3 3 false in
  for i = 1 to n do
    Scanf.scanf "%d\n" @@ fun x ->
    if List.mem x arr then List.iteri (fun i a -> if a = x then check.(i / 3).(i mod 3) <- true) arr
  done;
  let ans = ref false in
  for i = 0 to 2 do
    if check.(i).(0) && check.(i).(1) && check.(i).(2) then ans := true (* 横 *)
    else if check.(0).(i) && check.(1).(i) && check.(2).(i) then ans := true (* たて *)
  done;
  if check.(0).(0) && check.(1).(1) && check.(2).(2) then ans := true;
  if check.(0).(2) && check.(1).(1) && check.(2).(0) then ans := true;
  print_endline (if !ans then "Yes" else "No")

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

Submitted source-code file size, in bytes.

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

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


open Batteries
open BatPrintf

let dbg n = Printf.eprintf "%s\n" @@ dump n; n

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

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

let scan_listn n cnv =
  List.range 1 `To n |> List.map (fun _ -> cnv @@ read_line ())

let bsearch_ge arr a =
  let l = Array.length arr in
  match Array.bsearch Int.ord arr a with
  | `All_lower -> l
  | `All_bigger -> 0
  | `Just_after n -> l - n -1
  | `At n -> l - n
  | `Empty -> 0

let rec zip xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys ->
    (x, y) :: zip xs ys

let square x = x * x

let as_ = scan_listn 3
    (fun s -> String.split_on_char ' ' s |> List.Labels.map ~f:Int.of_string)
let n = scan "%d" identity
let bs = scan_listn n Int.of_string
let bingo = [[(0,0);(0,1);(0,2)]; [(1,0); (1,1); (1,2)]; [(2,0);(2,1);(2,2)];
             [(0,0);(1,0);(2,0)]; [(0,1); (1,1); (2,1)]; [(0,2);(1,2);(2,2)];
             [(0,0);(1,1);(2,2)];
             [(2,0);(1,1);(0,2)]]
let () =
  List.mapi
    (fun i a -> List.mapi (fun j b -> if List.exists ((=) b) bs then Some (i,j) else None) a) as_
  |> List.flatten
  |> List.filter Option.is_some
  |> List.map Option.get
  |> (fun l -> List.exists ((=) true) @@ List.map (fun b -> (List.fold_left (fun r c -> List.exists ((=) c) l && r) true b)) bingo)
  |> (fun ans -> printf "%s\n" (if ans then "Yes" else "No"))


let inp_matrix : 'a array -> int -> int -> unit = fun a m n ->
  for i = 0 to m - 1 do
    for j = 0 to n - 1 do
      a.(i).(j) <- Scanf.scanf " %d" (fun x -> x)
    done
  done

let rec inp_loop : (unit -> 'a) -> int -> 'a list = fun inp_fun n ->
  if n = 0 then []
  else
    let x = inp_fun () in
    x :: inp_loop inp_fun (n - 1)

let hole a m n k =
  for i = 0 to m - 1 do
    for j = 0 to n - 1 do
      if a.(i).(j) == k then
        a.(i).(j) <- (-1)
    done
  done

let calc_ans a =
  let ans = ref "No" in
  for i = 0 to 2 do
    if (a.(i).(0) == a.(i).(1) && a.(i).(0) == a.(i).(2)) then ans := "Yes"
  done;
  for j = 0 to 2 do
    if (a.(0).(j) == a.(1).(j) && a.(0).(j) == a.(2).(j)) then ans := "Yes"
  done;
  if (a.(0).(0) == a.(1).(1) && a.(2).(2) == a.(1).(1) || a.(0).(2) == a.(1).(1) && a.(0).(2) == a.(2).(0)) then ans := "Yes";
  !ans

let () =
  let a = Array.make_matrix 3 3 0 in
  let () = inp_matrix a 3 3 in
  let n = Scanf.sscanf (input_line stdin) "%d" (fun a -> a) in
  let l = inp_loop (fun () -> Scanf.sscanf (input_line stdin) "%d" (fun a -> a)) n in
  List.iter  (hole a 3 3) l;
  let ans = calc_ans a
  in
  print_endline ans;


let () =
    let main () =
        let ar = Array.make 101 1024 in
        for i = 0 to 8 do
            Scanf.scanf " %d" (fun a -> ar.(a) <- i)
        done;
        let n = read_int () in
        let rec loop i map =
            if i = 0 then map else
                let b = read_int () in
                loop (i - 1) (map lor ar.(b))
        in
        let m = loop n 0 in
        let l = [
            (1 lsl 0) lor (1 lsl 1) lor (1 lsl 2) ;
            (1 lsl 3) lor (1 lsl 4) lor (1 lsl 5) ;
            (1 lsl 6) lor (1 lsl 7) lor (1 lsl 8) ;
            (1 lsl 0) lor (1 lsl 3) lor (1 lsl 6) ;
            (1 lsl 1) lor (1 lsl 4) lor (1 lsl 7) ;
            (1 lsl 2) lor (1 lsl 5) lor (1 lsl 8) ;
            (1 lsl 0) lor (1 lsl 4) lor (1 lsl 8) ;
            (1 lsl 2) lor (1 lsl 4) lor (1 lsl 6)
        ]
        in
        print_endline (if List.exists (fun a -> a land m = a) l then "Yes" else "No")
    in
    main ()


Scanf.scanf "%d %d %d" (fun n m k ->
    let par = Array.init n (fun i -> i) in
    let size = Array.make n 1 in
    let near = Array.make n 0 in
    let rec root x =
        if par.(x) = x then x else
            let r = root par.(x) in
            let () = par.(x) <- r in
            r
    in
    for i = 1 to m do
        Scanf.scanf " %d %d" (fun a b ->
            let a = a - 1 in let b = b - 1 in
            near.(a) <- near.(a) + 1;
            near.(b) <- near.(b) + 1;
            if root a <> root b then (
                size.(par.(a)) <- size.(par.(a)) + size.(par.(b));
                par.(par.(b)) <- par.(a)
            )
        )
    done;
    for i = 1 to k do
        Scanf.scanf " %d %d" (fun c d ->
            let c = c - 1 in let d = d - 1 in
            if root c = root d then (
                near.(c) <- near.(c) + 1;
                near.(d) <- near.(d) + 1;
            )
        )
    done;
    for i = 0 to n - 1 do
        Printf.printf "%d " (size.(root i) - near.(i) - 1)
    done
)

Score : 400 points

Problem Statement

An SNS has N users - User 1, User 2, \cdots, User N.

Between these N users, there are some relationships - M friendships and K blockships.

For each i = 1, 2, \cdots, M, there is a bidirectional friendship between User A_i and User B_i.

For each i = 1, 2, \cdots, K, there is a bidirectional blockship between User C_i and User D_i.

We define User a to be a friend candidate for User b when all of the following four conditions are satisfied:

a \neq b.

There is not a friendship between User a and User b.

There is not a blockship between User a and User b.

There exists a sequence c_0, c_1, c_2, \cdots, c_L consisting of integers between 1 and N (inclusive) such that c_0 = a, c_L = b, and there is a friendship between User c_i and c_{i+1} for each i = 0, 1, \cdots, L - 1.

For each user i = 1, 2, ... N, how many friend candidates does it have?

Constraints

All values in input are integers.

2 ≤ N ≤ 10^5

0 \leq M \leq 10^5

0 \leq K \leq 10^5

1 \leq A_i, B_i \leq N

A_i \neq B_i

1 \leq C_i, D_i \leq N

C_i \neq D_i

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

(A_i, B_i) \neq (B_j, A_j)

(C_i, D_i) \neq (C_j, D_j) (i \neq j)

(C_i, D_i) \neq (D_j, C_j)

(A_i, B_i) \neq (C_j, D_j)

(A_i, B_i) \neq (D_j, C_j)

Input

Input is given from Standard Input in the following format:

N M K
A_1 B_1
\vdots
A_M B_M
C_1 D_1
\vdots
C_K D_K

Output

Print the answers in order, with space in between.

Sample Input 1

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

Sample Output 1

0 1 0 1

There is a friendship between User 2 and 3, and between 3 and 4. Also, there is no friendship or blockship between User 2 and 4. Thus, User 4 is a friend candidate for User 2.

However, neither User 1 or 3 is a friend candidate for User 2, so User 2 has one friend candidate.

Sample Input 2

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

Sample Output 2

0 0 0 0 0

Everyone is a friend of everyone else and has no friend candidate.

Sample Input 3

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

Sample Output 3

1 3 5 4 3 3 3 3 1 0


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let rec f n = if n < k then 1 else 1 + f (n / k)
let _ = Printf.printf "%d\n" @@ f n

Score : 200 points

Problem Statement

Given is an integer N. Find the number of digits that N has in base K.

Notes

For information on base-K representation, see Positional notation - Wikipedia.

Constraints

All values in input are integers.

1 \leq N \leq 10^9

2 \leq K \leq 10

Input

Input is given from Standard Input in the following format:

N K

Output

Print the number of digits that N has in base K.

Sample Input 1

11 2

Sample Output 1

4

In binary, 11 is represented as 1011.

Sample Input 2

1010101 10

Sample Output 2

7

Sample Input 3

314159265 3

Sample Output 3

18


open Batteries

(* purpose
        ある地点の住所Pと全住人の住所リストから全住人の住所からpにかけての距離の総和を求める
   - detail of data
        P:
                detail: 全住人からの距離が最小と成る点
                condition: 1 <= P <= 100
        住所:
                detail: Pが存在する範囲の始点と終点
                condition: 1 <= N <= 100
                           1 <= M <= 100

   - edge case
        P, 住所:
                - 1
                - 100
        住所リスト:
                - 全要素が同じ値

   amount_of_calculation
        upper_limit:
                O(N)
        actual     :
                O(N)
*)
(* - function type
        solver: int -> int list -> int
*)
let rec solver p lst =
        match lst with
                  [] -> 0
                | first :: rest ->
                        (Int.pow (first - p) 2) + (solver p rest)

(* - purpose
       任意の住所のリストと全住人の住所のリストから住人の住所からリストに含まれる任意の住所までの距離の全住人についての総和の最小値を求める

   - detail of data
        住所:
                detail: 全住人からの距離が最小と成る点
                condition: 1 <= 住所 <= 100

   - edge case
        住所:
                - 1
                - 100
        住所リスト:
                - 全要素が同じ値

   - amount_of_calculation
        upper_limit:
                O(N^2)
        actual     :
                O(N^2)
*)
(* - function type
        solver2: int list -> int list -> int(acm) -> int

   - accumulator(option)
   	minsum: (調べ終わった総和のうち最小の値を格納)
*)
let rec solver2 rlst lst minsum =
        match rlst with
                  [] -> minsum
                | first :: rest ->
                        let sum = solver first lst in (* O(N) *)
                                if sum < minsum then
                                        solver2 rest lst sum
                                else
                                        solver2 rest lst minsum

let test1 = (
        solver2 [] [] max_int
        =
        max_int
)
let test2 = (
        solver2 [1] [1] max_int
        =
        0
)
let test3 = (
        solver2 [1; 2] [1; 2] max_int
        =
        1
        ||
        solver2 [1; 2] [1; 2] max_int
        =
        2
)

let lst =
        Scanf.sscanf (read_line ()) "%d" (
                fun _ ->
                        Str.split (Str.regexp " ") (read_line ())
                        |> List.map int_of_string
        )

let () =
        let maxval = List.max lst in
        let minval = List.min lst in
                solver2 (List.range minval `To maxval) lst max_int
                |> Printf.printf "%d\n"
(*
let rec solver3 n m lst =
        if m = (n + 1) || n = m then
                solver n lst
        else
                let p = (n + m) / 2 in
                let lp = (n + p) / 2 in
                let rp = (p + 1 + m) / 2 in
                let lsum = solver lp lst in
                let rsum = solver rp lst in
                        if lsum < rsum then
                                solver3 n p lst
                        else
                                solver3 (p + 1) m lst

let lst = Scanf.sscanf (read_line ()) "%d" (
        fun _ ->
                Str.split (Str.regexp " ") (read_line ())
                |> List.map int_of_string
)

let () =
        let minlst = List.min lst in
        let maxlst = List.max lst in
                solver3 minlst maxlst lst
                |> Printf.printf "%d\n"
*)

Score : 300 points

Problem Statement

There are N people living on a number line.

The i-th person lives at coordinate X_i.

You are going to hold a meeting that all N people have to attend.

The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to attend the meeting.

Find the minimum total points of stamina the N people have to spend.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq X_i \leq 100

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print the minimum total stamina the N people have to spend.

Sample Input 1

2
1 4

Sample Output 1

5

Assume the meeting is held at coordinate 2. In this case, the first person will spend (1 - 2)^2 points of stamina, and the second person will spend (4 - 2)^2 = 4 points of stamina, for a total of 5 points of stamina. This is the minimum total stamina that the 2 people have to spend.

Note that you can hold the meeting only at an integer coordinate.

Sample Input 2

7
14 14 2 13 56 2 37

Sample Output 2

2354


open Batteries

let rec solver p lst =
        match lst with
                  [] -> 0
                | first :: rest ->
                        ((first - p) * (first - p)) + (solver p rest)

let rec solver2 n m lst =
        if m = (n + 1) then
                solver n lst
        else
                let p = (n + m) / 2 in
                let lp = (n + p) / 2 in
                let rp = (p + 1 + m) / 2 in
                let lsum = solver lp lst in
                let rsum = solver rp lst in
                        if lsum < rsum then
                                solver2 n p lst
                        else
                                solver2 (p + 1) m lst

let lst = Scanf.scanf "%d\n" (
        fun n ->
                Str.split (Str.regexp " ") (read_line ())
                |> List.map int_of_string
)

let () =
        let minlst = List.min lst in
        let maxlst = List.max lst in
                solver2 minlst maxlst lst
                |> Printf.printf "%d\n"


open Batteries
open BatPrintf

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

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

let scan_listn n cnv =
  (0 --^ n) |> Enum.map (fun _ -> (cnv % read_line) ())

let bsearch_ge arr a =
  let l = Array.length arr in
  match Array.bsearch Int.ord arr a with
  | `All_lower -> l
  | `All_bigger -> 0
  | `Just_after n -> l - n -1
  | `At n -> l - n
  | `Empty -> 0

let rec zip xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys ->
    (x, y) :: zip xs ys

let n = scan "%d" identity
let xs = scan_list Int.of_string

let () =
  let half = (List.sum xs) / n in
  let half2 = (List.sum xs) / n + 1 in
  let n = List.sum @@ List.map (fun n -> let k = n - half in k*k) xs in
  let m = List.sum @@ List.map (fun n -> let k = n - half2 in k*k) xs in
  printf "%d" @@ min n m


let m = 1000000007
let n, a, b, dp = Scanf.scanf "%d %d %d" @@ fun n a b -> n, a, b, Array.make (max a b + 1) 0
let ( * ) a b = a * b mod m
let (-) a b = a - b + if a < b then m else 0
let rec f b n = if n <= 0 then 1 else let p = f b (n / 2) in p * p * if n mod 2 = 0 then 1 else b
let _ = dp.(0) <- 1; for i = 1 to max a b do dp.(i) <- dp.(i - 1) * (n - i + 1) * f i (m - 2) done; f 2 n - 1 - dp.(a) - dp.(b) |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

Akari has n kinds of flowers, one of each kind.

She is going to choose one or more of these flowers to make a bouquet.

However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.

How many different bouquets are there that Akari can make?

Find the count modulo (10^9 + 7).

Here, two bouquets are considered different when there is a flower that is used in one of the bouquets but not in the other bouquet.

Constraints

All values in input are integers.

2 \leq n \leq 10^9

1 \leq a < b \leq \textrm{min}(n, 2 \times 10^5)

Input

Input is given from Standard Input in the following format:

n a b

Output

Print the number of bouquets that Akari can make, modulo (10^9 + 7). (If there are no such bouquets, print 0.)

Sample Input 1

4 1 3

Sample Output 1

7

In this case, Akari can choose 2 or 4 flowers to make the bouquet.

There are 6 ways to choose 2 out of the 4 flowers, and 1 way to choose 4, so there are a total of 7 different bouquets that Akari can make.

Sample Input 2

1000000000 141421 173205

Sample Output 2

34076506

Print the count modulo (10^9 + 7).


let m = 1000000007
let ( +^ ) x y = (x + y) mod m
let ( -^ ) x y = x +^ (m - y)
let ( *^ ) x y = (x * y) mod m

let rec power ( * ) e m n =
  if n <= 0 then e
  else power ( * ) (if n land 1 = 0 then e else m * e) (m * m) (n lsr 1)

let perm n k =
  Array.fold_left ( *^ ) 1 @@
  Array.init k @@ fun i -> (i + n - k + 1) mod m
let comb n k = power ( *^ ) (perm n k) (perm k k) (m - 2)

let () = Scanf.scanf "%d %d" @@ fun n k ->
  let perm_n = Array.make (min n k + 1) 1 in
  let perm_n1 = Array.make (min n k + 1) 1 in
  let perm_kk = Array.make (min n k + 1) 1 in
  for i = 0 to min n k - 1 do
    perm_n.(i + 1) <- (n - i) mod m *^ perm_n.(i);
    perm_n1.(i + 1) <- (n - i - 1) mod m *^ perm_n1.(i);
    perm_kk.(i + 1) <- (i + 1) *^ perm_kk.(i)
  done;
  let combn k = power ( *^ ) perm_n.(k) perm_kk.(k) (m - 2) in
  let combn1 k = power ( *^ ) perm_n1.(k) perm_kk.(k) (m - 2) in
  Printf.printf "%d\n" @@
  Array.fold_left ( +^ ) 0 @@
  Array.init (min n k + 1) @@ fun i -> combn i *^ combn1 i

Score : 500 points

Problem Statement

There is a building with n rooms, numbered 1 to n.

We can move from any room to any other room in the building.

Let us call the following event a move: a person in some room i goes to another room j~ (i \neq j).

Initially, there was one person in each room in the building.

After that, we know that there were exactly k moves happened up to now.

We are interested in the number of people in each of the n rooms now. How many combinations of numbers of people in the n rooms are possible?

Find the count modulo (10^9 + 7).

Constraints

All values in input are integers.

3 \leq n \leq 2 \times 10^5

2 \leq k \leq 10^9

Input

Input is given from Standard Input in the following format:

n k

Output

Print the number of possible combinations of numbers of people in the n rooms now, modulo (10^9 + 7).

Sample Input 1

3 2

Sample Output 1

10

Let c_1, c_2, and c_3 be the number of people in Room 1, 2, and 3 now, respectively. There are 10 possible combination of (c_1, c_2, c_3):

(0, 0, 3)

(0, 1, 2)

(0, 2, 1)

(0, 3, 0)

(1, 0, 2)

(1, 1, 1)

(1, 2, 0)

(2, 0, 1)

(2, 1, 0)

(3, 0, 0)

For example, (c_1, c_2, c_3) will be (0, 1, 2) if the person in Room 1 goes to Room 2 and then one of the persons in Room 2 goes to Room 3.

Sample Input 2

200000 1000000000

Sample Output 2

607923868

Print the count modulo (10^9 + 7).

Sample Input 3

15 6

Sample Output 3

22583772


open Batteries
open BatPrintf

let scan fmt f =
  BatScanf.sscanf (read_line ()) fmt f

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

let rec zip xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys ->
    (x, y) :: zip xs ys

let n = scan "%d" identity
let a = scan_list Int.of_string

let () =
  BatList.filter (fun x -> x mod 2 = 0) a
  |> BatList.for_all (fun x -> x mod 3 = 0 || x mod 5 = 0)
  |> (fun b -> if b then "APPROVED" else "DENIED")
  |> printf "%s\n"

Score: 200 points

Problem Statement

You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.

According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:

All even numbers written on the document are divisible by 3 or 5.

If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

Notes

The condition in the statement can be rephrased as "If x is an even number written on the document, x is divisible by 3 or 5".
Here "if" and "or" are logical terms.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

Sample Input 1

5
6 7 9 10 31

Sample Output 1

APPROVED

The even numbers written on the document are 6 and 10.

All of them are divisible by 3 or 5, so the immigrant should be allowed entry.

Sample Input 2

3
28 27 24

Sample Output 2

DENIED

28 violates the condition, so the immigrant should not be allowed entry.


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  print_endline @@
  if List.for_all (fun a -> a mod 2 = 1 || a mod 3 = 0 || a mod 5 = 0) @@ Array.to_list as_
  then "APPROVED" else "DENIED"


open Hashtbl
let h, m = create 100100, ref 1
let _ = for _ = 1 to read_int () do let s = read_line () in replace h s @@ try let c = find h s + 1 in m := max !m c; c with _ -> 1 done; List.(fold (fun s c a -> if c = !m then s :: a else a) h [] |> sort compare |> iter print_endline)

Score: 300 points

Problem Statement

We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

S_i (1 \leq i \leq N) are strings consisting of lowercase English letters.

The length of S_i (1 \leq i \leq N) is between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi


open Batteries
open BatPrintf

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

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

let scan_listn n cnv =
  (0 --^ n) /@ (fun _ -> (cnv % read_line) ())

let rec zip xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys ->
    (x, y) :: zip xs ys

let n = scan "%d" identity
let s = scan_listn n identity

module SMap = Map.Make (struct
    type t = string
    let compare = String.IString.compare
  end)

let () =
  let map = fold (fun m k -> SMap.modify_def 0 k succ m) SMap.empty s in
  let m = SMap.fold (fun _ v m -> if v > m then v else m) map 0 in
  SMap.filter (fun _ n -> n = m) map
  |> List.of_enum % SMap.keys
  |> String.concat "\n" % List.sort String.compare
  |> printf "%s\n"


module StringMap = Map.Make (String)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let ss = Array.init n @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  List.iter print_endline @@
  List.rev @@
  fst @@
  List.fold_left (fun (ss, n) (s, m) ->
    if n < m
    then ([s], m)
    else if n = m then (s :: ss, n)
    else (ss, n)) ([], 0) @@
  StringMap.bindings @@
  Array.fold_left (fun m s ->
    StringMap.add s (1 + try StringMap.find s m with Not_found -> 0) m) StringMap.empty ss


module M = Map.Make (struct type t = string let compare = compare end)

let () =
    let n = read_int () in
    let rec loop i map =
        if i = n then map else
            let s = read_line () in
            let map = M.add s (1 + try M.find s map with _ -> 0) map in
            loop (i + 1) map
    in
    let map = loop 0 M.empty in
    let (_, l) = M.fold (fun key v (mx, mxl) ->
        if v > mx then (v, [ key ]) else
            if v = mx then (v, key :: mxl) else (mx, mxl)) map (0, [])
    in
    List.sort compare l |> List.iter print_endline


Scanf.scanf "%s %s" (fun s t ->
    Scanf.scanf " %d %d" (fun a b ->
        Scanf.scanf " %s" (fun u ->
            let a, b = if s = u then (a - 1, b) else (a, b - 1) in
            Printf.printf "%d %d\n" a b
        )
    )
)

Score : 100 points

Problem Statement

We have A balls with the string S written on each of them and B balls with the string T written on each of them.

From these balls, Takahashi chooses one with the string U written on it and throws it away.

Find the number of balls with the string S and balls with the string T that we have now.

Constraints

S, T, and U are strings consisting of lowercase English letters.

The lengths of S and T are each between 1 and 10 (inclusive).

S \not= T

S=U or T=U.

1 \leq A,B \leq 10

A and B are integers.

Input

Input is given from Standard Input in the following format:

S T
A B
U

Output

Print the answer, with space in between.

Sample Input 1

red blue
3 4
red

Sample Output 1

2 4

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string S and four balls with the string T.

Sample Input 2

red blue
5 5
blue

Sample Output 2

5 4

Takahashi chose a ball with blue written on it and threw it away.
Now we have five balls with the string S and four balls with the string T.


open Batteries
let n = read_int ()
let a = read_line () |> String.split_on_char ' ' |> List.sort compare

let _ =
  let rec loop lst =
    match lst with
    | [] -> "YES"
    | first :: second :: rest -> if first = second then "NO" else loop (second :: rest)
    | first :: rest -> loop rest
  in loop a |> print_endline

Score : 300 points

Problem Statement

Given is a sequence of integers A_1, A_2, ..., A_N.
If its elements are pairwise distinct, print YES; otherwise, print NO.

Constraints

2 ≤ N ≤ 200000

1 ≤ A_i ≤ 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 ... A_N

Output

If the elements of the sequence are pairwise distinct, print YES; otherwise, print NO.

Sample Input 1

5
2 6 1 4 5

Sample Output 1

YES

The elements are pairwise distinct.

Sample Input 2

6
4 1 3 1 6 2

Sample Output 2

NO

The second and fourth elements are identical.

Sample Input 3

2
10000000 10000000

Sample Output 3

NO


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  print_endline @@
  if
    ( = ) n @@
    List.length @@
    List.sort_uniq compare @@
    Array.to_list as_
  then "YES"
  else "NO"


let () =
    let n = read_int () in
    let arr = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    Array.sort compare arr;
    let rec loop i prev =
        if i = n then "YES" else
            if arr.(i) = prev then "NO" else loop (i + 1) arr.(i)
    in
    loop 1 arr.(0) |>  print_endline


Scanf.scanf "%d %d" (fun h a -> let r = (h + a - 1) / a in Printf.printf "%d\n" r)

Score : 100 points

Problem Statement

Serval is fighting with a monster.

The health of the monster is H.

In one attack, Serval can decrease the monster's health by A.
There is no other way to decrease the monster's health.

Serval wins when the monster's health becomes 0 or below.

Find the number of attacks Serval needs to make before winning.

Constraints

1 \leq H \leq 10^4

1 \leq A \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H A

Output

Print the number of attacks Serval needs to make before winning.

Sample Input 1

10 4

Sample Output 1

3

After one attack, the monster's health will be 6.

After two attacks, the monster's health will be 2.

After three attacks, the monster's health will be -2.

Thus, Serval needs to make three attacks to win.

Sample Input 2

1 10000

Sample Output 2

1

Sample Input 3

10000 1

Sample Output 3

10000


let () =
  Scanf.scanf "%d %d\n" @@ fun h n ->
  let arr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  Printf.printf "%s\n" (if h <= Array.fold_left (+) 0 arr then "Yes" else "No")

Score : 200 points

Problem Statement

Raccoon is fighting with a monster.

The health of the monster is H.

Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i.
There is no other way to decrease the monster's health.

Raccoon wins when the monster's health becomes 0 or below.

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Constraints

1 \leq H \leq 10^9

1 \leq N \leq 10^5

1 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 A_2 ... A_N

Output

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Sample Input 1

10 3
4 5 6

Sample Output 1

Yes

The monster's health will become 0 or below after, for example, using the second and third moves.

Sample Input 2

20 3
4 5 6

Sample Output 2

No

Sample Input 3

210 5
31 41 59 26 53

Sample Output 3

Yes

Sample Input 4

211 5
31 41 59 26 53

Sample Output 4

No


let () = Scanf.scanf "%d %d\n" @@ fun h n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  print_endline @@
  if h <= Array.fold_left ( + ) 0 as_
  then "Yes"
  else "No"


let () =
  Scanf.scanf "%d %d\n" @@ fun n k ->
  let hrr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  let () = Array.fast_sort (fun x y -> y-x) hrr in
  let all = Array.fold_left (+) 0 hrr in
  let sum = ref 0 in
  if n > k then
    for i = 0 to k - 1 do
      sum := !sum + hrr.(i)
    done;
  Printf.printf "%d\n" (if n <= k then 0 else all - !sum)

Score : 300 points

Problem Statement

Fennec is fighting with N monsters.

The health of the i-th monster is H_i.

Fennec can do the following two actions:

Attack: Fennec chooses one monster. That monster's health will decrease by 1.

Special Move: Fennec chooses one monster. That monster's health will become 0.

There is no way other than Attack and Special Move to decrease the monsters' health.

Fennec wins when all the monsters' healths become 0 or below.

Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most K times.

Constraints

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

0 \leq K \leq 2 \times 10^5

1 \leq H_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
H_1 ... H_N

Output

Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

Sample Input 1

3 1
4 1 5

Sample Output 1

5

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

Sample Input 2

8 9
7 9 3 2 3 8 4 6

Sample Output 2

0

She can use Special Move on all the monsters.

Sample Input 3

3 0
1000000000 1000000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.


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

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

let rec f h =
        if h = 1 then
                1
        else
                2 * (f (h / 2)) + 1

let () =
        f h
        |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

Caracal is fighting with a monster.

The health of the monster is H.

Caracal can attack by choosing one monster. When a monster is attacked, depending on that monster's health, the following happens:

If the monster's health is 1, it drops to 0.

If the monster's health, X, is greater than 1, that monster disappears. Then, two new monsters appear, each with the health of \lfloor X/2 \rfloor.

(\lfloor r \rfloor denotes the greatest integer not exceeding r.)

Caracal wins when the healths of all existing monsters become 0 or below.

Find the minimum number of attacks Caracal needs to make before winning.

Constraints

1 \leq H \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H

Output

Find the minimum number of attacks Caracal needs to make before winning.

Sample Input 1

2

Sample Output 1

3

When Caracal attacks the initial monster, it disappears, and two monsters appear, each with the health of 1.

Then, Caracal can attack each of these new monsters once and win with a total of three attacks.

Sample Input 2

4

Sample Output 2

7

Sample Input 3

1000000000000

Sample Output 3

1099511627775


Scanf.scanf "%d" (fun h ->
    let rec loop h k acc =
        if h = 0 then Printf.printf "%d\n" acc else
            loop (h / 2) (k * 2) (acc + k)
    in
    loop h 1 0
)


let h, dp, ab_s = Scanf.(scanf "%d %d" @@ fun h n -> Array.(h, make (h + 1) (1 lsl 40), init n @@ fun _ -> scanf " %d %d" @@ fun a b -> a, b))
let _ = for i = 1 to h do Array.iter (fun (a, b) -> dp.(i) <- min dp.(i) @@ if a >= i then b else dp.(i - a) + b) ab_s done; Printf.printf "%d\n" @@ dp.(h)

Score : 500 points

Problem Statement

Ibis is fighting with a monster.

The health of the monster is H.

Ibis can cast N kinds of spells. Casting the i-th spell decreases the monster's health by A_i, at the cost of B_i Magic Points.

The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.

Ibis wins when the health of the monster becomes 0 or below.

Find the minimum total Magic Points that have to be consumed before winning.

Constraints

1 \leq H \leq 10^4

1 \leq N \leq 10^3

1 \leq A_i \leq 10^4

1 \leq B_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H N
A_1 B_1
:
A_N B_N

Output

Print the minimum total Magic Points that have to be consumed before winning.

Sample Input 1

9 3
8 3
4 2
2 1

Sample Output 1

4

First, let us cast the first spell to decrease the monster's health by 8, at the cost of 3 Magic Points. The monster's health is now 1.

Then, cast the third spell to decrease the monster's health by 2, at the cost of 1 Magic Point. The monster's health is now -1.

In this way, we can win at the total cost of 4 Magic Points.

Sample Input 2

100 6
1 1
2 3
3 9
4 27
5 81
6 243

Sample Output 2

100

It is optimal to cast the first spell 100 times.

Sample Input 3

9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461

Sample Output 3

139815


let () =
  Scanf.scanf "%d %d\n" @@ fun n m ->
  Printf.printf "%s\n" (if n = m then "Yes" else "No")

Score : 100 points

Problem Statement

Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A.

The problem has N test cases, all of which must be passed to get an AC verdict.

Takahashi's submission has passed M cases out of the N test cases.

Determine whether Takahashi's submission gets an AC.

Constraints

1 \leq N \leq 100

0 \leq M \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

If Takahashi's submission gets an AC, print Yes; otherwise, print No.

Sample Input 1

3 3

Sample Output 1

Yes

All three test cases have been passed, so his submission gets an AC.

Sample Input 2

3 2

Sample Output 2

No

Only two out of the three test cases have been passed, so his submission does not get an AC.

Sample Input 3

1 1

Sample Output 3

Yes


let () =
  let rec makeN n m = if m = 0 then "" else n ^ (makeN n (m-1)) in
  let ios = int_of_string in
  Scanf.scanf "%s %s\n" @@ fun a b ->
  Printf.printf "%d\n" @@ (if a < b then (ios (makeN a (ios(b)))) else (ios (makeN b (ios(a)))))

Score : 200 points

Problem Statement

Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?

Constraints

1 \leq a \leq 9

1 \leq b \leq 9

a and b are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)

Sample Input 1

4 3

Sample Output 1

3333

We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.

Sample Input 2

7 7

Sample Output 2

7777777


let rec fix f x = f (fix f) x
let () =
  Scanf.scanf "%d" @@ fun n ->
  let ad = Array.init 10 (fun _ -> Array.make 10 0) in
  for i = 1 to n do
    let d = fix (fun f x -> if x < 10 then x else f (x/10)) i in
    ad.(i mod 10).(d) <- ad.(i mod 10).(d) + 1;
  done;

  fix (fun f ans i j ->
    if i > 9 then ans
    else if j > 9 then f ans (i+1) 1
    else f (ans + ad.(i).(j) * ad.(j).(i)) i (j+1)) 0 1 1
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

Given is a positive integer N.

Find the number of pairs (A, B) of positive integers not greater than N that satisfy the following condition:

When A and B are written in base ten without leading zeros, the last digit of A is equal to the first digit of B, and the first digit of A is equal to the last digit of B.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

25

Sample Output 1

17

The following 17 pairs satisfy the condition: (1,1), (1,11), (2,2), (2,22), (3,3), (4,4), (5,5), (6,6), (7,7), (8,8), (9,9), (11,1), (11,11), (12,21), (21,12), (22,2), and (22,22).

Sample Input 2

1

Sample Output 2

1

Sample Input 3

100

Sample Output 3

108

Sample Input 4

2020

Sample Output 4

40812

Sample Input 5

200000

Sample Output 5

400000008


let () =
    let main () =
        let n, k, s = Scanf.scanf "%d %d %d" (fun n k s -> n, k ,s) in
        if s > n - k then (
            for i = 1 to k do Printf.printf "%d " s done;
            for i = k + 1 to n do Printf.printf "1 " done;
        ) else (
            for i = 1 to k do Printf.printf "%d " s done;
            for i = k + 1 to n do Printf.printf "100000000 " done;
        );
        print_newline ()
    in
    main ()

Score : 400 points

Problem Statement

Given are three integers N, K, and S.

Find a sequence A_1, A_2, ..., A_N of N integers between 1 and 10^9 (inclusive) that satisfies the condition below.
We can prove that, under the conditions in Constraints, such a sequence always exists.

There are exactly K pairs (l, r) of integers such that 1 \leq l \leq r \leq N and A_l + A_{l + 1} + \cdots + A_r = S.

Constraints

1 \leq N \leq 10^5

0 \leq K \leq N

1 \leq S \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K S

Output

Print a sequence satisfying the condition, in the following format:

A_1 A_2 ... A_N

Sample Input 1

4 2 3

Sample Output 1

1 2 3 4

Two pairs (l, r) = (1, 2) and (3, 3) satisfy the condition in the statement.

Sample Input 2

5 3 100

Sample Output 2

50 50 50 30 70


let () = Scanf.scanf "%d %d %d" @@ fun n k s ->
  for i = 1 to k do
    Printf.printf "%d " s
  done;
  for i = k + 1 to n do
    Printf.printf "%d " @@
    if n < s then 1 else s + 1
  done;
  print_newline ()


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let (h, w) = Scanf.sscanf (read_line ()) "%d %d" @@ fun h w -> (h, w)
let s = Array.init h @@ fun _ -> read_line () |> split_string |> Array.of_list

let rec start i j = if s.(i).(j) = "." then (i, j) else if j = w - 1 then start (i + 1) 0 else start i (j + 1)
let (si, sj) = start 0 0

let walk i j arr =
  let que = Queue.create () in
  Queue.add (i, j) que;
  while not (Queue.is_empty que) do
    let (i, j) = Queue.pop que in
    List.iter (fun (di, dj) ->
      if 0 <= di && di < h && 0 <= dj && dj < w && s.(di).(dj) = "."  && arr.(di).(dj) = -1 then begin
        arr.(di).(dj) <- arr.(i).(j) + 1;
        Queue.add (di, dj) que
      end
    ) [(i - 1, j); (i + 1, j); (i, j - 1); (i, j + 1)]
  done

let f arr =
  let m = ref 0 in
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do
      m := max !m arr.(i).(j)
    done
  done;
  !m

let () =
  let ans = ref 0 in
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do
      if s.(i).(j) = "." then begin
        let arr = Array.init h @@ fun _ -> Array.make w (-1) in
        arr.(i).(j) <- 0;
        walk i j arr;
        ans := max !ans (f arr)
      end
    done
  done;
  Printf.printf "%d\n" !ans

Score : 400 points

Problem Statement

Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.

The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is #, and a "road" square if S_{ij} is ..

From a road square, you can move to a horizontally or vertically adjacent road square.

You cannot move out of the maze, move to a wall square, or move diagonally.

Takahashi will choose a starting square and a goal square, which can be any road squares, and give the maze to Aoki.

Aoki will then travel from the starting square to the goal square, in the minimum number of moves required.

In this situation, find the maximum possible number of moves Aoki has to make.

Constraints

1 \leq H,W \leq 20

S_{ij} is . or #.

S contains at least two occurrences of ..

Any road square can be reached from any road square in zero or more moves.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible number of moves Aoki has to make.

Sample Input 1

3 3
...
...
...

Sample Output 1

4

If Takahashi chooses the top-left square as the starting square and the bottom-right square as the goal square, Aoki has to make four moves.

Sample Input 2

3 5
...#.
.#.#.
.#...

Sample Output 2

10

If Takahashi chooses the bottom-left square as the starting square and the top-right square as the goal square, Aoki has to make ten moves.


open Queue
let ans, q, h, w, ss = Scanf.(scanf "%d %d" @@ fun h w -> ref 0, create (), h, w, Array.init h @@ fun _ -> scanf " %s" @@ fun s -> s)
let f sy sx = let ds, m = Array.make_matrix h w ~-1, ref 0 in push (sy, sx) q; ds.(sy).(sx) <- 0;
  while not @@ is_empty q do let y0, x0 = pop q in List.iter (fun (dy, dx) -> let y, x = y0 + dy, x0 + dx in if 0 <= y && y < h && 0 <= x && x < w && ds.(y).(x) = -1 && ss.(y).[x] = '.' then (push (y, x) q; ds.(y).(x) <- ds.(y0).(x0) + 1; m := max !m ds.(y).(x))) [-1, 0; 0, -1; 1, 0; 0, 1] done; !m
let _ = for sy = 0 to h - 1 do for sx = 0 to w - 1 do if ss.(sy).[sx] = '.' then ans := max !ans (f sy sx) done done; Printf.printf "%d\n" !ans


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

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

(* 距離だけ欲しい場合 *)
module G = DirectedGraph (struct
  type t = int
  type edge = unit
  let nil = 0
  let snoc t _ = t + 1
end)

let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ss = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let d =
    Array.init h @@ fun i ->
      Array.init w @@ fun j ->
        let d =
          G.bfs (h * w) (fun (i, j) ->
            [(i - 1, j); (i + 1, j); (i, j - 1); (i, j + 1)]
            |> List.filter (fun (i, j) -> try ss.(i).[j] = '.' with _ -> false)
            |> List.map (fun v -> (v, ()))) (i, j) in
        Array.init h @@ fun i ->
          Array.init w @@ fun j -> d (i, j) in
  Printf.printf "%d\n" @@
  Array.fold_left (Array.fold_left (Array.fold_left (Array.fold_left (fun ans -> function None -> ans | Some d -> max d ans)))) min_int d


let () =
    let main () =
        let h, w = Scanf.sscanf (read_line ()) "%d %d" (fun h w -> h, w) in
        let s = Array.init h (fun _ -> read_line ()) in
        let dfs x y =
            let m = Array.make_matrix h w (-1) in
            let rec loop depth next = function
                | [] -> if next = [] then depth else loop (depth + 1) [] next
                | (xx, yy) :: tl ->
                        let () = m.(yy).(xx) <- depth in
                        let next = if xx > 0     && m.(yy).(xx - 1) < 0 && s.(yy).[xx-1] = '.' then (xx-1, yy) :: next else next in
                        let next = if xx < w - 1 && m.(yy).(xx + 1) < 0 && s.(yy).[xx+1] = '.' then (xx+1, yy) :: next else next in
                        let next = if yy > 0     && m.(yy - 1).(xx) < 0 && s.(yy-1).[xx] = '.' then (xx, yy-1) :: next else next in
                        let next = if yy < h - 1 && m.(yy + 1).(xx) < 0 && s.(yy+1).[xx] = '.' then (xx, yy+1) :: next else next in
                        loop depth next tl
            in
            if s.(y).[x] = '.' then loop 0 [] [ x, y ] else 0
        in
        let rec loop_h y acc =
            let rec loop_w x acc =
                if x = w then acc else loop_w (x + 1) (max acc (dfs x y))
            in
            if y = h then acc else loop_h (y + 1) (loop_w 0 acc)
        in
        loop_h 0 0 |> Printf.printf "%d\n"
    in
    main ()


let coins k x =
  if k * 500 >= x then "Yes" else "No"

let k, x = Scanf.sscanf (read_line ()) "%d %d" (fun k x -> (k, x))
let () = Printf.printf "%s\n" (coins k x)

Score : 100 points

Problem Statement

Takahashi has K 500-yen coins. (Yen is the currency of Japan.)
If these coins add up to X yen or more, print Yes; otherwise, print No.

Constraints

1 \leq K \leq 100

1 \leq X \leq 10^5

Input

Input is given from Standard Input in the following format:

K X

Output

If the coins add up to X yen or more, print Yes; otherwise, print No.

Sample Input 1

2 900

Sample Output 1

Yes

Two 500-yen coins add up to 1000 yen, which is not less than X = 900 yen.

Sample Input 2

1 501

Sample Output 2

No

One 500-yen coin is worth 500 yen, which is less than X = 501 yen.

Sample Input 3

4 2000

Sample Output 3

Yes

Four 500-yen coins add up to 2000 yen, which is not less than X = 2000 yen.


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

let (n,m) = scan "%d %d" Tuple2.make
let ls = scan_list ~sep:' ' Int.of_string

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

let () =
  let ms = ListL.map ls ~f:(fun x -> x / 2) in
  List.reduce (fun a b -> a*b / gcd a b) ms
  |> (fun x ->
      if m = 1 || m - x < 0 then 0
      else (m - List.min ms)/(2*x) + 1)
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.

Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):

There exists a non-negative integer p such that X= a_k \times (p+0.5).

Find the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Constraints

1 \leq N \leq 10^5

1 \leq M \leq 10^9

2 \leq a_i \leq 10^9

a_i is an even number.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 a_2 ... a_N

Output

Print the number of semi-common multiples of A among the integers between 1 and M (inclusive).

Sample Input 1

2 50
6 10

Sample Output 1

2

15 = 6 \times 2.5

15 = 10 \times 1.5

45 = 6 \times 7.5

45 = 10 \times 4.5

Thus, 15 and 45 are semi-common multiples of A. There are no other semi-common multiples of A between 1 and 50, so the answer is 2.

Sample Input 2

3 100
14 22 40

Sample Output 2

0

The answer can be 0.

Sample Input 3

5 1000000000
6 6 2 6 2

Sample Output 3

166666667


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

let lcm n m = n / gcd n m * m

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@
  try
    let lcm = Array.fold_left (fun ans a ->
      (if m < ans then raise Not_found);
      lcm ans (a / 2)) 1 as_ in
    (m / lcm + 1) / 2
  with Not_found -> 0


let () =
    let rec gcd a b = if b = 0 then a else gcd b (a mod b) in
    let lcm a b = a / gcd a b * b in
    let main () =
        let n, m = Scanf.scanf "%d %d" (fun n m -> n, m) in
        let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun p -> p)) in
        let rec loop i acc =
            if acc > m then acc else
            if i = n then acc else loop (i + 1) (lcm acc (a.(i) / 2))
        in
        let l = loop 1 (a.(0) / 2) in
        (m / l + 1) / 2 |> Printf.printf "%d\n"
    in
    main ()


Scanf.scanf "%s %s" (fun a b ->  print_endline (b^a))

Score : 100 points

Problem Statement

Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.

Constraints

S and T are strings consisting of lowercase English letters.

The lengths of S and T are between 1 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

S T

Output

Print the resulting string.

Sample Input 1

oder atc

Sample Output 1

atcoder

When S = oder and T = atc, concatenating T and S in this order results in atcoder.

Sample Input 2

humu humu

Sample Output 2

humuhumu


(* Vicfred
 * https://atcoder.jp/contests/abc149/tasks/abc149_b
 * implementation
 * *)
Scanf.scanf "%d %d %d\n" (fun a b k ->
    if k <= a then (a - k, b)
    else if k <= a+b then (0, b - k + a)
    else (0, 0)
) |> fun (x, y) -> Printf.printf "%d %d\n" x y

Score : 200 points

Problem Statement

Takahashi has A cookies, and Aoki has B cookies.
Takahashi will do the following action K times:

If Takahashi has one or more cookies, eat one of his cookies.

Otherwise, if Aoki has one or more cookies, eat one of Aoki's cookies.

If they both have no cookies, do nothing.

In the end, how many cookies will Takahashi and Aoki have, respectively?

Constraints

0 \leq A \leq 10^{12}

0 \leq B \leq 10^{12}

0 \leq K \leq 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the numbers of Takahashi's and Aoki's cookies after K actions.

Sample Input 1

2 3 3

Sample Output 1

0 2

Takahashi will do the following:

He has two cookies, so he eats one of them.

Now he has one cookie left, and he eats it.

Now he has no cookies left, but Aoki has three, so Takahashi eats one of them.

Thus, in the end, Takahashi will have 0 cookies, and Aoki will have 2.

Sample Input 2

500000000000 500000000000 1000000000000

Sample Output 2

0 0

Watch out for overflows.


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

let end_a = if a < k then 0 else a - k
let end_b = if end_a != 0 then b else if b < k - a then 0 else b - (k - a)

let _ = Printf.printf "%d %d\n" end_a end_b


let rec fix f x = f (fix f) x
let isprime x =
  fix (fun f d -> if d * d > x then true else x mod d <> 0 && f (d+1)) 2

let () =
  Scanf.scanf "%d" @@ fun x ->
  fix (fun f v -> if isprime v then v else f (v+1)) x
  |> Printf.printf "%d\n"

Score: 300 points

Problem Statement

Find the minimum prime number greater than or equal to X.

Notes

A prime number is an integer greater than 1 that cannot be evenly divided by any positive integer except 1 and itself.

For example, 2, 3, and 5 are prime numbers, while 4 and 6 are not.

Constraints

2 \le X \le 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the minimum prime number greater than or equal to X.

Sample Input 1

20

Sample Output 1

23

The minimum prime number greater than or equal to 20 is 23.

Sample Input 2

2

Sample Output 2

2

X itself can be a prime number.

Sample Input 3

99992

Sample Output 3

100003


let n, k, r, s, p = Scanf.scanf " %d %d %d %d %d" @@ fun a b c d e -> a, b, c, d, e
let ts = Array.init n @@ fun _ -> Scanf.scanf " %c" @@ fun c -> c
let us = Array.make n ' '
let ans = ref 0
let f = function 'r' -> 'p' | 's' -> 'r' | _ -> 's'
let g t u = List.(filter (fun x -> x <> t && x <> u) ['r'; 's'; 'p'] |> hd)
let h = function 'r' -> r | 's' -> s | _ -> p
let _ = Array.iteri (fun i t -> us.(i) <- if i - k >= 0 && us.(i - k) = f t then g t @@ if i + k < n then f ts.(i + k) else f t else (ans := !ans + h (f t); f t)) ts; Printf.printf "%d\n" !ans

Score : 400 points

Problem Statement

At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:

The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)

Each time the player wins a round, depending on which hand he/she uses, he/she earns the following score (no points for a draw or a loss):

R points for winning with Rock;

S points for winning with Scissors;

P points for winning with Paper.

However, in the i-th round, the player cannot use the hand he/she used in the (i-K)-th round. (In the first K rounds, the player can use any hand.)

Before the start of the game, the machine decides the hand it will play in each round. With supernatural power, Takahashi managed to read all of those hands.

The information Takahashi obtained is given as a string T. If the i-th character of T (1 \leq i \leq N) is r, the machine will play Rock in the i-th round. Similarly, p and s stand for Paper and Scissors, respectively.

What is the maximum total score earned in the game by adequately choosing the hand to play in each round?

Notes

In this problem, Rock Paper Scissors can be thought of as a two-player game, in which each player simultaneously forms Rock, Paper, or Scissors with a hand.

If a player chooses Rock and the other chooses Scissors, the player choosing Rock wins;

if a player chooses Scissors and the other chooses Paper, the player choosing Scissors wins;

if a player chooses Paper and the other chooses Rock, the player choosing Paper wins;

if both players play the same hand, it is a draw.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq N-1

1 \leq R,S,P \leq 10^4

N,K,R,S, and P are all integers.

|T| = N

T consists of r, p, and s.

Input

Input is given from Standard Input in the following format:

N K
R S P
T

Output

Print the maximum total score earned in the game.

Sample Input 1

5 2
8 7 6
rsrpr

Sample Output 1

27

The machine will play {Rock, Scissors, Rock, Paper, Rock}.

We can, for example, play {Paper, Rock, Rock, Scissors, Paper} against it to earn 27 points.
We cannot earn more points, so the answer is 27.

Sample Input 2

7 1
100 10 1
ssssppr

Sample Output 2

211

Sample Input 3

30 5
325 234 123
rspsspspsrpspsppprpsprpssprpsr

Sample Output 3

4996


let () = Scanf.scanf "%d %d\n%d %d %d\n%s" @@ fun n k r s p t ->
  let dp =
    Array.init (n + k) @@ fun _ ->
      Array.make 3 0 in
  for i = 0 to n - 1 do
    dp.(i + k).(0) <-
      max dp.(i).(1) dp.(i).(2)
      + if t.[i] = 's' then r else 0;
    dp.(i + k).(1) <-
      max dp.(i).(0) dp.(i).(2)
      + if t.[i] = 'p' then s else 0;
    dp.(i + k).(2) <-
      max dp.(i).(0) dp.(i).(1)
      + if t.[i] = 'r' then p else 0;
  done;
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.init k @@ fun i ->
    Array.fold_left max min_int dp.(n + i)


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

    let border = a.(p - 1) in

    let bordersum =
        let rec loop i acc =
            if i = n then acc else
                loop (i + 1) (acc + border - a.(i))
        in
        loop p 0
    in

    let rec loop i acc =
        if i = n then acc else
            if a.(i) + m < border then acc else
                let nb = bordersum - (border - a.(i)) in
                if nb + (a.(i) + m - border) * (n - p) <= (v - p) * m then acc
                else loop (i + 1) (acc + 1)
    in
    loop p p |> Printf.printf "%d\n"
)

Score : 700 points

Problem Statement

N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points.

M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges,
and increase the score of each chosen problem by 1.

After all M judges cast their vote, the problems will be sorted in non-increasing order of score, and the first P problems will be chosen for the problemset.
Problems with the same score can be ordered arbitrarily, this order is decided by the chief judge.

How many problems out of the given N have a chance to be chosen for the problemset?

Constraints

2 \le N \le 10^5

1 \le M \le 10^9

1 \le V \le N - 1

1 \le P \le N - 1

0 \le A_i \le 10^9

Input

Input is given from Standard Input in the following format:

N M V P
A_1 A_2 ... A_N

Output

Print the number of problems that have a chance to be chosen for the problemset.

Sample Input 1

6 1 2 2
2 1 1 3 0 2

Sample Output 1

5

If the only judge votes for problems 2 and 5, the scores will be 2 2 1 3 1 2.
The problemset will consist of problem 4 and one of problems 1, 2, or 6.

If the only judge votes for problems 3 and 4, the scores will be 2 1 2 4 0 2.
The problemset will consist of problem 4 and one of problems 1, 3, or 6.

Thus, problems 1, 2, 3, 4, and 6 have a chance to be chosen for the problemset. On the contrary, there is no way for problem 5 to be chosen.

Sample Input 2

6 1 5 2
2 1 1 3 0 2

Sample Output 2

3

Only problems 1, 4, and 6 have a chance to be chosen.

Sample Input 3

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

Sample Output 3

8


let () = Scanf.scanf "%d %d %d %d\n" @@ fun n m v p ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Array.sort (fun a a' -> compare a' a) as_;
  let acc = Array.make (n + 1) 0 in
  for i = 0 to n - 1 do
    acc.(i + 1) <- as_.(i) + acc.(i)
  done;
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.init n @@ fun i ->
    if
      as_.(p - 1) <= as_.(i) ||
      acc.(i) - acc.(p - 1)
        <= min (i - p + 1) (n - v) * m + as_.(i) * (i - p + 1)
    then 1
    else 0


let () = Scanf.scanf "%d %d %d %d\n" @@ fun n m v p ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Array.sort (fun a a' -> compare a' a) as_;
  Printf.printf "%d\n" @@
  snd @@
  Array.fold_left (fun ((oblig, c), n) a ->
    ( (oblig + a, c + 1),
      n + if as_.(p - 1) <= a || oblig <= (n - v) * m + a * c then 1 else 0 ))
  ((Array.fold_left ( - ) 0 (Array.sub as_ 0 (p - 1)), 0), 0) as_


Printf.printf "%d\n" @@ Scanf.scanf "%d %d %d" (fun a b c -> 6-a-b)

Score: 100 points

Problem Statement

Takahashi is solving quizzes. He has easily solved all but the last one.

The last quiz has three choices: 1, 2, and 3.

With his supernatural power, Takahashi has found out that the choices A and B are both wrong.

Print the correct choice for this problem.

Constraints

Each of the numbers A and B is 1, 2, or 3.

A and B are different.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print the correct choice.

Sample Input 1

3
1

Sample Output 1

2

When we know 3 and 1 are both wrong, the correct choice is 2.

Sample Input 2

1
2

Sample Output 2

3


let () = Scanf.scanf "%d\n%d" @@ fun a b ->
  Printf.printf "%d\n" @@
  List.find (fun x -> x <> a && x <> b) [1; 2; 3]


let () =
  let n, s, t = Scanf.scanf "%d\n%s %s\n" @@ fun a b c -> a, b, c in
  let ans = Array.make (n*2) 'x' in
  for i = 0 to n-1 do
    ans.(2*i) <- s.[i]; ans.(2*i+1) <- t.[i];
  done;
  print_endline (Array.fold_left (fun s a -> s ^ Char.escaped a) "" ans)

Score : 200 points

Problem Statement

Given are strings s and t of length N each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of S, the N-th character of T. Print this new string.

Constraints

1 \leq N \leq 100

|S| = |T| = N

S and T are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S T

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa


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

let rec gcd = function
  | (x, 0) -> x
  | (x, y) -> gcd (y, x mod y)

let lcm (x, y) = x * (y / gcd (x, y))

let () = print_int (lcm (a, b))

Score : 300 points

Problem Statement

Takahashi is organizing a party.

At the party, each guest will receive one or more snack pieces.

Takahashi predicts that the number of guests at this party will be A or B.

Find the minimum number of pieces that can be evenly distributed to the guests in both of the cases predicted.

We assume that a piece cannot be divided and distributed to multiple guests.

Constraints

1 \leq A, B \leq 10^5

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of pieces that can be evenly distributed to the guests in both of the cases with A guests and B guests.

Sample Input 1

2 3

Sample Output 1

6

When we have six snack pieces, each guest can take three pieces if we have two guests, and each guest can take two if we have three guests.

Sample Input 2

123 456

Sample Output 2

18696

Sample Input 3

100000 99999

Sample Output 3

9999900000


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

let lcm n m = n / gcd n m * m

let () = Printf.printf "%d\n" @@ Scanf.scanf "%d %d" lcm


let n = read_int ()
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let k = Array.fold_left (fun c a -> if a = c then c + 1 else c) 1 a_s - 1
let _ = Printf.printf "%d\n" @@ if k = 0 then -1 else n - k

Score : 400 points

Problem Statement

We have N bricks arranged in a row from left to right.

The i-th brick from the left (1 \leq i \leq N) has an integer a_i written on it.

Among them, you can break at most N-1 bricks of your choice.

Let us say there are K bricks remaining. Snuke will be satisfied if, for each integer i (1 \leq i \leq K), the i-th of those brick from the left has the integer i written on it.

Find the minimum number of bricks you need to break to satisfy Snuke's desire. If his desire is unsatisfiable, print -1 instead.

Constraints

All values in input are integers.

1 \leq N \leq 200000

1 \leq a_i \leq N

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of bricks that need to be broken to satisfy Snuke's desire, or print -1 if his desire is unsatisfiable.

Sample Input 1

3
2 1 2

Sample Output 1

1

If we break the leftmost brick, the remaining bricks have integers 1 and 2 written on them from left to right, in which case Snuke will be satisfied.

Sample Input 2

3
2 2 2

Sample Output 2

-1

In this case, there is no way to break some of the bricks to satisfy Snuke's desire.

Sample Input 3

10
3 1 4 1 5 9 2 6 5 3

Sample Output 3

7

Sample Input 4

1
1

Sample Output 4

0

There may be no need to break the bricks at all.


let blackjack a1 a2 a3 =
  if a1 + a2 + a3 <= 21 then "win" else "bust"

let a1, a2, a3 =
  Scanf.sscanf (read_line ()) "%d %d %d" (fun a1 a2 a3 -> (a1, a2, a3))
let ans = blackjack a1 a2 a3
let () = print_endline ans

Score : 100 points

Problem Statement

Given are three integers A_1, A_2, and A_3.

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Constraints

1 \leq A_i \leq 13 \ \ (i=1,2,3)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

If A_1+A_2+A_3 is greater than or equal to 22, print bust; otherwise, print win.

Sample Input 1

5 7 9

Sample Output 1

win

5+7+9=21, so print win.

Sample Input 2

13 7 2

Sample Output 2

bust

13+7+2=22, so print bust.


open Batteries
let rec print_list lst=
  match lst with
  | [] -> Printf.printf "\n"
  | first :: rest -> Printf.printf "%b " first ; print_list rest

let count_list lst target =
  let rec loop l =
    match l with
    | [] -> 0
    | first :: rest -> if first = target then 1 + loop rest else loop rest
  in loop lst

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

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

type syogen = { user : int; is_honest : bool }
let rec get_syogen i a =
  if i >= a then [] else
    Scanf.sscanf (read_line()) "%d %d" (fun x y -> { user=x-1; is_honest=if y = i then true else false }) :: get_syogen (i+1) a

let n = read_int ()
let data = Array.init n (fun a -> get_syogen 0 @@ read_int ())

let rec check_true ary syogen_list =
  match syogen_list with
  | [] -> true
  | first :: rest ->
    if ary.(first.user) = first.is_honest then check_true ary rest else false

let rec check_false ary syogen_list =
  match syogen_list with
  | [] -> true
  | first :: rest ->
    if ary.(first.user) != first.is_honest then check_false ary rest else false

let check_syogen ary i syogen_list =
  if i = 1 then check_true ary syogen_list else true

let rec is_true ary i =
  if i >= n then true else if check_syogen ary i data.(i) then is_true ary (i+1) else false

let check bit =
  let b_list = bit_list bit n in
  if is_true (Array.of_list @@ b_list) 0 then (count_list b_list true) else 0

let rec bit_loop bit =
  if bit > n * n then min_int else max (check bit) (bit_loop @@ bit+1)

let _ = Printf.printf "%d\n" @@ bit_loop 0
(* 3
   1
   2 1
   1
   1 1
   1
   2 0 *)

Score : 300 points

Problem Statement

There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.

Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.

How many honest persons can be among those N people at most?

Constraints

All values in input are integers.

1 \leq N \leq 15

0 \leq A_i \leq N - 1

1 \leq x_{ij} \leq N

x_{ij} \neq i

x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)

y_{ij} = 0, 1

Input

Input is given from Standard Input in the following format:

N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

Output

Print the maximum possible number of honest persons among the N people.

Sample Input 1

3
1
2 1
1
1 1
1
2 0

Sample Output 1

2

If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.

Sample Input 2

3
2
2 1
3 0
2
3 1
1 0
2
1 1
2 0

Sample Output 2

0

Assuming that one or more of them are honest immediately leads to a contradiction.

Sample Input 3

2
1
2 0
1
1 0

Sample Output 3

1


let popcnt x =
  let x = (x land 0x5555555555555555) + ((x lsr 1) land 0x5555555555555555) in
  let x = (x land 0x3333333333333333) + ((x lsr 2) land 0x3333333333333333) in
  let x = (x land 0x0f0f0f0f0f0f0f0f) + ((x lsr 4) land 0x0f0f0f0f0f0f0f0f) in
  let x = (x land 0x00ff00ff00ff00ff) + ((x lsr 8) land 0x00ff00ff00ff00ff) in
  let x = (x land 0x0000ffff0000ffff) + ((x lsr 16) land 0x0000ffff0000ffff) in
  (x land 0x00000000ffffffff) + ((x lsr 32) land 0x00000000ffffffff)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let xyss =
    Array.init n @@ fun _ ->
      Scanf.scanf "%d\n" @@ fun a ->
        Array.to_list @@ Array.init a @@ fun _ ->
          Scanf.scanf "%d %d\n" @@ fun x y -> x, y in
  Printf.printf "%d\n" @@
  Array.fold_left max min_int @@
  Array.init (1 lsl n) @@ fun ans ->
    if
      Array.fold_left ( && ) true @@
      Array.init n @@ fun i ->
        if ans land (1 lsl i) = 0
        then true
        else
          List.for_all (fun (x, y) ->
            ans land (1 lsl (x - 1)) = y lsl (x - 1)) xyss.(i)
    then popcnt ans
    else 0


let () =
    let main () =
        let h, w = Scanf.scanf "%d %d" (fun h w -> h, w) in
        let a = Array.init h (fun _ -> Array.init w (fun _ -> Scanf.scanf " %d" (fun n -> n))) in
        let b = Array.init h (fun _ -> Array.init w (fun _ -> Scanf.scanf " %d" (fun n -> n))) in
        let m = (h + w) * 2 * 80 in
        let m2 = m / 2 in
        let ar = Array.init (h + 1) (
            fun y -> Array.init (w + 1) (
                fun x -> Array.init m (
                    fun t -> t = m2 && (y = 0 || x = 0))))
        in
        for y = 1 to h do
            for x = 1 to w do
                for k = 0 to m - 1 do
                    if ar.(y - 1).(x).(k) || ar.(y).(x - 1).(k) then (
                        ar.(y).(x).(k + a.(y - 1).(x - 1) - b.(y - 1).(x - 1)) <- true;
                        ar.(y).(x).(k - a.(y - 1).(x - 1) + b.(y - 1).(x - 1)) <- true
                    )
                done
            done
        done;
        let rec loop i acc =
            if i = m then acc else
                let acc = if ar.(h).(w).(i) then min acc (abs (i - m2)) else acc in
                loop (i + 1) acc
        in
        let s = loop 0 max_int in
        Printf.printf "%d\n" s
    in
    main ()

Score : 500 points

Problem Statement

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

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2


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

let add x s =
  if 160 <= x
  then s
  else IntSet.add x s

let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ass =
    Array.init h @@ fun _ ->
      Array.init w @@ fun _ ->
        Scanf.scanf "%d " @@ fun a -> a in
  let bss =
    Array.init h @@ fun _ ->
      Array.init w @@ fun _ ->
        Scanf.scanf "%d " @@ fun b -> b in
  let dp = Array.make_matrix (h + 1) (w + 1) IntSet.empty in
  dp.(0).(1) <- IntSet.singleton 0;
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do
      dp.(i + 1).(j + 1) <-
        IntSet.fold (fun sum s ->
          add (abs (sum + ass.(i).(j) - bss.(i).(j))) @@
          add (abs (sum - ass.(i).(j) + bss.(i).(j))) s) dp.(i).(j + 1) @@
        IntSet.fold (fun sum s ->
          add (abs (sum + ass.(i).(j) - bss.(i).(j))) @@
          add (abs (sum - ass.(i).(j) + bss.(i).(j))) s) dp.(i + 1).(j) IntSet.empty
    done
  done;
  Printf.printf "%d\n" @@
  IntSet.fold min dp.(h).(w) max_int


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

let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ass =
    Array.init h @@ fun _ ->
      Array.init w @@ fun _ ->
        Scanf.scanf "%d " @@ fun a -> a in
  let bss =
    Array.init h @@ fun _ ->
      Array.init w @@ fun _ ->
        Scanf.scanf "%d " @@ fun b -> b in
  let dp = Array.make_matrix (h + 1) (w + 1) IntSet.empty in
  dp.(0).(1) <- IntSet.singleton 0;
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do
      dp.(i + 1).(j + 1) <-
        IntSet.fold (fun sum s ->
          IntSet.add (abs (sum + ass.(i).(j) - bss.(i).(j))) @@
          IntSet.add (abs (sum - ass.(i).(j) + bss.(i).(j))) s) dp.(i).(j + 1) @@
        IntSet.fold (fun sum s ->
          IntSet.add (abs (sum + ass.(i).(j) - bss.(i).(j))) @@
          IntSet.add (abs (sum - ass.(i).(j) + bss.(i).(j))) s) dp.(i + 1).(j) IntSet.empty
    done
  done;
  Printf.printf "%d\n" @@
  IntSet.fold min dp.(h).(w) max_int


Scanf.scanf "%d %d %d %d" (fun m1 d1 m2 d2 -> if m1 = m2 then "0" else "1") |> print_endline

Score: 100 points

Problem Statement

In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019.

Integers M_1, D_1, M_2, and D_2 will be given as input.

It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1.

Determine whether the date 2019-M_1-D_1 is the last day of a month.

Constraints

Both 2019-M_1-D_1 and 2019-M_2-D_2 are valid dates in the Gregorian calendar.

The date 2019-M_2-D_2 follows 2019-M_1-D_1.

Input

Input is given from Standard Input in the following format:

M_1 D_1
M_2 D_2

Output

If the date 2019-M_1-D_1 is the last day of a month, print 1; otherwise, print 0.

Sample Input 1

11 16
11 17

Sample Output 1

0

November 16 is not the last day of a month.

Sample Input 2

11 30
12 1

Sample Output 2

1

November 30 is the last day of November.


open Printf
open Scanf

let tax x = x * 108 / 100

let solve n =
  let rec f s l =
    let m = (s + l) / 2 in
    let t = tax m in
    if s + 1 = l then ":("
    else if t = n then string_of_int m
    else if t > n then f s m
    else f m l
  in f 0 50000

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

Score: 200 points

Problem Statement

Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.

The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).

Takahashi forgot the price of his apple pie before tax, X, and wants to know it again. Write a program that takes N as input and finds X. We assume X is an integer.

If there are multiple possible values for X, find any one of them. Also, Takahashi's memory of N, the amount he paid, may be incorrect. If no value could be X, report that fact.

Constraints

1 \leq N \leq 50000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If there are values that could be X, the price of the apple pie before tax, print any one of them.

If there are multiple such values, printing any one of them will be accepted.

If no value could be X, print :(.

Sample Input 1

432

Sample Output 1

400

If the apple pie is priced at 400 yen before tax, you have to pay 400 \times 1.08 = 432 yen to buy one.

Otherwise, the amount you have to pay will not be 432 yen.

Sample Input 2

1079

Sample Output 2

:(

There is no possible price before tax for which you have to pay 1079 yen with tax.

Sample Input 3

1001

Sample Output 3

927

If the apple pie is priced 927 yen before tax, by rounding down 927 \times 1.08 = 1001.16, you have to pay 1001 yen.


let n = read_int ()
let x = (100 * n + 107) / 108
let _ = print_endline @@ if 108 * x / 100 = n then string_of_int x else ":("


let m_1e9 = int_of_float 1e9 + 7
let ( +^ ) x y = (x + y) mod m_1e9
let ( -^ ) x y = x - y + if x < y then m_1e9 else 0
let ( *^ ) x y = ((x mod m_1e9) * (y mod m_1e9)) mod m_1e9
let split_string ?(pattern=" ") = Str.split @@ Str.regexp pattern

let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let a = read_line () |> split_string |> List.map int_of_string

let rec loop ans arr = function
  | [] -> Printf.printf "%d\n" @@ ans
  | x :: xs ->
    let t = Array.fold_left (fun s i -> s + if i = x then 1 else 0) 0 arr in
    if arr.(0) = x then arr.(0) <- arr.(0) + 1
    else if arr.(1) = x then arr.(1) <- arr.(1) + 1
    else arr.(2) <- arr.(2) + 1;
    loop (ans *^ t) arr xs

let () = loop 1 (Array.make 3 0) a

Score: 500 points

Problem Statement

N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green.

The person numbered i says:

"In front of me, exactly A_i people are wearing hats with the same color as mine."

Assuming that all these statements are correct, find the number of possible combinations of colors of the N people's hats.

Since the count can be enormous, compute it modulo 1000000007.

Constraints

1 \leq N \leq 100000

0 \leq A_i \leq N-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print the number of possible combinations of colors of the N people's hats, modulo 1000000007.

Sample Input 1

6
0 1 2 3 4 5

Sample Output 1

3

We have three possible combinations, as follows:

Red, Red, Red, Red, Red, Red

Blue, Blue, Blue, Blue, Blue, Blue

Green, Green, Green, Green, Green, Green

Sample Input 2

3
0 0 0

Sample Output 2

6

Sample Input 3

54
0 0 1 0 1 2 1 2 3 2 3 3 4 4 5 4 6 5 7 8 5 6 6 7 7 8 8 9 9 10 10 11 9 12 10 13 14 11 11 12 12 13 13 14 14 15 15 15 16 16 16 17 17 17

Sample Output 3

115295190


let m = 1000000007
let ( +^ ) x y = (x + y) mod m
let ( *^ ) x y = (x * y) mod m

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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let m =
    Array.fold_left (fun m a ->
      IntTripleMap.fold (fun (r, g, b) n m ->
        let m =
          if r <> a then m else
          IntTripleMap.add (r + 1, g, b)
          (n +^
            try IntTripleMap.find (r + 1, g, b) m
            with Not_found -> 0) m in
        let m =
          if g <> a then m else
          IntTripleMap.add (r, g + 1, b)
            (n +^
              try IntTripleMap.find (r, g + 1, b) m
              with Not_found -> 0) m in
        let m =
          if b <> a then m else
          IntTripleMap.add (r, g, b + 1)
            (n +^
              try IntTripleMap.find (r, g, b + 1) m
              with Not_found -> 0) m in
        m) m IntTripleMap.empty) (IntTripleMap.singleton (0, 0, 0) 1) as_ in
  Printf.printf "%d\n" @@
  IntTripleMap.fold (fun _ -> ( +^ )) m 0


let () =
    let main () =
        let t1, t2 = Scanf.sscanf (read_line ()) "%d %d" (fun t1 t2 -> t1, t2) in
        let a1, a2 = Scanf.sscanf (read_line ()) "%d %d" (fun a1 a2 -> a1, a2) in
        let b1, b2 = Scanf.sscanf (read_line ()) "%d %d" (fun b1 b2 -> b1, b2) in
        let r =
            if a1 = b1 then (-1) else (
                let m1a = t1 * a1 in
                let m1b = t1 * b1 in
                let m2a = m1a + t2 * a2 in
                let m2b = m1b + t2 * b2 in
                if m2a = m2b then (-1) else
                    if (m1a > m1b && m2a > m2b) ||
                       (m1a < m1b && m2a < m2b) then 0 else (
                           let d1 = t1 * (max a1 b1 - min a1 b1) in
                           let d2 = t2 * (max a2 b2 - min a2 b2) in
                           let rec loop d acc =
                               if d = 0 then acc else
                               if d - d2 > 0 then acc else
                                   if d - d2 + d1 < 0 then acc + 1 else
                                       loop (d - d2 + d1) (acc + 2)
                           in
                           let c = d1 / (d2 - d1) in
                           loop (d1 + (d1 - d2) * c) (2 * c)
                       )
            )
        in
        if r < 0 then Printf.printf "infinity\n" else Printf.printf "%d\n" r
    in
    main ()

Score: 600 points

Problem Statement

Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east.

They start simultaneously at the same point and moves as follows towards the east:

Takahashi runs A_1 meters per minute for the first T_1 minutes, then runs at A_2 meters per minute for the subsequent T_2 minutes, and alternates between these two modes forever.

Aoki runs B_1 meters per minute for the first T_1 minutes, then runs at B_2 meters per minute for the subsequent T_2 minutes, and alternates between these two modes forever.

How many times will Takahashi and Aoki meet each other, that is, come to the same point? We do not count the start of the run. If they meet infinitely many times, report that fact.

Constraints

1 \leq T_i \leq 100000

1 \leq A_i \leq 10^{10}

1 \leq B_i \leq 10^{10}

A_1 \neq B_1

A_2 \neq B_2

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T_1 T_2
A_1 A_2
B_1 B_2

Output

Print the number of times Takahashi and Aoki will meet each other.

If they meet infinitely many times, print infinity instead.

Sample Input 1

1 2
10 10
12 4

Sample Output 1

1

They will meet just once, \frac{4}{3} minutes after they start, at \frac{40}{3} meters from where they start.

Sample Input 2

100 1
101 101
102 1

Sample Output 2

infinity

They will meet 101, 202, 303, 404, 505, 606, ... minutes after they start, that is, they will meet infinitely many times.

Sample Input 3

12000 15700
3390000000 3810000000
5550000000 2130000000

Sample Output 3

113

The values in input may not fit into a 32-bit integer type.


Score : 100 points

Problem Statement

Given is a string S representing the day of the week today.

S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.

After how many days is the next Sunday (tomorrow or later)?

Constraints

S is SUN, MON, TUE, WED, THU, FRI, or SAT.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of days before the next Sunday.

Sample Input 1

SAT

Sample Output 1

1

It is Saturday today, and tomorrow will be Sunday.

Sample Input 2

SUN

Sample Output 2

7

It is Sunday today, and seven days later, it will be Sunday again.


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

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

let edges =
  let add k v idx map =
    let vs = try IntMap.find k map with Not_found -> [] in
    IntMap.add k ((idx, v) :: vs) map in
  fst @@ Array.fold_left (fun (map, i) (a, b) ->
    (add b a i @@ add a b i map, i + 1)
  ) (IntMap.empty, 0) ab

let () =
  let arr = Array.make (n - 1) 0 in
  let used = Array.make n false in
  let k = IntMap.bindings edges |> List.map (snd $ List.length) |> List.fold_left max 0 in
  let que = Queue.create () in
  Queue.add (0, k + 1) que;
  while not (Queue.is_empty que) do
    let node, col = Queue.pop que in
    let children = IntMap.find node edges |> List.filter (fun (_, v) -> not used.(v)) |> List.rev in
    used.(node) <- true;
    List.iteri (fun idx (i, v) ->
      let c = idx + if idx < col - 1 then 1 else 2 in
      arr.(i) <- c;
      Queue.add (v, c) que;
    ) children;

  done;
  Printf.printf "%d\n" k;
  Array.iter (Printf.printf "%d\n") arr;

Score : 400 points

Problem Statement

Given is a tree G with N vertices.
The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.

Consider painting the edges in G with some number of colors.
We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.

Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.

Constraints

2 \le N \le 10^5

1 \le a_i \lt b_i \le N

All values in input are integers.

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

Print N lines.

The first line should contain K, the number of colors used.

The (i+1)-th line (1 \le i \le N-1) should contain c_i, the integer representing the color of the i-th edge, where 1 \le c_i \le K must hold.

If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.

Sample Input 1

3
1 2
2 3

Sample Output 1

2
1
2

Sample Input 2

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

Sample Output 2

4
1
2
3
4
1
1
2

Sample Input 3

6
1 2
1 3
1 4
1 5
1 6

Sample Output 3

5
1
2
3
4
5


type edge = {a: int; b: int; i: int}

let degrees edges =
  let n = (List.length edges) + 1 in
  let rec helper edges acc =
    match edges with
    | [] -> acc
    | {a=a; b=b} :: rst ->
      acc.(a) <- acc.(a) + 1;
      acc.(b) <- acc.(b) + 1;
      helper rst acc in
  helper edges (Array.make n 0)
;;

let solve n edges =
  let k =
    let rec find_max l i m =
      if i == Array.length l then m
      else if l.(i) > m then find_max l (i+1) l.(i)
      else find_max l (i+1) m in
    find_max (degrees edges) 0 0 in
  let p = Array.make n 0 in
  let cs = Array.make (n-1) 0 in
  let rec choose_color es prev cnt =
    match es with
    | [] -> cs
    | e :: rst ->
      let cnt = if e.a == prev then cnt else 0 in
      let color = if e.a == 0 then cnt
        else if cnt < p.(e.a) then cnt else cnt + 1 in
      p.(e.b) <- color; cs.(e.i) <- color;
      choose_color rst e.a (cnt+1) in
  (k, choose_color edges 0 0)
;;

let read () =
  let n = read_int () in
  let rec read_edges i acc =
    if i == n-1 then acc else
      let input = Str.split (Str.regexp " ") (read_line ()) in
      let a::b::[] = List.map int_of_string input in
      let edge = {a=a-1; b=b-1; i=i} in
      read_edges (i+1) (edge :: acc) in
  let edges = List.sort (fun e1 e2 -> e1.a - e2.a) (read_edges 0 []) in
  (n, edges) in
let print k colors =
  print_endline (string_of_int k);
  for i = 0 to ((Array.length colors) - 1) do
    print_endline (string_of_int (colors.(i) + 1))
  done in
let n, edges = read() in
let k, colors = solve n edges in
print k colors


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

let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then ( if flag then cur :: acc else acc) else (
                match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let main () =
        let n, k = Scanf.sscanf (read_line ()) "%d %d" (fun n k -> n, k) in
        let a = Array.of_list (split (read_line ())) in
        let arr = Array.make (n + 1) 0 in
        let rec loop i sum =
            if i < n then (
                let sum = sum + a.(i) - 1 in
                arr.(i + 1) <- sum mod k;
                loop (i + 1) sum
            )
        in
        loop 0 0;
        let add k v map = M.add k (v + try M.find k map with _ -> 0) map in
        let rec loop i map acc =
            if i > n then acc else
                let map = if i >= k then add arr.(i - k) (-1) map else map in
                let acc = acc + try M.find arr.(i) map with _ -> 0 in
                let map = add arr.(i) 1 map in
                loop (i + 1) map acc
        in
        let r = loop 1 (M.add 0 1 M.empty) 0 in
        Printf.printf "%d\n" r
    in
    main ()

Score : 500 points

Problem Statement

Given are a sequence of N positive integers A_1, A_2, \ldots, A_N, and a positive integer K.

Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from different positions, even if they are equal sequences.

Constraints

All values in input are integers.

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

1 \leq K \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print the number of subsequences that satisfy the condition.

Sample Input 1

5 4
1 4 2 3 5

Sample Output 1

4

Four sequences satisfy the condition: (1), (4,2), (1,4,2), and (5).

Sample Input 2

8 4
4 2 4 2 4 2 4 2

Sample Output 2

7

(4,2) is counted four times, and (2,4) is counted three times.

Sample Input 3

10 7
14 15 92 65 35 89 79 32 38 46

Sample Output 3

8


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

let m = scan "%d" id
let ls = scan_lines m "%d %d" Tuple2.make

let rec calc v n =
  if n = 1 then (v, 0)
  else
    let (w, m) = if v * 2 / 10 = 1 then
        v*2 mod 10 + v*2 / 10, 2
      else v * 2, 1
    in
    let (x, o) = calc w (n/2) in
    if n mod 2 = 0 then
      (x, n/2 * m + o)
    else
      ((v+x) mod 10 + v*2/10, n/2 * m + o + 1 + (v+x)/10)

let () =
  ListL.map ls ~f:(fun (v, n) ->
      calc v n)
  |> List.reduce (fun (v,n) (w, m) ->
      ((v+w) mod 10, n + m + 1 + (v+w)/10))
  |> Tuple2.second
  |> Printf.printf "%d\n"

Score: 500 points

Problem Statement

N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.

The preliminary stage consists of several rounds, which will take place as follows:

All the N contestants will participate in the first round.

When X contestants participate in some round, the number of contestants advancing to the next round will be decided as follows:

The organizer will choose two consecutive digits in the decimal notation of X, and replace them with the sum of these digits. The number resulted will be the number of contestants advancing to the next round.

For example, when X = 2378, the number of contestants advancing to the next round will be 578 (if 2 and 3 are chosen), 2108 (if 3 and 7 are chosen), or 2315 (if 7 and 8 are chosen).

When X = 100, the number of contestants advancing to the next round will be 10, no matter which two digits are chosen.

The preliminary stage ends when 9 or fewer contestants remain.

Ringo, the chief organizer, wants to hold as many rounds as possible.
Find the maximum possible number of rounds in the preliminary stage.

Since the number of contestants, N, can be enormous, it is given to you as two integer sequences d_1, \ldots, d_M and c_1, \ldots, c_M, which means the following: the decimal notation of N consists of c_1 + c_2 + \ldots + c_M digits, whose first c_1 digits are all d_1, the following c_2 digits are all d_2, \ldots, and the last c_M digits are all d_M.

Constraints

1 \leq M \leq 200000

0 \leq d_i \leq 9

d_1 \neq 0

d_i \neq d_{i+1}

c_i \geq 1

2 \leq c_1 + \ldots + c_M \leq 10^{15}

Input

Input is given from Standard Input in the following format:

M
d_1 c_1
d_2 c_2
:
d_M c_M

Output

Print the maximum possible number of rounds in the preliminary stage.

Sample Input 1

2
2 2
9 1

Sample Output 1

3

In this case, N = 229 contestants will participate in the first round. One possible progression of the preliminary stage is as follows:

229 contestants participate in Round 1, 49 contestants participate in Round 2, 13 contestants participate in Round 3, and 4 contestants advance to the finals.

Here, three rounds take place in the preliminary stage, which is the maximum possible number.

Sample Input 2

3
1 1
0 8
7 1

Sample Output 2

9

In this case, 1000000007 will participate in the first round.