let n = read_int ()
let ps = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let _ = Array.fold_left (fun (m, c) p -> if p <= m then p, c + 1 else m, c) (ps.(0), 0) ps |> snd |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

Given is a permutation P_1, \ldots, P_N of 1, \ldots, N.
Find the number of integers i (1 \leq i \leq N) that satisfy the following condition:

For any integer j (1 \leq j \leq i), P_i \leq P_j.

Constraints

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

P_1, \ldots, P_N is a permutation of 1, \ldots, N.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 ... P_N

Output

Print the number of integers i that satisfy the condition.

Sample Input 1

5
4 2 5 1 3

Sample Output 1

3

i=1, 2, and 4 satisfy the condition, but i=3 does not - for example, P_i > P_j holds for j = 1.

Similarly, i=5 does not satisfy the condition, either. Thus, there are three integers that satisfy the condition.

Sample Input 2

4
4 3 2 1

Sample Output 2

4

All integers i (1 \leq i \leq N) satisfy the condition.

Sample Input 3

6
1 2 3 4 5 6

Sample Output 3

1

Only i=1 satisfies the condition.

Sample Input 4

8
5 7 4 2 6 8 1 3

Sample Output 4

4

Sample Input 5

1
1

Sample Output 5

1


let () =
  Scanf.scanf "%d\n%d\n%d\n" @@ fun h w n ->
  let m = max h w in
  Printf.printf "%d\n" (if n mod m = 0 then n / m else n / m + 1)

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

Score : 100 points

Problem Statement

We have a grid with H rows and W columns, where all the squares are initially white.

You will perform some number of painting operations on the grid.
In one operation, you can do one of the following two actions:

Choose one row, then paint all the squares in that row black.

Choose one column, then paint all the squares in that column black.

At least how many operations do you need in order to have N or more black squares in the grid?
It is guaranteed that, under the conditions in Constraints, having N or more black squares is always possible by performing some number of operations.

Constraints

1 \leq H \leq 100

1 \leq W \leq 100

1 \leq N \leq H \times W

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H
W
N

Output

Print the minimum number of operations needed.

Sample Input 1

3
7
10

Sample Output 1

2

You can have 14 black squares in the grid by performing the "row" operation twice, on different rows.

Sample Input 2

14
12
112

Sample Output 2

8

Sample Input 3

2
100
200

Sample Output 3

2

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.


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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let xls = Array.init (n + 1) @@ function
    | 0 -> (-100000000, 0)
    | _ -> Scanf.scanf "%d %d\n" @@ fun x l -> x, l in
  Array.sort (fun (x, l) (x', l') -> compare (x + l) (x' + l')) xls;
  let dp = Array.make (n + 1) 0 in
  for i = 1 to n do
    dp.(i) <- max (dp.(i - 1)) @@
      1 + dp.(upper_bound 0 i (fun j ->
        fst (xls.(j)) + snd (xls.(j)) <= fst (xls.(i)) - snd (xls.(i))))
  done;
  Printf.printf "%d\n" dp.(n)

Score : 200 points

Problem Statement

In a factory, there are N robots placed on a number line.
Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.

We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect.
Here, for each i (1 \leq i \leq N), the movable range of arms of Robot i is the part of the number line between the coordinates X_i - L_i and X_i + L_i, excluding the endpoints.

Find the maximum number of robots that we can keep.

Constraints

1 \leq N \leq 100,000

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

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

If i \neq j, X_i \neq X_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 L_1
X_2 L_2
\vdots
X_N L_N

Output

Print the maximum number of robots that we can keep.

Sample Input 1

4
2 4
4 3
9 3
100 5

Sample Output 1

3

By removing Robot 2, we can keep the other three robots.

Sample Input 2

2
8 20
1 10

Sample Output 2

1

Sample Input 3

5
10 1
2 1
4 1
6 1
8 1

Sample Output 3

5


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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let xls = Array.init (n + 1) @@ function
    | 0 -> (-100000000, 0)
    | _ -> Scanf.scanf "%d %d\n" @@ fun x l -> x, l in
  Array.sort (fun (x, l) (x', l') -> compare (x + l) (x' + l')) xls;
  let dp = Array.make (n + 1) 0 in
  for i = 1 to n do
    dp.(i) <-
      1 + dp.(upper_bound 0 i (fun j ->
        fst (xls.(j)) + snd (xls.(j)) <= fst (xls.(i)) - snd (xls.(i))))
  done;
  Printf.printf "%d\n" @@ Array.fold_left max 0 dp


let rec popcnt acc = function
  | 0 -> acc
  | n -> popcnt (acc + (acc land 1)) (n lsr 1)
let popcnt = popcnt 0

let rec drop n = function
  | [] -> []
  | (_ :: t) as l ->
      if n = 0
      then l
      else drop (n - 1) t

let sort_count ( <= ) xs =
  let rec merge_count acc xs ys n cnt =
    match xs, ys with
    | _, [] -> cnt, List.rev_append acc xs
    | [], _ -> cnt, List.rev_append acc ys
    | x :: xs', y :: ys' ->
        if x <= y
        then merge_count (x :: acc) xs' ys (n - 1) cnt
        else merge_count (y :: acc) xs ys' n (n + cnt) in
  let rec sort_count xs = function
    | 0 -> 0, []
    | 1 -> 0, [List.hd xs]
    | n ->
        let c, ys = sort_count xs (n / 2) in
        let d, zs = sort_count (drop (n / 2) xs) ((n + 1) / 2) in
        merge_count [] ys zs (n / 2) (c + d) in
  sort_count xs (List.length xs)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let bs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun b -> b in
  let ans =
    Array.fold_left min max_int @@
    Array.init (1 lsl n) @@ fun s ->
      if popcnt s mod 2 = 1 then max_int else
      let f i = if s land (1 lsl i) = 0 then as_.(i) else bs.(i) in
      let (inv, xs) =
        sort_count (fun i j -> f i <= f j) @@
        Array.to_list @@
        Array.init n @@ fun i -> i in
      let ((x, b) :: bs) = List.mapi (fun i j -> (f j, (i mod 2 = j mod 2) = (s land (1 lsl j) = 0))) xs in
      match
        List.fold_left (fun (x, b, inv) (x', b') ->
          if b
          then (x', b', inv)
          else if x = x'
          then (x', not b', inv + 1)
          else raise Not_found) (x, b, inv) bs
      with
      | exception Not_found -> max_int
      | (_, true, inv) -> inv
      | (_, false, _) -> max_int in
  Printf.printf "%d\n" @@ if ans = max_int then -1 else ans

Score : 700 points

Problem Statement

We have N cards numbered 1, 2, ..., N.
Card i (1 \leq i \leq N) has an integer A_i written in red ink on one side and an integer B_i written in blue ink on the other side.
Initially, these cards are arranged from left to right in the order from Card 1 to Card N, with the red numbers facing up.

Determine whether it is possible to have a non-decreasing sequence facing up from left to right (that is, for each i (1 \leq i \leq N - 1), the integer facing up on the (i+1)-th card from the left is not less than the integer facing up on the i-th card from the left) by repeating the operation below. If the answer is yes, find the minimum number of operations required to achieve it.

Choose an integer i (1 \leq i \leq N - 1).
Swap the i-th and (i+1)-th cards from the left, then flip these two cards.

Constraints

1 \leq N \leq 18

1 \leq A_i, B_i \leq 50 (1 \leq i \leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N

Output

If it is impossible to have a non-decreasing sequence, print -1.
If it is possible, print the minimum number of operations required to achieve it.

Sample Input 1

3
3 4 3
3 2 3

Sample Output 1

1

By doing the operation once with i = 1, we have a sequence [2, 3, 3] facing up, which is non-decreasing.

Sample Input 2

2
2 1
1 2

Sample Output 2

-1

After any number of operations, we have the sequence [2, 1] facing up, which is not non-decreasing.

Sample Input 3

4
1 2 3 4
5 6 7 8

Sample Output 3

0

No operation may be required.

Sample Input 4

5
28 15 22 43 31
20 22 43 33 32

Sample Output 4

-1

Sample Input 5

5
4 46 6 38 43
33 15 18 27 37

Sample Output 5

3


let rec popcnt acc = function
  | 0 -> acc
  | n -> popcnt (acc + (acc land 1)) (n lsr 1)
let popcnt = popcnt 0

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

  module Make (S : SemiGroup) : sig
    type t
  type elt

  (* 与えられたリストの要素からなるセグ木を作る *)
  val of_list : elt list -> t
  (* f 0, ... f (n - 1)のn要素からなるセグ木を作る *)
  val init : int -> (int -> elt) -> t
  (*
   * update i f t
   * i番目の要素x_iをf x_iに変更したセグ木を作る
   *)
  val update : int -> (elt -> elt) -> t -> t
  (*
   * query l r t
   * 添字が[l, r)の要素を半群の演算子で畳み込んだ値を求める
   *)
  val query : int -> int -> t -> elt
  end with type elt = S.t = struct
    type elt = S.t

  type body =
    | Leaf of elt
    | Node of elt * body * body
  type t = { size : int; body : body }

  (* セグ木の要素をどのように左右に分配するか
     正整数nについて lsize n + rsize n = n が成り立たなくてはならない *)
  let lsize n = n lsr 1
  let rsize n = (n + 1) lsr 1

  (* セグ木の保持する要素を半群の演算子で畳み込んだもの *)
  let data = function
    | Leaf x
    | Node (x, _, _) -> x

  let mknode l r = Node (S.op (data l) (data r), l, r)

  let rec of_list l = function
    | 1 -> Leaf (List.hd l), List.tl l
    | n ->
        let t1, l = of_list l (lsize n) in
        let t2, l = of_list l (rsize n) in
        mknode t1 t2, l
  let of_list l =
    let n = List.length l in
    assert (0 < n);
    { size = n; body = fst (of_list l n) }

  let rec init i f = function
    | 1 -> Leaf (f i)
    | n -> mknode (init i f (lsize n)) (init (i + lsize n) f (rsize n))
  let init n f =
    assert (1 <= n);
    { size = n; body = init 0 f n }

  let rec update n i f = function
    | Leaf x -> Leaf (f x)
    | Node (_, l, r) ->
        if i < lsize n
        then mknode (update (lsize n) i f l) r
        else mknode l (update (rsize n) (i - lsize n) f r)
  let update i f t =
    assert (0 <= i && i < t.size);
    { t with body = update t.size i f t.body }

  let rec query n l r = function
    | Leaf x -> x
    | Node (x, left, right) ->
        if l = 0 && r = n then x
        else if r <= lsize n then query (lsize n) l r left
        else if lsize n <= l then query (rsize n) (l - lsize n) (r - lsize n) right
        else S.op (query (lsize n) l (lsize n) left) (query (rsize n) 0 (r - lsize n) right)
  let query l r t =
    assert (0 <= l && l < r && r <= t.size);
    query t.size l r t.body
  end
end

module SumSegTree = SegTree.Make (struct
  type t = int
  let op = ( + )
end)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let bs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun b -> b in
  let ans =
    Array.fold_left min max_int @@
    Array.init (1 lsl n) @@ fun s ->
      if popcnt s mod 2 = 1 then max_int else
      let (inv, diff, _) =
        Array.fold_left (fun (inv, diff, same) (x, b) ->
          let d = SumSegTree.query (x + 1) 52 diff + SumSegTree.query (x + 1) 52 same in
          if (d mod 2 = 0) = b
          then (inv + d, diff, SumSegTree.update x succ same)
          else (inv + d, SumSegTree.update x succ diff, same))
        (0, SumSegTree.init 53 (fun _ -> 0), SumSegTree.init 53 (fun _ -> 0)) @@
        Array.init n @@ fun i -> if (s land (1 lsl i)) = 0 then (as_.(i), true) else (bs.(i), false) in
      try
        Array.fold_left ( + ) inv @@
        Array.init 51 @@ fun i ->
          let x = SumSegTree.query i (i + 1) diff in
          if x mod 2 = 1
          then raise Not_found
          else x / 2
      with Not_found -> max_int in
  Printf.printf "%d\n" @@ if ans = max_int then -1 else ans


open Printf
open Scanf

let () =
  scanf "%c" (fun c -> Char.chr @@ (fun x -> x + 1) @@ Char.code c) |> printf "%c\n"

Score : 100 points

Problem Statement

Given is a lowercase English letter C that is not z. Print the letter that follows C in alphabetical order.

Constraints

C is a lowercase English letter that is not z.

Input

Input is given from Standard Input in the following format:

C

Output

Print the letter that follows C in alphabetical order.

Sample Input 1

a

Sample Output 1

b

a is followed by b.

Sample Input 2

y

Sample Output 2

z

y is followed by z.


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


let m, cs, c, d = Scanf.scanf "%d %d" @@ fun n m -> m, Array.make n (0, 0), ref 0, ref 0
let _ = for _ = 1 to m do Scanf.scanf " %d %s" @@ fun p s -> let a, w = cs.(p - 1) in if s = "AC" then (if a = 0 then (d := !d + w; cs.(p - 1) <- 1, w; incr c)) else if a = 0 then cs.(p - 1) <- a, w + 1 done; Printf.printf "%d %d\n" !c !d

Score : 300 points

Problem Statement

Takahashi participated in a contest on AtCoder.

The contest had N problems.

Takahashi made M submissions during the contest.

The i-th submission was made for the p_i-th problem and received the verdict S_i (AC or WA).

The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.

The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.

Find the numbers of Takahashi's correct answers and penalties.

Constraints

N, M, and p_i are integers.

1 \leq N \leq 10^5

0 \leq M \leq 10^5

1 \leq p_i \leq N

S_i is AC or WA.

Input

Input is given from Standard Input in the following format:

N M
p_1 S_1
:
p_M S_M

Output

Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

Sample Input 1

2 5
1 WA
1 AC
2 WA
2 AC
2 WA

Sample Output 1

2 2

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.

In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.

Thus, he has two correct answers and two penalties.

Sample Input 2

100000 3
7777 AC
7777 AC
7777 AC

Sample Output 2

1 0

Note that it is pointless to get an AC more than once on the same problem.

Sample Input 3

6 0

Sample Output 3

0 0


let () =
    let main () =
        let n = Scanf.scanf "%d" (fun n -> n) in
        let xy = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
        let gx, gy = Array.fold_left (fun (ax, ay) (x, y) -> ax + x, ay + y) (0, 0) xy in
        let gx = float gx /. float n in
        let gy = float gy /. float n in

        let ax = Array.init n (fun i -> xy.(i) |> fst |> float) in
        let ay = Array.init n (fun i -> xy.(i) |> snd |> float) in

        let rec loop_i i p x y last_dist =
            if i = 0 then sqrt last_dist else
                let rec loop_j j fx fy max_dist =
                    if j = n then loop_i (i - 1) (p *. 0.999) (x +. (fx -. x) *. p) (y +. (fy -. y) *. p) max_dist else
                        let d = (ax.(j) -. x) *. (ax.(j) -. x) +. (ay.(j) -. y) *. (ay.(j) -. y) in
                        if max_dist < d then loop_j (j + 1) ax.(j) ay.(j) d else
                            loop_j (j + 1) fx fy max_dist
                in
                loop_j 0 0.0 0.0 0.0
        in
        loop_i 30000 0.1 gx gy 0.0 |> Printf.printf "%.10f\n"
    in
    main ()

Score : 600 points

Problem Statement

Given are N points (x_i, y_i) in a two-dimensional plane.

Find the minimum radius of a circle such that all the points are inside or on it.

Constraints

2 \leq N \leq 50

0 \leq x_i \leq 1000

0 \leq y_i \leq 1000

The given N points are all different.

The values in input are all integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum radius of a circle such that all the N points are inside or on it.

Your output will be considered correct if the absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

2
0 0
1 0

Sample Output 1

0.500000000000000000

Both points are contained in the circle centered at (0.5,0) with a radius of 0.5.

Sample Input 2

3
0 0
0 1
1 0

Sample Output 2

0.707106781186497524

Sample Input 3

10
10 9
5 9
2 0
0 0
2 7
3 3
2 5
10 0
3 7
1 9

Sample Output 3

6.726812023536805158

If the absolute or relative error from our answer is at most 10^{-6}, the output will be considered correct.


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let pair = Array.init n @@ fun _ -> Scanf.scanf "%s %d\n" @@ fun s t -> (s, t) in
  Scanf.scanf "%s\n" @@ fun x ->
  let sum = Array.fold_left (fun sum p -> sum + snd p) 0 pair in
  let listen = Array.fold_left
      (fun (sum, b) p -> if fst p = x then (sum + snd p, true) else if b then (sum, b) else (sum + snd p, b))
      (0, false) pair  in
  Printf.printf "%d\n" (sum - fst listen)

Score : 200 points

Problem Statement

Niwango created a playlist of N songs.
The title and the duration of the i-th song are s_i and t_i seconds, respectively.
It is guaranteed that s_1,\ldots,s_N are all distinct.

Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.)
However, he fell asleep during his work, and he woke up after all the songs were played.
According to his record, it turned out that he fell asleep at the very end of the song titled X.

Find the duration of time when some song was played while Niwango was asleep.

Constraints

1 \leq N \leq 50

s_i and X are strings of length between 1 and 100 (inclusive) consisting of lowercase English letters.

s_1,\ldots,s_N are distinct.

There exists an integer i such that s_i = X.

1 \leq t_i \leq 1000

t_i is an integer.

Input

Input is given from Standard Input in the following format:

N
s_1 t_1
\vdots
s_{N} t_N
X

Output

Print the answer.

Sample Input 1

3
dwango 2
sixth 5
prelims 25
dwango

Sample Output 1

30

While Niwango was asleep, two songs were played: sixth and prelims.

The answer is the total duration of these songs, 30.

Sample Input 2

1
abcde 1000
abcde

Sample Output 2

0

No songs were played while Niwango was asleep.

In such a case, the total duration of songs is 0.

Sample Input 3

15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu

Sample Output 3

6348


open Printf
open Scanf

let () =
  let n = scanf "%d " (fun x -> x) in
  let ar = Array.init n (fun _ -> scanf "%s %d " (fun x y -> (x, y))) in
  let (_, db) = Array.fold_right (fun (nm, t) (tt, ls) -> (t + tt, (nm, tt) :: ls)) ar (0, []) in
  let s = scanf "%s " (fun x -> x) in
  printf "%d\n" @@ List.assoc s db


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 (k, x) = scan "%d %d" BatTuple.Tuple2.make

let () =
  printf "%s\n"
    (if x <= k * 500 then
       "Yes"
     else
       "No")

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.


let () = Scanf.scanf "%d\n%s" @@ fun n s ->
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.init (n - 2) @@ fun i ->
    if s.[i] = 'A' && s.[i + 1] = 'B' && s.[i + 2] = 'C'
    then 1
    else 0

Score : 200 points

Problem Statement

We have a string S of length N consisting of uppercase English letters.

How many times does ABC occur in S as contiguous subsequences (see Sample Inputs and Outputs)?

Constraints

3 \leq N \leq 50

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print number of occurrences of ABC in S as contiguous subsequences.

Sample Input 1

10
ZABCDBABCQ

Sample Output 1

2

Two contiguous subsequences of S are equal to ABC: the 2-nd through 4-th characters, and the 7-th through 9-th characters.

Sample Input 2

19
THREEONEFOURONEFIVE

Sample Output 2

0

No contiguous subsequences of S are equal to ABC.

Sample Input 3

33
ABCCABCBABCCABACBCBBABCBCBCBCABCB

Sample Output 3

5


open Batteries
let rec perm n ls =
  if n = 0 then [[]]
  else flatmap (fun x -> List.map (fun y -> x :: y)
                                  (perm (n - 1) (remove x ls)))
               ls
and remove x ls = List.filter (fun y -> x <> y) ls
and flatten = function
  [] -> []
| x::xs -> x @ (flatten xs)
and flatmap func ls = flatten (List.map func ls)

let n = read_int ()
let rec m lst =
  match lst with
   [] -> ""
  | first :: rest -> first ^ m rest
let p = m (read_line () |> String.split_on_char ' ')
let q = m (read_line () |> String.split_on_char ' ')
let rec g k =
  match k with
   0 -> []
  | _ -> k :: g (k-1)
let all =
  let rec h lst =
    match lst with
     [] -> []
    | first :: rest -> m(List.map string_of_int first) :: h rest
  in List.sort compare (h(perm n (g n)))

let _ =
  let rec o target l s =
    match l with
     [] -> 0
    | first :: rest -> if first = target then s else o target rest (s+1)
  in let jj t = if t < 0 then t * (-1) else t
    in print_endline(string_of_int (jj( (o p all 1) - (o q all 1))))

Score : 300 points

Problem Statement

We have two permutations P and Q of size N (that is, P and Q are both rearrangements of (1,~2,~...,~N)).

There are N! possible permutations of size N. Among them, let P and Q be the a-th and b-th lexicographically smallest permutations, respectively. Find |a - b|.

Notes

For two sequences X and Y, X is said to be lexicographically smaller than Y if and only if there exists an integer k such that X_i = Y_i~(1 \leq i < k) and X_k < Y_k.

Constraints

2 \leq N \leq 8

P and Q are permutations of size N.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 ... P_N
Q_1 Q_2 ... Q_N

Output

Print |a - b|.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are 6 permutations of size 3: (1,~2,~3), (1,~3,~2), (2,~1,~3), (2,~3,~1), (3,~1,~2), and (3,~2,~1). Among them, (1,~3,~2) and (3,~1,~2) come 2-nd and 5-th in lexicographical order, so the answer is |2 - 5| = 3.

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

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 i = n then acc else
                loop (i + 1) (lcm acc (a.(i) / 2))
        in
        let l = loop 1 (a.(0) / 2) in
        let r = if Array.fold_left (fun t k -> t || ((l / (k / 2)) mod 2 = 0)) false a then 0 else (m / l + 1) / 2 in
        Printf.printf "%d %d\n" l r
    in
    main ()

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


(* Vicfred
 * https://atcoder.jp/contests/abc149/tasks/abc149_a
 * string manipulation
 * *)
print_endline @@ Scanf.scanf "%s %s" @@ fun s t -> t ^ s

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


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 (a,b,k) = scan "%d %d %d" Tuple3.make

let () =
  Printf.printf "%d %d" (max 0 (a-k)) @@ max 0 (if a-k < 0 then b + a -k else b)

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 () =
  let rec prime n m = if n = m then true else if n mod m = 0 then false else prime n (m+1) in
  let rec check n m = if prime n 2 then n else if n = m then n else check (n+1) m  in
  let n = read_int () in
  Printf.printf "%d\n" (check n (n*2))

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 x = read_int ()
let f n = if n <= 1 then false else let rec f i = if i * i > n then true else if n mod i = 0 then false else f @@ i + 1 in f 2
let _ = for i = x to 100003 do if f i then (Printf.printf "%d\n" i; exit 0) done


let k, t, ss = Scanf.scanf "%d %d %d %d %d %s" @@ fun n k r s p t -> k, t, Array.init n (fun i -> match t.[i] with 'r' -> p | 's' -> r | _ -> s)
let _ = Array.(iteri (fun i s -> if i >= k && ss.(i - k) > 0 && t.[i] = t.[i - k] then ss.(i) <- 0) ss; fold_left (+) 0 ss) |> Printf.printf "%d\n"

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 n, k, r, s, p, t = Scanf.scanf " %d %d %d %d %d %s" @@ fun a b c d e f -> a, b, c, d, e, f
let f = function 'r' -> p | 's' -> r | _ -> s
let ss = Array.init n (fun i -> f t.[i])
let _ = Array.(iteri (fun i s -> if i >= k && ss.(i - k) > 0 && t.[i] = t.[i - k] then ss.(i) <- 0) ss; fold_left (+) 0 ss) |> Printf.printf "%d\n"


let rec fix ~f x = f (fix ~f) x

let modulo = 1000000007
let (+@) a b = (a + b) mod modulo
let (-@) a b = (a - b + modulo) mod modulo
let ( *@) a b = (a * b) mod modulo
let rec ( **@) a n =
  if n = 0 then 1
  else if n mod 2 = 1 then a *@ a **@ (n-1)
  else let h = a **@ (n/2) in h *@ h
let modinv a = a **@ (modulo-2)
let (/@) a b = a *@ modinv b

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

let () =
  let n, g = input () in
  let _, lvs =
    fix 1 0 [] ~f:(fun dfs u p lvs ->
      let lv, lvs =
       List.fold_left (fun (lv, lvs) v ->
          if v = p then (lv, lvs)
          else
            let c, lvs' = dfs v u lvs
            in (c :: lv, lvs')) ([], lvs) g.(u)
      in
      let cn = List.fold_left (+) 0 lv in
      let lv = n-1-cn :: lv in
      1 + cn, lv :: lvs)
  in
  List.fold_left (fun ans lv ->
    let b0 = List.fold_left (fun b0 l -> b0 /@ (2 **@ l)) 1 lv in
    let b1 = List.fold_left (fun b1 l ->
      b1 +@ b0 *@ (2 **@ l) *@ (1 -@ modinv (2 **@ l))) 0 lv in
    ans +@ (1 -@ b0 -@ b1) /@ 2) 0 lvs
  |> Printf.printf "%d\n"

Score : 600 points

Problem Statement

Given is a tree T with N vertices. The i-th edge connects Vertex A_i and B_i (1 \leq A_i,B_i \leq N).

Now, each vertex is painted black with probability 1/2 and white with probability 1/2, which is chosen independently from other vertices. Then, let S be the smallest subtree (connected subgraph) of T containing all the vertices painted black. (If no vertex is painted black, S is the empty graph.)

Let the holeyness of S be the number of white vertices contained in S. Find the expected holeyness of S.

Since the answer is a rational number, we ask you to print it \bmod 10^9+7, as described in Notes.

Notes

When you print a rational number, first write it as a fraction \frac{y}{x}, where x, y are integers, and x is not divisible by 10^9 + 7
(under the constraints of the problem, such representation is always possible).

Then, you need to print the only integer z between 0 and 10^9 + 6, inclusive, that satisfies xz \equiv y \pmod{10^9 + 7}.

Constraints

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

1 \leq A_i,B_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

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

Output

Print the expected holeyness of S, \bmod 10^9+7.

Sample Input 1

3
1 2
2 3

Sample Output 1

125000001

If the vertices 1, 2, 3 are painted black, white, black, respectively, the holeyness of S is 1.

Otherwise, the holeyness is 0, so the expected holeyness is 1/8.

Since 8 \times 125000001 \equiv 1 \pmod{10^9+7}, we should print 125000001.

Sample Input 2

4
1 2
2 3
3 4

Sample Output 2

375000003

The expected holeyness is 3/8.

Since 8 \times 375000003 \equiv 3 \pmod{10^9+7}, we should print 375000003.

Sample Input 3

4
1 2
1 3
1 4

Sample Output 3

250000002

The expected holeyness is 1/4.

Sample Input 4

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

Sample Output 4

570312505


(* Vicfred
 * https://atcoder.jp/contests/abc148/tasks/abc148_a
 * implementation
 * *)

let solve a b = 6 - a - b

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

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 a = read_int ()
let _ = Printf.printf "%d\n" @@ 6 - a - read_int ()


(* Vicfred
 * https://atcoder.jp/contests/abc148/tasks/abc148_b
 * string manipulation
 * *)
open Printf
open Scanf

let main =
    scanf"%d %s %s" (fun n s t ->
    for i = 0 to n-1 do
        printf "%c%c" s.[i] t.[i]
    done
    );
    printf "\n"

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 () =
    let main () =
        let n = int_of_string (read_line ()) in
        let s, t = Scanf.scanf "%s %s" (fun s t -> s, t) in
        let rec loop i acc =
            if i = n then acc else loop (i + 1)
            (Printf.sprintf "%s%c%c" acc s.[i] t.[i])
        in
        loop 0 "" |> print_endline
    in
    main ()


let () = Scanf.scanf "%d %d %d\n" @@ fun n u v ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- b - 1 :: es.(a - 1);
      es.(b - 1) <- a - 1 :: es.(b - 1)
  done;
  let rec visit visited depth d u =
    if not visited.(u) then begin
      depth.(u) <- d;
      visited.(u) <- true;
      List.iter (visit visited depth (d + 1)) es.(u)
    end in
  let depthT = Array.make n 0 in
  let depthA = Array.make n 0 in
  visit (Array.make n false) depthT 0 (u - 1);
  visit (Array.make n false) depthA 0 (v - 1);
  Printf.printf "%d\n" @@
  Array.fold_left max min_int @@
  Array.init n @@ fun i ->
    if depthA.(i) < depthT.(i)
    then min_int
    else depthA.(i) - 1

Score : 600 points

Problem Statement

We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally.

Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.

Now, they will play a game of tag as follows:

1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.

2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.

3. Go back to step 1.

Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible.

Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy.

It can be proved that the game is bound to end.

Constraints

2 \leq N \leq 10^5

1 \leq u,v \leq N

u \neq v

1 \leq A_i,B_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N u v
A_1 B_1
:
A_{N-1} B_{N-1}

Output

Print the number of moves Aoki will perform before the end of the game.

Sample Input 1

5 4 1
1 2
2 3
3 4
3 5

Sample Output 1

2

If both players play optimally, the game will progress as follows:

Takahashi moves to Vertex 3.

Aoki moves to Vertex 2.

Takahashi moves to Vertex 5.

Aoki moves to Vertex 3.

Takahashi moves to Vertex 3.

Here, Aoki performs two moves.

Note that, in each move, it is prohibited to stay at the current vertex.

Sample Input 2

5 4 5
1 2
1 3
1 4
1 5

Sample Output 2

1

Sample Input 3

2 1 2
1 2

Sample Output 3

0

Sample Input 4

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

Sample Output 4

5


let () = Scanf.scanf "%d %d %d" @@ fun a b c -> Printf.printf "%s\n" @@
  if a + b + c >= 22
  then "bust"
  else "win"

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.


Scanf.sscanf (read_line ()) "%d %d %d" (fun a b c ->
    let r = a + b + c in
    Printf.printf "%s\n" (if r >= 22 then "bust" else "win"))


(* Vicfred
 * https://atcoder.jp/contests/abc147/tasks/abc147_b
 * string manipulation
 * *)
open Scanf

let main =
    let s = read_line() in
    Printf.printf "%d\n" @@
    Array.fold_left (+) 0 @@
    Array.init (String.length s/2) @@ fun i ->
        if s.[i] = s.[String.length s - i - 1] then 0 else 1

Score : 200 points

Problem Statement

Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.

Given is a string S. Find the minimum number of hugs needed to make S palindromic.

Constraints

S is a string consisting of lowercase English letters.

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

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of hugs needed to make S palindromic.

Sample Input 1

redcoder

Sample Output 1

1

For example, we can change the fourth character to o and get a palindrome redooder.

Sample Input 2

vvvvvv

Sample Output 2

0

We might need no hugs at all.

Sample Input 3

abcdabc

Sample Output 3

2


let rec pow x n = if n = 1 then x else x * pow x (n - 1)

let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let a = Array.init n @@ fun _ ->
  let l = Scanf.sscanf (read_line ()) "%d" @@ fun l -> l in
  Array.init l @@ fun _ -> Scanf.sscanf (read_line ()) "%d %d" @@ fun x y -> (x - 1, y)

let x = pow 2 n

let rec to_list x = function
  | 0 -> []
  | n -> x mod 2 :: to_list (x / 2) (n - 1)

let f arr =
  let res = Array.mapi(fun i t ->
    Array.fold_left (fun z (x, y) ->
      z && (t = 0 || arr.(x) = y)
    ) true a.(i)
  ) arr in
  Array.fold_left (&&) true res

let rec loop m i =
  if i = x then m
  else begin
    let arr = Array.of_list @@ to_list i n in
    loop (if f arr then max m (Array.fold_left (+) 0 arr) else m) (i + 1)
  end

let () = Printf.printf "%d\n" @@ loop 0 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 m = 1_000_000_007
let n = read_int()
let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i))

let () =
  let ans = ref 0 in
  for i = 0 to 59 do
    let b = 1 lsl i in
    let z = Array.fold_left (fun z a -> if a land b = 0 then z + 1 else z) 0 a in
    ans := (!ans + b mod m * z mod m * (n - z) mod m) mod m
  done;
  Printf.printf "%d\n" !ans

Score : 400 points

Problem Statement

We have N integers. The i-th integer is A_i.

Find \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

What is \mbox{ XOR }?

The XOR of integers A and B, A \mbox{ XOR } B, is defined as follows:

When A \mbox{ XOR } B is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if either A or B, but not both, has 1 in the 2^k's place, and 0 otherwise.

For example, 3 \mbox{ XOR } 5 = 6. (In base two: 011 \mbox{ XOR } 101 = 110.)

Constraints

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

0 \leq A_i < 2^{60}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the value \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} (A_i \mbox{ XOR } A_j), modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

6

We have (1\mbox{ XOR } 2)+(1\mbox{ XOR } 3)+(2\mbox{ XOR } 3)=3+2+1=6.

Sample Input 2

10
3 1 4 1 5 9 2 6 5 3

Sample Output 2

237

Sample Input 3

10
3 14 159 2653 58979 323846 2643383 27950288 419716939 9375105820

Sample Output 3

103715602

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


let () =
  let n = Scanf.scanf "%d\n" (fun d -> d) in
  let an = Array.init n @@
    fun x -> Scanf.scanf (if x==n-1 then "%d\n" else "%d ") @@ fun c -> c
  in
  let m = int_of_float(10.0 ** 9.) + 7 in
  let sum = ref 0 in
  for i = 0 to n-1 do
    for j = i to n-1 do
      sum := (!sum + (an.(i) lxor an.(j))) mod m
    done
  done;
  Printf.printf "%d\n" !sum


let () =
    let main () =
        let n = Scanf.scanf "%d" (fun n -> n) in
        let m = 1000000000 + 7 in
        let ( +@) a b = (a + b) mod m in
        let ( *@) a b = ((a mod m) * (b mod m)) mod m in
        let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
        let rec loop i acc =
            if i = 60 then acc else
                let d0, d1 = Array.fold_left (fun (acc1, acc2) v ->
                    if v land (1 lsl i) = 0 then acc1 + 1, acc2 else acc1, acc2 + 1) (0, 0) a
                in
                loop (i + 1) (acc +@ d0 *@ d1 *@ (1 lsl i))
        in
        Printf.printf "%d\n" (loop 0 0)
    in
    main ()


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) * 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


Scanf.scanf " %d %d %d %d" @@ fun a b c d -> print_endline @@ if a < c then "1" else "0"

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.


let () =
    let arr = Array.make 100001 false in
    arr.(0) <- true;
    for i = 0 to 100000 do
        if arr.(i) then (
            for j = 100 to 105 do
                if i + j <= 100000 then arr.(i + j) <- true
            done
        )
    done;
    let main () =
        let n = int_of_string (read_line ()) in
        Printf.printf "%d\n" (if arr.(n)then 1 else 0)
    in
    main ()

Score: 300 points

Problem Statement

AtCoder Mart sells 1000000 of each of the six items below:

Riceballs, priced at 100 yen (the currency of Japan) each

Sandwiches, priced at 101 yen each

Cookies, priced at 102 yen each

Cakes, priced at 103 yen each

Candies, priced at 104 yen each

Computers, priced at 105 yen each

Takahashi wants to buy some of them that cost exactly X yen in total.
Determine whether this is possible.

(Ignore consumption tax.)

Constraints

1 \leq X \leq 100000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If it is possible to buy some set of items that cost exactly X yen in total, print 1; otherwise, print 0.

Sample Input 1

615

Sample Output 1

1

For example, we can buy one of each kind of item, which will cost 100+101+102+103+104+105=615 yen in total.

Sample Input 2

217

Sample Output 2

0

No set of items costs 217 yen in total.


open Batteries

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_array n m e conv =
  let arr = Array.make_matrix n m e in
  Enum.Labels.iter (0 --^ n)
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

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

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

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

let () =
  Enum.Labels.map (0 --^ 1000)
    ~f:(fun i ->
        let d = String.to_list @@ Printf.sprintf "%03d" i in
        let last = List.Labels.fold_left d
            ~init:0 ~f:(fun i c ->
                if i < n then
                  match String.Exceptionless.find_from s i @@ String.of_char c with
                  | Some i -> succ i
                  | None -> n+1
                else n+1)
        in
        if last < n+1 then 1 else 0)
  |> Enum.sum
  |> Printf.printf "%d\n"

Score: 400 points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.

The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a 0.

Constraints

4 \leq N \leq 30000

S is a string of length N consisting of digits.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of S and set 224.

Erase the second digit of S and set 024.

Erase the third digit of S and set 024.

Erase the fourth digit of S and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329


let rec fix f x = f (fix f) x
let ( *@) a b = a * b mod 1000000007
let _ =
  Scanf.scanf "%d" @@ fun n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let hats = [|0; 0; 0|] in
  (1, 0) |> fix (fun f (d, i) ->
    if i >= n then d else begin
      let c = Array.fold_left (fun c h -> if a.(i) = h then c+1 else c) 0 hats in
      0 |> fix (fun f j ->
        if j >= 3 then ()
        else if hats.(j) = a.(i) then hats.(j) <- hats.(j) + 1
        else f (j+1));
      f (c *@ d, i+1)
    end)
  |> Printf.printf "%d\n"

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 scan_string () = Scanf.scanf " %s" (fun x -> x)
let print_int n = Printf.printf "%d\n" n

let calc s =
  if s = "SUN" then 7
  else if s = "MON" then 6
  else if s = "TUE" then 5
  else if s = "WED" then 4
  else if s = "THU" then 3
  else if s = "FRI" then 2
  else 1

let () =
  let s = scan_string() in
  print_int (calc s)

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 () =
  Printf.printf "%d\n" @@
  match read_line () with
  | "SUN" -> 7
  | "MON" -> 6
  | "TUE" -> 5
  | "WED" -> 4
  | "THU" -> 3
  | "FRI" -> 2
  | "SAT" -> 1


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

let () =
    let find_root ver =
        let rec loop prev cur =
            let rec loop_2 = function
                | [] -> cur
                | (hd, _) :: tl -> if hd = prev then loop_2 tl else loop cur hd
            in
            loop_2 ver.(cur)
        in
        loop 1 (fst (List.hd ver.(1)))
    in
    let main () =
        let n = int_of_string (read_line ()) in
        let ab = Array.init (n - 1) (fun i -> Scanf.sscanf (read_line ()) "%d %d" (fun a b -> a, b, i)) in
        let ver = Array.make (n + 1) [] in
        let used = Array.make (n + 1) S.empty in
        let col = Array.make (n + 1) 0 in
        Array.iter (fun (a, b, i) ->
            ver.(a) <- (b, i) :: ver.(a);
            ver.(b) <- (a, i) :: ver.(b)) ab;
        let k = Array.fold_left (fun acc l -> max acc (List.length l)) 0 ver in
        let find_color set =
            let rec loop i set = if S.mem i set then loop (i + 1) set else i in
            loop 1 set
        in
        let rec loop cur =
            let rec loop2 = function
                | [] -> ()
                | (hd, edge) :: tl -> (
                    if col.(edge) = 0 then (
                        let c = find_color used.(cur) in
                        col.(edge) <- c;
                        used.(cur) <- S.add c used.(cur);
                        used.(hd) <- S.add c used.(hd);
                        loop hd
                    );
                    loop2 tl
                )
            in
            loop2 ver.(cur)
        in
        let root = find_root ver in
        loop root;
        Printf.printf "%d\n" k;
        for i = 0 to n - 2 do
            Printf.printf "%d\n" col.(i)
        done
    in
    main ()

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


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

let rows = Array.init h @@ fun i -> String.length (Str.global_replace (Str.regexp "[^#]") "" ss.(i)) > 0
let ans = Array.make_matrix h w 0

let () =
  let num = ref 1 in
  Array.iteri (fun i s -> if rows.(i) then begin
    for j = 0 to w - 1 do
      if s.[j] = '#' then begin
        ans.(i).(j) <- !num;
        num := !num + 1
      end else if j > 0 && ans.(i).(j - 1)  > 0 then
        ans.(i).(j) <- ans.(i).(j - 1)
    done;
    for j = w - 2 downto 0 do
      if ans.(i).(j) = 0 then ans.(i).(j) <- ans.(i).(j + 1)
    done
  end) ss;
  for i = 0 to w - 1 do
    for j = 1 to h - 1 do
      if ans.(j).(i) = 0 && ans.(j - 1).(i) > 0 then ans.(j).(i) <- ans.(j - 1).(i)
    done;
    for j = h - 2 downto 0 do
      if ans.(j).(i) = 0 && ans.(j + 1).(i) > 0 then ans.(j).(i) <- ans.(j + 1).(i)
    done
  done;
  Array.iter (fun arr ->
    Array.map string_of_int arr |> Array.to_list |> String.concat " " |> print_endline
  ) ans

Score: 400 points

Problem Statement

Chokudai made a rectangular cake for contestants in DDCC 2020 Finals.

The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them.

The positions of the strawberries are given to you as H \times W characters s_{i, j} (1 \leq i \leq H, 1 \leq j \leq W). If s_{i, j} is #, the section at the i-th row from the top and the j-th column from the left contains a strawberry; if s_{i, j} is ., the section does not contain one. There are exactly K occurrences of #s.

Takahashi wants to cut this cake into K pieces and serve them to the contestants. Each of these pieces must satisfy the following conditions:

Has a rectangular shape.

Contains exactly one strawberry.

One possible way to cut the cake is shown below:

Find one way to cut the cake and satisfy the condition. We can show that this is always possible, regardless of the number and positions of the strawberries.

Constraints

1 \leq H \leq 300

1 \leq W \leq 300

1 \leq K \leq H \times W

s_{i, j} is # or ..

There are exactly K occurrences of # in s.

Input

Input is given from Standard Input in the following format:

H W K
s_{1, 1} s_{1, 2} \cdots s_{1, W}
s_{2, 1} s_{2, 2} \cdots s_{2, W}
:
s_{H, 1} s_{H, 2} \cdots s_{H, W}

Output

Assign the numbers 1, 2, 3, \dots, K to the K pieces obtained after the cut, in any order. Then, let a_{i, j} be the number representing the piece containing the section at the i-th row from the top and the j-th column from the left of the cake. Output should be in the following format:

a_{1, 1} \ a_{1, 2} \ \cdots \ a_{1, W}
a_{2, 1} \ a_{2, 2} \ \cdots \ a_{2, W}
:
a_{H, 1} \ a_{H, 2} \ \cdots \ a_{H, W}

If multiple solutions exist, any of them will be accepted.

Sample Input 1

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

Sample Output 1

1 2 2
1 3 4
5 5 4

One way to cut this cake is shown below:

Sample Input 2

3 7 7
#...#.#
..#...#
.#..#..

Sample Output 2

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

One way to cut this cake is shown below:

Sample Input 3

13 21 106
.....................
.####.####.####.####.
..#.#..#.#.#....#....
..#.#..#.#.#....#....
..#.#..#.#.#....#....
.####.####.####.####.
.....................
.####.####.####.####.
....#.#..#....#.#..#.
.####.#..#.####.#..#.
.#....#..#.#....#..#.
.####.####.####.####.
.....................

Sample Output 3

12 12 23 34 45 45 60 71 82 93 93 2 13 24 35 35 17 28 39 50 50
12 12 23 34 45 45 60 71 82 93 93 2 13 24 35 35 17 28 39 50 50
12 12 56 89 89 89 60 104 82 31 31 46 13 24 35 35 61 61 39 50 50
12 12 67 67 100 100 60 9 9 42 42 57 13 24 6 72 72 72 72 72 72
12 12 78 5 5 5 20 20 20 53 68 68 90 24 6 83 83 83 83 83 83
16 16 27 38 49 49 64 75 86 97 79 79 90 101 6 94 94 105 10 21 21
16 16 27 38 49 49 64 75 86 97 79 79 90 101 6 94 94 105 10 21 21
32 32 43 54 65 65 80 11 106 95 22 22 33 44 55 55 70 1 96 85 85
32 32 43 54 76 76 91 11 106 84 84 4 99 66 66 66 81 1 96 74 74
14 14 3 98 87 87 102 11 73 73 73 4 99 88 77 77 92 92 63 63 63
25 25 3 98 87 87 7 29 62 62 62 15 99 88 77 77 103 19 30 52 52
36 36 47 58 69 69 18 29 40 51 51 26 37 48 59 59 8 19 30 41 41
36 36 47 58 69 69 18 29 40 51 51 26 37 48 59 59 8 19 30 41 41


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

Score : 100 points

Problem Statement

Given is an integer r.

How many times is the area of a circle of radius r larger than the area of a circle of radius 1?

It can be proved that the answer is always an integer under the constraints given.

Constraints

1 \leq r \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r

Output

Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000


let n = read_int ()
let s = read_line ()
let _ = print_endline @@ if String.(sub s 0 @@ n / 2 = sub s (n / 2) @@ (n + 1) / 2) then "Yes" else "No"

Score : 200 points

Problem Statement

Given are a positive integer N and a string S of length N consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

Constraints

1 \leq N \leq 100

S consists of lowercase English letters.

|S| = N

Input

Input is given from Standard Input in the following format:

N
S

Output

If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let T = abc, and S = T + T.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

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

let n = scan "%d" id
let ls = Array.of_list @@ scan_lines n "%f %f" Tuple2.make

let () =
  let sets = permutations (0++^n) in
  ListL.map sets ~f:(fun set ->
      ListL.map (List.combine (List.take (pred @@ List.length set) set) (List.drop 1 set))
        ~f:(fun (i, j) ->
            let (x0,y0)= ls.(i) in
            let (x1,y1)= ls.(j) in
            Float.sqrt (Float.pow (x0-.x1) 2.0  +. Float.pow (y0 -. y1) 2.0)
          ) |> List.fsum
    ) |> List.fsum
  |> (fun v -> v /. (Float.of_int @@ List.length sets))
  |> Printf.printf "%f\n"

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


Scanf.scanf "%d" (fun n ->
    let xy = Array.init n (fun _ -> Scanf.scanf " %f %f" (fun x y -> x, y)) in

    let dist a b =
        let x1, y1 = xy.(a) in
        let x2, y2 = xy.(b) in
        sqrt ((x1 -. x2) *. (x1 -. x2) +. (y1 -. y2) *. (y1 -. y2))
    in

    let rec loop1 i1 acc =
        let rec loop2 i2 acc =
            if i2 = n then acc else
                loop2 (i2 + 1) (acc +. dist i1 i2)
        in
        if i1 = n then acc else
            loop1 (i1 + 1) (loop2 (i1 + 1) acc)
    in
    let s = loop1 0 0. *. 2. /. float n in
    Printf.printf "%.8f\n" s
)


let () =
    let calc (x1, y1) (x2, y2) =
        sqrt (float ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)))
    in
    let main () =
        let n = int_of_string (read_line ()) in
        let xy = Array.init n (fun _ ->
            Scanf.sscanf (read_line ()) "%d %d" (fun x y -> x, y))
        in
        let rec loop_i i acc =
            let rec loop_j j acc =
                if j >= n then acc else
                    let acc = calc xy.(i) xy.(j) +. acc in
                    loop_j (j + 1) acc
            in
            if i = n then acc else
                let acc = loop_j (i + 1) acc in
                loop_i (i + 1) acc
        in
        let r = loop_i 0 0. in
        let r = r *. 2. /. float n in
        Printf.printf "%.7f\n" r
    in
    main ()


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

module Comb = struct
  let prime = 1_000_000_007

  let ( * ) a b = a * b mod prime

  let rec pow n m =
    if m = 0 then 1
    else if m mod 2 = 0 then pow (n*n) (m/2)
    else n * pow (n*n) (m/2)

  let fact n =
    let rec aux m acc =
      if m = 0 then acc
      else aux (pred m) @@ m * acc
    in aux n 1

  let comb n k =
    if n <= 0 || k <= 0 then 1
    else
      fact n * (pow (fact k) (prime-2)) * (pow (fact (n - k)) (prime-2))
end

let (x,y) = scan "%d %d" Tuple2.make

exception Found

let () =
  try
    ListL.iter (0 ++ x) ~f:(fun k ->
        if (x-k) mod 2 = 0 &&  (x - k) / 2 = (y - 2*k) then
          Printf.printf "%d\n" @@ Comb.comb (k+ (x-k)/2) k)
  with Found -> ()

Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.


Scanf.scanf "%d %d" (fun n t ->
    let ab = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun a b -> a, b)) in
    Array.sort compare ab;
    let dp = Array.make (t + 1) 0 in
    Array.iter (fun (a, b) ->
        for j = t - 1 downto 0 do
            let idx = min t (j + a) in
            dp.(idx) <- max dp.(idx) (dp.(j) + b)
        done
    ) ab;
    Array.fold_left max 0 dp |> Printf.printf "%d\n"
)

Score : 500 points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be 50.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145


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

let upper_bound x s =
  match IntSet.split x s with
  | (_, true, _) -> x
  | (s, false, _) -> IntSet.max_elt s

let () = Scanf.scanf "%d %d" @@ fun n k ->
  try
    let (_, abcs) =
      Array.fold_right (fun c (s, abcs) ->
        let a = IntSet.max_elt s in
        let s = IntSet.remove a s in
        (*
         * a + b <= c
         * b <= c - a
         *)
        let b = upper_bound (c - a) s in
        let s = IntSet.remove b s in
        (s, (a, b, c) :: abcs)) (Array.init n (( + ) (k + 2 * n))) @@
        ( IntSet.of_list @@
          Array.to_list @@
          Array.init (2 * n) (( + ) k), [] ) in
    List.iter (fun (a, b, c) -> Printf.printf "%d %d %d\n" a b c) abcs
  with Not_found -> print_endline "-1"

Score : 700 points

Problem Statement

Given are positive integers N and K.

Determine if the 3N integers K, K+1, ..., K+3N-1 can be partitioned into N triples (a_1,b_1,c_1), ..., (a_N,b_N,c_N) so that the condition below is satisfied. Any of the integers K, K+1, ..., K+3N-1 must appear in exactly one of those triples.

For every integer i from 1 to N, a_i + b_i \leq c_i holds.

If the answer is yes, construct one such partition.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq 10^9

Input

Input is given from Standard Input in the following format:

N K

Output

If it is impossible to partition the integers satisfying the condition, print -1. If it is possible, print N triples in the following format:

a_1 b_1 c_1
:
a_N b_N c_N

Sample Input 1

1 1

Sample Output 1

1 2 3

Sample Input 2

3 3

Sample Output 2

-1


Scanf.scanf "%d" (fun n ->
    let l = Array.make n 0 in
    let r = Array.make n 0 in
    for i = 0 to n - 1 do
        Scanf.scanf " %d %d" (fun a b -> l.(i) <- a; r.(i) <- b + 1)
    done;

    let rec loop i p q =
        if i = n then p, q else
            let p = if l.(i) > l.(p) then i else p in
            let q = if r.(i) < r.(q) then i else q in
            loop (i + 1) p q
    in
    let p, q = loop 0 0 0 in

    let result1 =
        let rec loop j acc =
            if j = n then acc + max (r.(q) - l.(p)) 0 else
            if j = p || j = q then loop (j + 1) acc else
                loop (j + 1) (max acc (r.(j) - l.(j)))
        in
        loop 0 0
    in

    Printf.printf "%d\n" @@ (
        let work = Array.init n (fun i -> max (r.(i) - l.(p)) 0, max (r.(q) - l.(i)) 0) in
        Array.sort (fun (a0, b0) (a1, b1) -> compare (a0, -b0) (a1, -b1)) work;
        let s = Array.make (n + 1) (r.(p) - l.(p)) in
        let t = Array.make (n + 1) (r.(q) - l.(q)) in
        for i = 1     to     n do t.(i) <- min t.(i - 1) (snd work.(i - 1)); done;
        for i = n - 1 downto 0 do s.(i) <- min s.(i + 1) (fst work.(i    )); done;

        let rec loop i acc =
            if i = n + 1 then acc else loop (i + 1) (max acc (s.(i) + t.(i)))
        in
        loop 0 result1
    )
)

Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931


Scanf.scanf "%d" (fun n ->
    let l = Array.make n 0 in
    let r = Array.make n 0 in
    for i = 0 to n - 1 do
        Scanf.scanf " %d %d" (fun a b -> l.(i) <- a; r.(i) <- b + 1)
    done;

    let rec loop i p q =
        if i = n then p, q else
            let p = if l.(i) > l.(p) then i else p in
            let q = if r.(i) < r.(q) then i else q in
            loop (i + 1) p q
    in
    let p, q = loop 0 0 0 in

    let result1 =
        let rec loop j acc =
            if j = n then acc + max (r.(q) - l.(p)) 0 else
            if j = p || j = q then loop (j + 1) acc else
                loop (j + 1) (max acc (r.(j) - l.(j)))
        in
        loop 0 0
    in

    let result2 = (
        let work = Array.init n (fun i -> max (r.(i) - l.(p)) 0, max (r.(q) - l.(i)) 0) in
        Array.sort (fun (a0, b0) (a1, b1) -> compare (-b0, a0) (-b1, a1)) work;
        let s = Array.make (n + 1) 0 in
        let t = Array.make (n + 1) 0 in
        t.(0) <- r.(q) - l.(q);
        s.(n) <- r.(p) - l.(p);
        for i = 1 to n do
            let _, b = work.(i - 1) in
            t.(i) <- min t.(i - 1) b;
        done;
        for i = n - 1 downto 0 do
            let a, _ = work.(i) in
            s.(i) <- min s.(i + 1) a;
        done;

        let rec loop i acc =
            if i = n + 1 then acc else loop (i + 1) (max acc (s.(i) + t.(i)))
        in
        loop 0 result1
    )
    in
    Printf.printf "%d\n" result2
)


Scanf.scanf "%d" (fun n ->
    let l = Array.make n 0 in
    let r = Array.make n 0 in
    for i = 0 to n - 1 do
        Scanf.scanf " %d %d" (fun a b -> l.(i) <- a; r.(i) <- b + 1)
    done;

    let rec loop i p q =
        if i = n then p, q else
            let p = if l.(i) > l.(p) then i else p in
            let q = if r.(i) < r.(q) then i else q in
            loop (i + 1) p q
    in
    let p, q = loop 0 0 0 in

    let result1 =
        let rec loop j acc =
            if j = n then acc + max (r.(q) - l.(p)) 0 else
            if j = p || j = q then loop (j + 1) acc else
                loop (j + 1) (max acc (r.(j) - l.(j)))
        in
        loop 0 0
    in

    let result2 = (
        let work = Array.init n (fun i -> max (r.(i) - l.(p)) 0, max (r.(q) - l.(i)) 0) in
        Array.sort (fun (a0, b0) (a1, b1) -> compare (-b0, a0) (-b1, a1)) work;
        let s = Array.make (n + 1) 0 in
        let t = Array.make (n + 1) 0 in
        t.(0) <- r.(q) - l.(q);
        s.(n) <- r.(p) - l.(p);
        for i = 1 to n do
            let _, b = work.(i - 1) in
            t.(i) <- min t.(i - 1) b;
        done;
        for i = n - 1 downto 0 do
            let a, _ = work.(i) in
            s.(i) <- min s.(i + 1) a;
        done;

        let rec loop i acc =
            if i = n + 1 then acc else loop (i + 1) (max acc (s.(i) + t.(i)))
        in
        loop 0 0
    )
    in
    Printf.printf "%d\n" @@ max result1 result2
)


Scanf.scanf "%d" (fun n ->
    let lr = Array.init n (fun i -> Scanf.scanf " %d %d" (fun l r -> l, r)) in

    let rec loop i bestl besti =
        if i = n then besti else
            let l, r = lr.(i) in
            if l > bestl then loop (i + 1) l i
                         else loop (i + 1) bestl besti
    in
    let p = loop 0 0 0 in
    let rec loop i bestr besti =
        if i = n then besti else
            let l, r = lr.(i) in
            if r < bestr then loop (i + 1) r i
                         else loop (i + 1) bestr besti
    in
    let q = loop 0 max_int 0 in
    let lp, rp = lr.(p) in
    let lq, rq = lr.(q) in

    let result = if p = q then (
        let l0, r0 = lr.(p) in
        let rec loop j acc =
            if j = n then acc + r0 - l0 + 1 else
            if j = p then loop (j + 1) acc else
                let l1, r1 = lr.(j) in
                loop (j + 1) (max acc (r1 - l1 + 1))
        in
        loop 0 0
    ) else (
        let work = Array.map (fun (l, r) -> max (r - lp + 1) 0, max (rq - l + 1) 0) lr in
        Array.sort (fun (a0, b0) (a1, b1) -> compare (a0, -b0) (a1, -b1)) work;
        let work2 = Array.init (n + 1) (fun _ -> [| 0; 0 |]) in
        work2.(0).(1) <- rq - lq + 1;
        work2.(n).(0) <- rp - lp + 1;
        for i = 1 to n do
            let _, b = work.(i - 1) in
            work2.(i).(1) <- min work2.(i - 1).(1) b;
        done;
        for i = n - 1 downto 0 do
            let a, _ = work.(i) in
            work2.(i).(0) <- min work2.(i + 1).(0) a;
        done;

        Array.fold_left (fun acc arr -> max acc (arr.(0) + arr.(1))) 0 work2
    )
    in
    Printf.printf "%d\n" result
)


Scanf.scanf "%d" (fun n ->
    let lim = 10_000_000_000 in
    let lr = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun l r -> l, r)) in
    let lp = Array.fold_left (fun acc (l, r) -> max acc l) 0  lr in
    let rq = Array.fold_left (fun acc (l, r) -> min acc r) lim lr in
    let ab = Array.mapi (fun i (l, r)-> max (r - lp + 1) 0, - max (rq - l + 1) 0, l, r) lr in
    Array.sort compare ab;
    let s = Array.make (n - 1) 0 in
    let rec loop i l r =
        if i = n - 1 then () else
            let (_, _, ll, rr) = ab.(i) in
            let l = max ll l in
            let r = min rr r in
            let () = s.(i) <- max 0 (r - l + 1) in
            loop (i + 1) l r
    in
    loop 0 0 lim;

    let rec loop i l r =
        if i = 0 then () else
            let (_, _, ll, rr) = ab.(i) in
            let l = max ll l in
            let r = min rr r in
            let () = s.(i - 1) <- s.(i - 1) + max 0 (r - l + 1) in
            loop (i - 1) l r
    in
    loop (n - 1) 0 lim;

    Array.fold_left max 0 s |> Printf.printf "%d\n"
)


Scanf.scanf "%d" (fun n ->
    let lr = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun l r -> l, r)) in
    let lp = Array.fold_left (fun acc (l, r) -> max acc l) 0       lr in
    let rq = Array.fold_left (fun acc (l, r) -> min acc r) max_int lr in
    let ab = Array.mapi (fun i (l, r)-> max (r - lp + 1) 0, - max (rq - l + 1) 0, i) lr in
    Array.sort compare ab;
    let s = Array.make (n - 1) 0 in
    let rec loop i l r =
        if i = n - 1 then () else
            let (_, _, j) = ab.(i) in
            let ll, rr = lr.(j) in
            let l = max ll l in
            let r = min rr r in
            let () = s.(i) <- max 0 (r - l + 1) in
            loop (i + 1) l r
    in
    loop 0 0 max_int;

    let rec loop i l r =
        if i = 0 then () else
            let (_, _, j) = ab.(i) in
            let ll, rr = lr.(j) in
            let l = max ll l in
            let r = min rr r in
            let () = s.(i - 1) <- s.(i - 1) + max 0 (r - l + 1) in
            loop (i - 1) l r
    in
    loop (n - 1) 0 max_int;

    Array.fold_left max 0 s |> Printf.printf "%d\n"
)


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

let () = Scanf.scanf "%d" @@ fun n ->
  let i = max_divisor 1 1 n in
  Printf.printf "%d\n" @@ i + n / i - 2

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


let a, b, x = Scanf.scanf " %f %f %f" @@ fun a b c -> a, b, c
let f r = 180. *. r /. acos (-1.) |> Printf.printf "%.10f\n"
let _ = f @@ if x <= b *. a *. a /. 2. then atan2 b @@ 2. *. x /. (a *. b) else atan2 (2. *. (a *. b -. x /. a)) (a *. a)

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


open Scanf ;;
open Printf ;;

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

let rec powi a b = if b = 0 then 1 else a * powi a (b - 1);;

let list_sum a = List.fold_left (+) 0 a ;;

let rec read_ints n = if n = 0 then [] else read_int() :: read_ints (n - 1) ;;

let () =
  let n = read_int () in
  let k = read_int () in
  let a = read_ints n |> List.sort compare in
  let f = read_ints n |> List.sort compare |> List.rev in
  let rec search l r =
    if r - l = 1 then r
    else begin
      let m = (l + r) / 2 in
      let v = List.map2 (fun x y -> max 0 (x - m / y)) a f |> list_sum in
      if v <= k
        then search l m
        else search m r
    end
  in
  let ans = search (-1) (powi 10 12) in
  printf "%d\n" ans
  ;;

Score: 500 points

Problem Statement

Takahashi will take part in an eating contest. Teams of N members will compete in this contest, and Takahashi's team consists of N players numbered 1 through N from youngest to oldest. The consumption coefficient of Member i is A_i.

In the contest, N foods numbered 1 through N will be presented, and the difficulty of Food i is F_i. The details of the contest are as follows:

A team should assign one member to each food, and should not assign the same member to multiple foods.

It will take x \times y seconds for a member to finish the food, where x is the consumption coefficient of the member and y is the difficulty of the dish.

The score of a team is the longest time it takes for an individual member to finish the food.

Before the contest, Takahashi's team decided to do some training. In one set of training, a member can reduce his/her consumption coefficient by 1, as long as it does not go below 0. However, for financial reasons, the N members can do at most K sets of training in total.

What is the minimum possible score of the team, achieved by choosing the amounts of members' training and allocating the dishes optimally?

Constraints

All values in input are integers.

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

0 \leq K \leq 10^{18}

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

1 \leq F_i \leq 10^6\ (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N
F_1 F_2 ... F_N

Output

Print the minimum possible score of the team.

Sample Input 1

3 5
4 2 1
2 3 1

Sample Output 1

2

They can achieve the score of 2, as follows:

Member 1 does 4 sets of training and eats Food 2 in (4-4) \times 3 = 0 seconds.

Member 2 does 1 set of training and eats Food 3 in (2-1) \times 1 = 1 second.

Member 3 does 0 sets of training and eats Food 1 in (1-0) \times 2 = 2 seconds.

They cannot achieve a score of less than 2, so the answer is 2.

Sample Input 2

3 8
4 2 1
2 3 1

Sample Output 2

0

They can choose not to do exactly K sets of training.

Sample Input 3

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

Sample Output 3

12


Scanf.sscanf (read_line ()) "%d %d" (fun a b -> let r = max 0 (a - 2 * b) in Printf.printf "%d\n" r)

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


let i_inp_list : unit -> int list = fun () ->
  let inp_split = Str.split (Str.regexp " ") (input_line stdin) in
  List.map (fun x -> int_of_string x) (inp_split)

let rec pairs : 'a list -> ('a * 'a) list = function
    [] -> []
  | x :: xs -> List.map (fun y -> (x, y)) xs @ (pairs xs)

let () =
  let _ = Scanf.sscanf (input_line stdin) "%d" (fun n -> n) in
  let l = i_inp_list () in
  let p = pairs l in
  let ans = List.fold_right(fun (a,b) s -> a * b + s) p 0
  in
  print_int ans;
  print_newline ()

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312