Scanf.scanf "%d %d %d" (fun rr cc k ->
    let mat = Array.make_matrix rr cc 0 in
    for i = 1 to k do
        Scanf.scanf " %d %d %d" (fun rr cc v ->
            mat.(rr - 1).(cc - 1) <- v
        )
    done;

    let prev = Array.make cc 0 in
    for y = 0 to rr - 1 do
        let m = mat.(y) in
        let rec loop x work0 work1 work2 work3 =
            if x < cc then (
                let work0 = max work0 prev.(x) in
                let v = m.(x) in
                let work3 = max work3 (work2 + v) in
                let work2 = max work2 (work1 + v) in
                let work1 = max work1 (work0 + v) in
                prev.(x) <- max (max work3 work2) (max work1 work0);
                loop (x + 1) work0 work1 work2 work3
            )
        in
        loop 0 0 0 0 0
    done;
    Printf.printf "%d\n" (prev.(cc - 1))
)

Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

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

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

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

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142


let () = Scanf.scanf "%d" @@ fun x ->
  print_endline @@ if 30 <= x then "Yes" else "No"

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

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes

Submitted source-code file size, in bytes.

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

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


open Printf
open Scanf

let solve n d =
  let lxy = List.init n @@ fun _ -> scanf "%d %d " @@ fun x y -> (x, y) in
  let f ct (x, y) = if d * d >= x * x + y * y then ct + 1 else ct in
  List.fold_left f 0 lxy

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

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

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

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


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

let () =
  let n, d = f () in
  let d2 = d * d in
  let rec g i s =
    if i = n then
      print_int s
    else
      let x, y = f () in
      if x * x + y * y <= d2 then
        g (i + 1) (s + 1)
      else
        g (i + 1) s
  in g 0 0


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let c2i = int_of_char
let i2c = char_of_int
let f2i = int_of_float
let i2f = float_of_int

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putw ?yn:(yn=("Yes", "No")) b = puts (if b then fst yn else snd yn)
let puti i = puts @@ i2s i

module StaleList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  let scanl f z ls =
    let rec loop acl acc = function
      | [] -> rev acl
      | h::t ->
        let r = f acc h in
        loop (r::acl) r t
    in loop [] z ls

  let scanr f z ls =
    let rec loop acl acc = function
      | [] -> acl
      | h::t ->
        let r = f h acc in
        loop (r::acl) r t
    in loop [] z (rev ls)

  (* let scanli = scan_lefti *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = StaleList

module StaleArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = StaleArray

module StaleString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = StaleString

let spsp s = S.split_on_char ' ' s

module StaleSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = StaleSortedSet

module StaleSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = StaleSortedMap

module StaleRange = struct

  type t = Range of int * int

  let make lb ub = Range (lb, ub)

  let to_list r =
    let Range (lb, ub) = r in
    L.make (ub - lb) ((+) lb)

  let to_array r =
    let Range (lb, ub) = r in
      A.make (ub - lb) ((+) lb)

  let iter r f =
    let Range (lb, ub) = r in
    for i = lb to ub do f i done

  let iter2 r1 r2 f =
    let Range (lb1, ub1) = r1 and Range (lb2, ub2) = r2 in
      for i = lb1 to ub2 do
        for j = lb2 to ub2 do
          f i j
        done
      done
end

module R = StaleRange

let (---) lb ub = R.make lb ub
let (--^) lb ub = R.make lb (ub - 1)

module StaleGenericAlgorithms = struct

  let set_power ls =
    let rec loop ls pls =
      match ls with
      | [] -> pls
      | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
    in loop ls [[]]

  let rec bsearch_max_int f lb ub =
    if lb >= ub then (if f lb then lb else (lb - 1))
    else (
      let m = (lb + ub) / 2 in
      if f m then bsearch_max_int f (m + 1) ub
      else bsearch_max_int f lb m
    )

  let partial_sum n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s + h) (k + 1) t
    in
    loop 0 0 ls

end

module Gal = StaleGenericAlgorithms

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let print_carray aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%c " a); puts "]"

let print_matrix mat =
  puts "----";
  mat |> A.iter (fun r -> print_carray r);
  puts "----"

let _ =
  let (n, d) = rdi2 () in
  let xys = rdvi2 n in
  let flt = xys |> L.filter (fun (x,y) -> x*x + y*y <= d*d) in
  puti @@ L.len flt;
  ()


let k = read_int() in
let rec f m i =
  if i = k then -1
  else
    let m = (10 * m + 7) mod k in
    if m = 0 then i + 1
    else f m (i + 1)
in print_int (f 0 0)

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


let n = read_int ()
let c = read_line()

let rec r i s =
  if i = n then s
  else if c.[i] = 'R' then
    r (i + 1) (s + 1)
  else
    r (i + 1) s

let rec f i w r =
  if w == r then r
  else if c.[i] = 'W' then
    f (i + 1) (w + 1) r
  else
    f (i + 1) w (r - 1)

let () =
  let ans = f 0 0 (r 0 0) in
  Printf.printf "%d\n" ans

Score : 400 points

Problem Statement

An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

2 \leq N \leq 200000

c_i is R or W.

Input

Input is given from Standard Input in the following format:

N
c_{1}c_{2}...c_{N}

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the 1-st and 3-rd stones from the left, resulting in RWWR.

Change the color of the 4-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3


let () =
  let red = ref 0 in
  let rec charlist_of_string str n i =
    if i = n then []
    else if str.[i] = 'R' then (red := !red + 1; 'R' :: charlist_of_string str n (i+1))
    else 'W' :: charlist_of_string str n (i+1)  in
  let rec count lst target n i =
    if i = n then 0
    else match lst with
      | [] -> 0
      | h :: t -> if h = target then 1 + count t target n (i+1) else count t target n (i+1) in
  Scanf.scanf "%d\n%s\n" @@ fun n s ->
  let lst = charlist_of_string s (String.length s) 0 in
  Printf.printf "%d\n" (count lst 'W' (!red) 0)


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

    let count m =
        Array.fold_left (fun acc b -> acc + (b + m - 1) / m - 1) 0 a
    in

    let rec loop l r =
        if l = r then l else
            let m = (l + r) / 2 in
            if count m <= k then loop l m else loop (m + 1) r
    in
    loop 0 1000000001 |> Printf.printf "%d\n"
)

Score : 500 points

Problem Statement

We have N logs of lengths A_1,A_2,\cdots A_N.

We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.

Find the shortest possible length of the longest log after at most K cuts, and print it after rounding up to an integer.

Constraints

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

0 \leq K \leq 10^9

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print an integer representing the answer.

Sample Input 1

2 3
7 9

Sample Output 1

4

First, we will cut the log of length 7 at a point whose distance from an end of the log is 3.5, resulting in two logs of length 3.5 each.

Next, we will cut the log of length 9 at a point whose distance from an end of the log is 3, resulting in two logs of length 3 and 6.

Lastly, we will cut the log of length 6 at a point whose distance from an end of the log is 3.3, resulting in two logs of length 3.3 and 2.7.

In this case, the longest length of a log will be 3.5, which is the shortest possible result. After rounding up to an integer, the output should be 4.

Sample Input 2

3 0
3 4 5

Sample Output 2

5

Sample Input 3

10 10
158260522 877914575 602436426 24979445 861648772 623690081 433933447 476190629 262703497 211047202

Sample Output 3

292638192


module Fenwick = struct
    module type Element =
        sig
            type t
            val proc: t -> t -> t
            val zero: t
        end
    module Make(E: Element) = struct
        let create n = Array.make (n + 1) E.zero

        let update bit index value =
            let n = Array.length bit - 1 in
            let rec loop ii =
                if ii <= n then (
                    bit.(ii) <- E.proc bit.(ii) value;
                    loop (ii + (ii land (-ii)))
                )
            in
            loop index

        let query bit index =
            let rec loop ii acc =
                if ii > 0 then (
                    loop (ii - (ii land -ii)) (E.proc bit.(ii) acc)
                ) else acc
            in
            loop index E.zero
    end
end;;
type q = { r:int; l:int; idx:int };;
Scanf.scanf "%d %d" (fun n q ->
    let solve arr n query q =
        let ans = Array.make q 0 in
        let module F = Fenwick.Make (struct type t = int let proc = (+) let zero = 0 end) in
        let bit = F.create n in
        let last_visit = Array.make 500001 (-1) in

        let rec loop i qi =
            if i < n then (
                if last_visit.(arr.(i)) <> -1 then
                    F.update bit (last_visit.(arr.(i)) + 1) (-1);
                last_visit.(arr.(i)) <- i;

                F.update bit (i + 1) 1;

                let rec loop2 qi =
                    if qi < q && query.(qi).r = i then  (
                        ans.(query.(qi).idx) <-
                            F.query bit (query.(qi).r + 1) - F.query bit (query.(qi).l);
                        loop2 (qi + 1)
                    ) else qi
                in
                loop (i + 1) (loop2 qi)
            )
        in
        loop 0 0;
        Array.iter (Printf.printf "%d\n") ans
    in
    let c = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let query = Array.init q (fun i -> Scanf.scanf " %d %d" (fun l r -> { r = r - 1; l = l - 1; idx = i})) in
    Array.sort compare query;
    solve c n query q
)

Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

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

Sample Input 1

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

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

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

Sample Output 2

1
2
2
1
2
2
6
3
3
3


let x = read_int ()
let _ = (
  if x < 600 then "8" else
  if x < 800 then "7" else
  if x < 1000 then "6" else
  if x < 1200 then "5" else
  if x < 1400 then "4" else
  if x < 1600 then "3" else
  if x < 1800 then "2" else
  "1"
) |> print_endline

Score: 100 points

Problem Statement

M-kun is a competitor in AtCoder, whose highest rating is X.

In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:

From 400 through 599: 8-kyu

From 600 through 799: 7-kyu

From 800 through 999: 6-kyu

From 1000 through 1199: 5-kyu

From 1200 through 1399: 4-kyu

From 1400 through 1599: 3-kyu

From 1600 through 1799: 2-kyu

From 1800 through 1999: 1-kyu

What kyu does M-kun have?

Constraints

400 \leq X \leq 1999

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the kyu M-kun has, as an integer.
For example, if he has 8-kyu, print 8.

Sample Input 1

725

Sample Output 1

7

M-kun's highest rating is 725, which corresponds to 7-kyu.

Thus, 7 is the correct output.

Sample Input 2

1600

Sample Output 2

2

M-kun's highest rating is 1600, which corresponds to 2-kyu.

Thus, 2 is the correct output.


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

let rec loop red green blue i =
  if blue > green && green > red then "Yes" else
  if i >= k then "No" else (
    if red > green then loop red (green*2) blue (i+1) else
    loop red green (blue*2) (i+1)
  )

let () = print_endline @@ loop a b c 0

Score: 200 points

Problem Statement

M-kun has the following three cards:

A red card with the integer A.

A green card with the integer B.

A blue card with the integer C.

He is a genius magician who can do the following operation at most K times:

Choose one of the three cards and multiply the written integer by 2.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

1 \leq A, B, C \leq 7

1 \leq K \leq 7

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C
K

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now 7, 2, and 10, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now 7, 4, and 10, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now 7, 8, and 10, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.


open Batteries
let n, k = Scanf.sscanf (read_line()) "%d %d" (fun n k -> n,k)
let a = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ fun a -> a

let get_hyoutei start ed=
  let rec loop i result =
    if i > ed then result else (
      loop (i+1) result * a.(i)
    )
  in loop start 1

let rec hyoutei_loop i result =
  if i + k > n then List.rev result else (
    hyoutei_loop (i+1) (get_hyoutei i (i+k-1) :: result)
  )

let rec loop old lst =
  match lst with
  | [] -> ()
  | first :: rest ->
    if first > old then print_endline "Yes" else print_endline "No"; loop first rest

let r = hyoutei_loop 0 []
let () = loop (List.hd r) @@ List.tl r

Score: 300 points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into N terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through (K-1)-th terms: not given.

For each of the K-th through N-th terms: the multiplication of the scores in the last K exams, including the exam in the graded term.

M-kun scored A_i in the exam at the end of the i-th term.

For each i such that K+1 \leq i \leq N, determine whether his grade for the i-th term is strictly greater than the grade for the (i-1)-th term.

Constraints

2 \leq N \leq 200000

1 \leq K \leq N-1

1 \leq A_i \leq 10^{9}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 A_3 \ldots A_N

Output

Print the answer in N-K lines.

The i-th line should contain Yes if the grade for the (K+i)-th term is greater than the grade for the (K+i-1)-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

3-rd term: (96 \times 98 \times 95) = 893760

4-th term: (98 \times 95 \times 100) = 931000

5-th term: (95 \times 100 \times 20) = 190000

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the 3-rd term is equal to the grade for the 2-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let lst = Array.to_list (Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d) in
  let (bfr,(x,ans)) = List.fold_left
      (fun (bfr,(stock, money)) x ->
         if bfr < x then (x,(stock+(money/bfr), money - bfr*(money/bfr)))
         else (x, (0, money+bfr*stock))) (List.hd lst, (0, 1000)) (List.tl lst) in
  Printf.printf "%d\n" (bfr*x+ans)

Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.


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

    let calc list =
        Array.fold_left (fun acc (x, y, p) ->
            let dist =
                List.fold_left (fun acc2 (flag, l) ->
                    if flag then min acc2 (abs (x - l))
                             else min acc2 (abs (y - l))) max_int list
            in
            acc + dist * p) 0 xyp
    in
    let init = [ true, 0; false, 0 ] in
    let best = Array.make (n + 1) max_int in
    best.(0) <- calc init;

    let rec loop i c l =
        if i < n then (
            loop (i + 1) c l;
            let x, y, p = xyp.(i) in
            let l1 = ((true, x) :: l) in
            let l2 = ((false, y) :: l) in
            let q1 = calc l1 in
            let q2 = calc l2 in
            best.(c + 1) <- min best.(c + 1) (min q1 q2);
            loop (i + 1) (c + 1) l1;
            loop (i + 1) (c + 1) l2;
        )
    in
    loop 0 0 init;

    Array.iter (Printf.printf "%d\n") best;
)

Score: 500 points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of 1 between them. They correspond to the lines \ldots, y = -2, y = -1, y = 1, y = 2, \ldots in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the y-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of 1 between them. They correspond to the lines \ldots, x = -2, x = -1, x = 1, x = 2, \ldots in the two-dimensional coordinate plane.

There are N residential areas in New AtCoder City. The i-th area is located at the intersection with the coordinates (X_i, Y_i) and has a population of P_i. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose K streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, S, is minimized.

For each K = 0, 1, 2, \dots, N, what is the minimum possible value of S after building railroads?

Constraints

1 \leq N \leq 15

-10 \ 000 \leq X_i \leq 10 \ 000

-10 \ 000 \leq Y_i \leq 10 \ 000

1 \leq P_i \leq 1 \ 000 \ 000

The locations of the N residential areas, (X_i, Y_i), are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 Y_1 P_1
X_2 Y_2 P_2
: : :
X_N Y_N P_N

Output

Print the answer in N+1 lines.

The i-th line (i = 1, \ldots, N+1) should contain the minimum possible value of S after building railroads for the case K = i-1.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When K = 0, the residents of Area 1, 2, and 3 have to walk the distances of 1, 3, and 1, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, S, is 1 \times 300 + 3 \times 600 + 1 \times 800 = 2900.

When K = 1, if we build a railroad along the street corresponding to the line y = 4 in the coordinate plane, the walking distances of the citizens of Area 1, 2, and 3 become 1, 1, and 0, respectively.

Then, S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900.

We have many other options for where we build the railroad, but none of them makes S less than 900.

When K = 2, if we build a railroad along the street corresponding to the lines x = 1 and x = 3 in the coordinate plane, all citizens can reach a railroad with the walking distance of 0, so S = 0. We can also have S = 0 when K = 3.

The figure below shows the optimal way to build railroads for the cases K = 0, 1, 2.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases K = 1, 2.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case K = 3.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case K = 4.


open Printf
open Scanf

let id x = x

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

let run () =
    let result = ref 0 in
    for i = 0 to n - 1 do
        if (i + 1) mod 2 = 1 && ns.(i) mod 2 = 1 then incr result
    done;
    printf "%d\n" !result

let () = run ()

Score : 200 points

Problem Statement

We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i.

How many squares i satisfy both of the following conditions?

The assigned number, i, is odd.

The written integer is odd.

Constraints

All values in input are integers.

1 \leq N, a_i \leq 100

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \cdots a_N

Output

Print the number of squares that satisfy both of the conditions.

Sample Input 1

5
1 3 4 5 7

Sample Output 1

2

Two squares, Square 1 and 5, satisfy both of the conditions.

For Square 2 and 4, the assigned numbers are not odd.

For Square 3, the written integer is not odd.

Sample Input 2

15
13 76 46 15 50 98 93 77 31 43 84 90 6 24 14

Sample Output 2

3


let create_int_array n = Array.init n (fun _ -> 0)

let calc x y z = x * x + y * y + z * z + x * y + y * z + z * x

let case x y z =
  if x = y then (if y = z then 1 else 3)
  else if y = z then 3
  else 6

let () =
  let n = read_int () in
  let a = create_int_array n in

  let rec f x =
    let k = 6 * x * x in
    if k <= n then
      let rec g y =
        let k = x * x + 3 * y * y + 2 * x * y in
        if n < k then f (x + 1)
        else
          let rec h z =
            let k = calc x y z in
            if n < k then g (y + 1)
            else
              let w = case x y z in
              a.(k - 1) <- a.(k - 1) + w;
              h (z + 1)
          in h y
      in g x
  in

  f 1;
  ignore (Array.map (fun i -> Printf.printf "%d\n" i) a);
  ()

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


open Printf
open Scanf

let id x = x
exception Break

let n = scanf "%d"id

let int_sqrt n = truncate (sqrt (float n))

let run () =
    let nn = Array.init (n + 1) (fun _ -> ref 0) in
    let max = int_sqrt n in
    begin
        try for x = 1 to max do
            try for y = 1 to max do
                try for z = 1 to max do
                    let i = x * x + y * y + z * z + x * y + y * z + z * x in
                    if i > n then begin
                        raise Break
                    end else incr (nn.(i))
                done with Break -> ()
            done with Break -> ()
        done with Break -> ()
    end;
    for i = 1 to n do
        printf "%d\n" !(nn.(i))
    done

let () = run ()


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

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

let () = Scanf.scanf "%d\n%s" @@ fun n x ->
  let x = Array.init n @@ String.get x in
  let dp = Array.make (n + 2) 0 in
  for i = 1 to n + 1 do
    dp.(i) <- 1 + dp.(i mod popcnt i)
  done;
  let pop = Array.fold_right (function '0' -> Fun.id | '1' -> succ) x 0 in
  let m0 = Array.fold_left (fun acc c -> (2 * acc + if c = '0' then 0 else 1) mod (pop + 1)) 0 x in
  let m1 = Array.fold_left (fun acc c -> (2 * acc + if c = '0' then 0 else 1) mod (pop - 1)) 0 x in
  Fun.flip Array.iteri x @@ fun i c ->
    let i = n - i - 1 in
    Printf.printf "%d\n" @@
    succ @@
    Array.get dp @@
    if c = '0'
    then (m0 + power (fun x y -> (x * y) mod (pop + 1)) 1 2 i) mod (pop + 1)
    else (m1 + pop - 1 - power (fun x y -> (x * y) mod (pop - 1)) 1 2 i) mod (pop - 1)

Score : 400 points

Problem Statement

Let \mathrm{popcount}(n) be the number of 1s in the binary representation of n.
For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0.

Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n is divided by \mathrm{popcount}(n)." (It can be proved that, under the constraints of this problem, n always becomes 0 after a finite number of operations.)

For example, when n=7, it becomes 0 after two operations, as follows:

\mathrm{popcount}(7)=3, so we divide 7 by 3 and replace it with the remainder, 1.

\mathrm{popcount}(1)=1, so we divide 1 by 1 and replace it with the remainder, 0.

You are given an integer X with N digits in binary.
For each integer i such that 1 \leq i \leq N, let X_i be what X becomes when the i-th bit from the top is inverted.
Find f(X_1), f(X_2), \ldots, f(X_N).

Constraints

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

X is an integer with N digits in binary, possibly with leading zeros.

Input

Input is given from Standard Input in the following format:

N
X

Output

Print N lines. The i-th line should contain the value f(X_i).

Sample Input 1

3
011

Sample Output 1

2
1
1

X_1 = 7, which will change as follows: 7 \rightarrow 1 \rightarrow 0. Thus, f(7) = 2.

X_2 = 1, which will change as follows: 1 \rightarrow 0. Thus, f(1) = 1.

X_3 = 2, which will change as follows: 2 \rightarrow 0. Thus, f(2) = 1.

Sample Input 2

23
00110111001011011001110

Sample Output 2

2
1
2
2
1
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
1
3


open Printf
open Scanf

let id x = x

let print_ans (a, b, c, d) =
  printf "AC x %d\n" a;
  printf "WA x %d\n" b;
  printf "TLE x %d\n" c;
  printf "RE x %d\n" d

let solve n =
  let ss = List.init n (fun _ -> scanf "%s " id) in
  let ht = Hashtbl.create n in
  Hashtbl.replace ht "AC" 0;
  Hashtbl.replace ht "WA" 0;
  Hashtbl.replace ht "TLE" 0;
  Hashtbl.replace ht "RE" 0;
  List.iter (fun s -> let v = Hashtbl.find ht s in Hashtbl.replace ht s (v + 1)) ss;
  (Hashtbl.find ht "AC", Hashtbl.find ht "WA", Hashtbl.find ht "TLE", Hashtbl.find ht "RE")

let () =
  scanf "%d " solve |> print_ans

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Array.sort (Fun.flip compare) as_;
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) as_.(1) @@
  Array.sub as_ 0 (n - 2)

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


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

    let z = 1_000_000_007 in

    let ( *@) a b = (((a * b) mod z) + z) mod z in

    let rec loop rest i m z p minm minp =
        if rest = 0 then m, z, p, minm, minp else
            let m = if a.(i) < 0 then m + 1 else m in
            let z = if a.(i) = 0 then z + 1 else z in
            let p = if a.(i) > 0 then p + 1 else p in
            loop (rest - 1) (i - 1) m z p (if a.(i) < 0 then i else minm) (if a.(i) > 0 then i else minp)
    in
    let m, z, p, minm, minp = loop k (n - 1) 0 0 0 n n in
    let prod f t =
        let rec loop i acc =
            if i > t then acc else loop (i + 1) (acc *@ a.(i))
        in
        loop f 1
    in
    let prod2 f t skip alter =
        let rec loop i acc =
            if i > t then acc else
                let acc = if i = skip then acc else acc *@ a.(i) in
                loop (i + 1) acc
        in
        loop f a.(alter)
    in
    Printf.printf "%d\n" @@ if z > 0 then 0 else ( (* z = 0 *)
        if k = n then prod 0 (n - 1) else
        if m mod 2 = 0 then prod (n - k) (n - 1) else ( (* z = 0 && m % 2 = 1 *)
            let rec loop i maxm maxp zero =
                if i = n - k then maxm, maxp, zero else
                    if a.(i) > 0 then loop (i + 1) maxm i zero else
                    if a.(i) < 0 then loop (i + 1) i maxp zero else
                                      loop (i + 1) maxm maxp true
            in
            let maxm, maxp, zero = loop 0 (-1) (-1) false in
            (* case:
                * p > 0 && m % 2 = 1:
                    * maxm >= 0 && maxp >= 0 -> compare prod / a.(minm) * a.(maxp)
                                                        prod / a.(minp) * a.(maxm)
                    * maxm >= 0 && maxp <  0 -> prod / a.(minp) * a.(maxm)
                    * maxm <  0 && maxp >= 0 -> prod / a.(minm) * a.(maxp)
                    * else -> 0
                * p = 0 && m % 2 = 1 && zero -> 0
                * p = 0 && m % 2 = 1 && !zero -> phase2
             *)
            if p > 0 then (
                if maxm >= 0 && maxp >= 0 then (
                    if a.(maxp) * a.(minp) > a.(maxm) * a.(minm) then prod2 (n - k) (n - 1) minm maxp
                                                                 else prod2 (n - k) (n - 1) minp maxm
                ) else
                if maxm >= 0 && maxp <  0 then prod2 (n - k) (n - 1) minp maxm else
                if maxm <  0 && maxp >= 0 then prod2 (n - k) (n - 1) minm maxp else 0
            ) else if zero then 0 else prod 0 (k - 1)
        )
    )
)

Score : 500 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

We will choose exactly K of these elements. Find the maximum possible product of the chosen elements.

Then, print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Constraints

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

|A_i| \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 \ldots A_N

Output

Print the maximum product modulo (10^9+7), using an integer between 0 and 10^9+6 (inclusive).

Sample Input 1

4 2
1 2 -3 -4

Sample Output 1

12

The possible products of the two chosen elements are 2, -3, -4, -6, -8, and 12, so the maximum product is 12.

Sample Input 2

4 3
-1 -2 -3 -4

Sample Output 2

1000000001

The possible products of the three chosen elements are -24, -12, -8, and -6, so the maximum product is -6.

We print this value modulo (10^9+7), that is, 1000000001.

Sample Input 3

2 1
-1 1000000000

Sample Output 3

1000000000

The possible products of the one chosen element are -1 and 1000000000, so the maximum product is 1000000000.

Sample Input 4

10 10
1000000000 100000000 10000000 1000000 100000 10000 1000 100 10 1

Sample Output 4

999983200

Be sure to print the product modulo (10^9+7).


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

let () = Printf.printf "%d" @@ a + a * a + a * a * a

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


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


(* unihernandez22
 * https://atcoder.jp/contests/abc171/tasks/abc171_a
 * implementation
 * *)

let is_uppercase = function
    'A' .. 'Z' -> true
    | _ -> false;;

Printf.printf "%c\n" @@
Scanf.scanf "%c" @@ fun a ->
    if is_uppercase a then 'A'
    else 'a';;

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


let () =
  Scanf.scanf "%d %d\n" @@ fun n k ->
  let prr = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ fun d -> d in
  let () = Array.fast_sort compare prr in
  let plst = Array.to_list prr in
  let rec sumk lst k = if k = 0 then 0 else (List.hd lst) + sumk (List.tl lst) (k-1) in
  Printf.printf "%d\n" (sumk plst k)

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


open Printf
open Scanf

module L =
  struct
    include List

    let rec take n = function
        [] -> []
      | h :: t when n > 0 -> h :: take (n - 1) t
      | _ -> []

    let sum = fold_left (+) 0
  end

let id x = x

let solve n k =
  let ps = L.init n @@ fun _ -> scanf "%d " id in
  L.sum @@ L.take k @@ List.sort compare ps

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


let () = Scanf.scanf "%d" @@ fun n ->
  let pow = Array.make 12 0 in
  pow.(0) <- 1;
  for i = 0 to 10 do
    pow.(i + 1) <- 26 * pow.(i)
  done;
  let rec aux n d (p :: ps) k =
    if n < p
    then k n d
    else aux (n - p) (d + 1) ps k in
  let rec solve acc n = function
    | 0 -> acc
    | d -> solve (Char.chr (Char.code 'a' + n mod 26) :: acc) (n / 26) (d - 1) in
  List.iter print_char @@ aux n 0 (Array.to_list pow) @@ solve ['\n']

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


let rec solve acc = function
  | 0 -> acc
  | n -> solve (Char.chr (Char.code 'a' + n mod 26) :: acc) (n / 26)

let () = Scanf.scanf "%d" @@ fun n ->
  let pow = Array.make 12 0 in
  pow.(0) <- 1;
  for i = 0 to 10 do
    pow.(i + 1) <- 26 * pow.(i)
  done;
  let rec aux d n (p :: ps) =
    if n < p
    then (d, n)
    else aux (d + 1) (n - p) ps in
  let rec solve acc n = function
    | 0 -> acc
    | d -> solve (Char.chr (Char.code 'a' + n mod 26) :: acc) (n / 26) (d - 1) in
  let (d, n) = aux 0 n @@ Array.to_list pow in
  List.iter print_char @@ solve ['\n'] n d


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

let code_a = int_of_char 'a'

let char_of_code code = char_of_int (code_a + code)

let rec alp_of_int acc n =
  let acc = (n mod 26) :: acc in
  if n > 25 then alp_of_int acc (n / 26 - 1)
  else acc

let () =
  (n - 1) |> alp_of_int [] |> List.map char_of_code |> List.map Char.escaped |> String.concat "" |> print_endline


Scanf.scanf "%d" (fun n ->
    let n = n - 1 in
    let calc r digits =
        let rec loop r i acc =
            if i = 0 then acc else
                loop (r / 26) (i - 1) (Printf.sprintf "%c%s" (char_of_int ((r mod 26) + 97)) acc)
        in
        loop r digits ""
    in
    let rec loop p digits d k =
        if n < k then calc (n - p) digits else
            loop k (digits + 1) (d * 26) (k + d)
    in
    loop 0 1 (26 * 26) 26 |> print_endline
)


let () = Scanf.scanf "%d\n" @@ fun n ->
  let sum = ref 0 in
  let cnt = Array.make 100001 0 in
  for i = 0 to n - 1 do
    Scanf.scanf "%d " @@ fun a ->
    sum := !sum + a;
    cnt.(a) <- cnt.(a) + 1
  done;
  Scanf.scanf "%d\n" @@ fun q ->
    for i = 0 to q - 1 do
      Scanf.scanf "%d %d\n" @@ fun b c ->
      sum := !sum + (c - b) * cnt.(b);
      cnt.(c) <- cnt.(c) + cnt.(b);
      cnt.(b) <- 0;
      Printf.printf "%d\n" !sum
    done;

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

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

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


open Batteries
let n = read_int ()
let a = read_line () |> String.split_on_char ' ' |> List.map int_of_string
let q = read_int ()

let dp = Array.init 100010 @@ fun _ -> 0
let rec dp_loop lst result =
  match lst with
  | [] -> result
  | first :: rest -> dp.(first) <- dp.(first)+1; dp_loop rest (result+first)
let all = dp_loop a 0

let rec q_loop i now_all =
  if i >= q then () else (
    Scanf.sscanf (read_line()) "%d %d" (fun b c ->
    let new_all = (now_all - (dp.(b)*b) - (dp.(c)*c) + ((dp.(b)+dp.(c))*c)) in
      Printf.printf "%d\n" new_all;
      (* Printf.printf "dp(b)*b: %d, dp(b): %d\n" (dp.(b)*b) (dp.(b));
      Printf.printf "dp(c)*c: %d, dp(c): %d\n" (dp.(c)*c) dp.(c); *)
      dp.(c) <- dp.(c) + dp.(b);
      dp.(b) <- 0;
      q_loop (i+1) new_all
    )
  )

let _ = q_loop 0 all


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

Score : 500 points

Problem Statement

There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.

Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.

Recently, they learned the operation called xor (exclusive OR).

What is xor?

For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:

When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3~\textrm{xor}~5 = 6.

They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.

We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.

Constraints

All values in input are integers.

2 \leq N \leq 200000

N is even.

0 \leq a_i \leq 10^9

There exists a combination of integers on the scarfs that is consistent with the given information.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print a line containing N integers separated with space.

The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.

If there are multiple possible solutions, you may print any of them.

Sample Input 1

4
20 11 9 24

Sample Output 1

26 5 7 22

5~\textrm{xor}~7~\textrm{xor}~22 = 20

26~\textrm{xor}~7~\textrm{xor}~22 = 11

26~\textrm{xor}~5~\textrm{xor}~22 = 9

26~\textrm{xor}~5~\textrm{xor}~7 = 24

Thus, this output is consistent with the given information.


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

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

let () = Scanf.scanf "%d %s" @@ fun k s ->
  (* comb.(i) = (|S| - 1 + i)C(|S| - 1) *)
  let comb = Array.make (k + 1) 0 in
  comb.(0) <- 1;
  for i = 1 to k do
    comb.(i) <- (String.length s - 1 + i) *^ comb.(i - 1) /^ i
  done;
  Printf.printf "%d\n" @@
  Array.fold_left ( +^ ) (power ( *^ ) 1 26 k) @@
  Array.init k @@ fun i ->
    power ( *^ ) (power ( *^ ) comb.(k - i) 25 (k - i)) 26 i

Score: 600 points

Problem Statement

How many strings can be obtained by applying the following operation on a string S exactly K times: "choose one lowercase English letter and insert it somewhere"?

The answer can be enormous, so print it modulo (10^9+7).

Constraints

K is an integer between 1 and 10^6 (inclusive).

S is a string of length between 1 and 10^6 (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

K
S

Output

Print the number of strings satisfying the condition, modulo (10^9+7).

Sample Input 1

5
oof

Sample Output 1

575111451

For example, we can obtain proofend, moonwolf, and onionpuf, while we cannot obtain oofsix, oofelevennn, voxafolt, or fooooooo.

Sample Input 2

37564
whydidyoudesertme

Sample Output 2

318008117


Scanf.scanf "%d" (fun x ->
    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 q = lcm x 360 in
    Printf.printf "%d\n" @@ q / x
)

Score : 200 points

Problem Statement

Takahashi is standing on a two-dimensional plane, facing north. Find the minimum positive integer K such that Takahashi will be at the starting position again after he does the following action K times:

Go one meter in the direction he is facing. Then, turn X degrees counter-clockwise.

Constraints

1 \leq X \leq 179

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of times Takahashi will do the action before he is at the starting position again.

Sample Input 1

90

Sample Output 1

4

Takahashi's path is a square.

Sample Input 2

1

Sample Output 2

360


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

let () = Scanf.scanf "%d\n" @@ fun x ->
  Printf.printf "%d\n" @@ 360 / gcd 360 x


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 = if n <= m then  List.range n `To m else []
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) (0 ++^ 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 itoa n = Char.chr (n + Char.code '0')

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

(* ===== MAIN ===== *)

let xs = scan_list ~sep:' ' int_of_string

let () =
  List.fold_lefti (fun state i x ->
      if (state >= 1) then state
      else if (x = 0) then (i+1)
      else (-1)) (-1) xs
  |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

We have five variables x_1, x_2, x_3, x_4, and x_5.

The variable x_i was initially assigned a value of i.

Snuke chose one of these variables and assigned it 0.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned 0.

Constraints

The values of x_1, x_2, x_3, x_4, and x_5 given as input are a possible outcome of the assignment by Snuke.

Input

Input is given from Standard Input in the following format:

x_1 x_2 x_3 x_4 x_5

Output

If the variable Snuke assigned 0 was x_i, print the integer i.

Sample Input 1

0 2 3 4 5

Sample Output 1

1

In this case, Snuke assigned 0 to x_1, so we should print 1.

Sample Input 2

1 2 0 4 5

Sample Output 2

3


let x1,x2,x3,x4,x5 = Scanf.sscanf (read_line()) "%d %d %d %d %d" (fun q w e r t -> q,w,e,r,t)
let _ = (
  if x1 = 0 then "1" else
  if x2 = 0 then "2" else
  if x3 = 0 then "3" else
  if x4 = 0 then "4" else
"5") |> print_endline


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

let x, y = Scanf.sscanf (read_line ()) "%f %f" ( fun x y -> x, y)

let kame = (y -. (2.0 *. x)) /. 2.0
let tsuru = x -. kame
let () =
        (
                if kame = (ceil kame) && tsuru = (ceil tsuru) && kame >= 0.0 && tsuru >= 0.0 then
                        "Yes"
                else
                        "No"
        ) |> Printf.printf "%s\n"

Score : 200 points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

1 \leq X \leq 100

1 \leq Y \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

Sample Input 1

3 8

Sample Output 1

Yes

The statement "there are 3 animals in total in the garden, and they have 8 legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.


let () = Scanf.scanf "%d %d %d\n%d %d %d %d\n" @@ fun h w k x1 y1 x2 y2 ->
  let x1 = x1 - 1 in
  let x2 = x2 - 1 in
  let y1 = y1 - 1 in
  let y2 = y2 - 1 in
  let css = Array.init h @@ fun _ -> Scanf.scanf "%s\n" Fun.id in
  let d =
    Array.init h @@ fun _ ->
      Array.init w @@ fun _ ->
        Array.init 5 @@ fun _ -> (max_int, max_int) in
  let es (i, j, s, dir) =
    List.filter_map (fun (i, j, dir') ->
      if i < 0 || h <= i || j < 0 || w <= j || css.(i).[j] = '@'
      then None
      else if dir = dir' && s < k
      then Some ((i, j, s + 1, dir'), false)
      else Some ((i, j, 1, dir'), true))
    [(i - 1, j, 1); (i + 1, j, 2); (i, j - 1, 3); (i, j + 1, 4)] in
  let rec bfs p = function
    | [] -> ()
    | vs -> bfs (p + 1) @@ List.fold_left (dfs p) [] vs
  and dfs p vs ((i, j, s, dir) as v) =
    if d.(i).(j).(dir) <= (p, s)
    then vs
    else begin
      d.(i).(j).(dir) <- (p, s);
      List.fold_left (fun vs (v, b) ->
        if b
        then v :: vs
        else dfs p vs v) vs (es v)
    end in
  bfs 0 [(x1, y1, 0, 0)];
  Printf.printf "%d\n" @@
  (fun x -> if max_int <= x then -1 else x) @@
  fst @@ Array.fold_left min (max_int, max_int) d.(x2).(y2)

Score : 600 points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with H east-west rows and W north-south columns. Let (i,j) be the square at the i-th row from the north and j-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square (i,j) has a lotus leaf on it if c_{ij} is @, and it does not if c_{ij} is ..

In one stroke, Snuke can move between 1 and K squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2).
If the travel from (x_1,y_1) to (x_2,y_2) is impossible, point out that fact.

Constraints

1 \leq H,W,K \leq 10^6

H \times W \leq 10^6

1 \leq x_1,x_2 \leq H

1 \leq y_1,y_2 \leq W

x_1 \neq x_2 or y_1 \neq y_2.

c_{i,j} is . or @.

c_{x_1,y_1} = .

c_{x_2,y_2} = .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

H W K
x_1 y_1 x_2 y_2
c_{1,1}c_{1,2} .. c_{1,W}
c_{2,1}c_{2,2} .. c_{2,W}
:
c_{H,1}c_{H,2} .. c_{H,W}

Output

Print the minimum number of strokes Snuke takes to travel from the square (x_1,y_1) to (x_2,y_2), or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square (3,2).
He can reach the square (3, 4) by making five strokes as follows:

From (3, 2), go west one square to (3, 1).

From (3, 1), go north two squares to (1, 1).

From (1, 1), go east two squares to (1, 3).

From (1, 3), go east one square to (1, 4).

From (1, 4), go south two squares to (3, 4).

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1


let () =
  Scanf.scanf "%d %d\n%d %d\n%d\n" @@ fun a v b w t ->
  Printf.printf "%s\n" (if v <= w || abs(a-b)/(v-w) >= t then "NO" else "YES")

Score : 200 points

Problem Statement

Two children are playing tag on a number line. (In the game of tag, the child called "it" tries to catch the other child.) The child who is "it" is now at coordinate A, and he can travel the distance of V per second.
The other child is now at coordinate B, and she can travel the distance of W per second.

He can catch her when his coordinate is the same as hers.
Determine whether he can catch her within T seconds (including exactly T seconds later).
We assume that both children move optimally.

Constraints

-10^9 \leq A,B \leq 10^9

1 \leq V,W \leq 10^9

1 \leq T \leq 10^9

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A V
B W
T

Output

If "it" can catch the other child, print YES; otherwise, print NO.

Sample Input 1

1 2
3 1
3

Sample Output 1

YES

Sample Input 2

1 2
3 2
3

Sample Output 2

NO

Sample Input 3

1 2
3 3
3

Sample Output 3

NO


let rec floor_sqrt acc acc_x_2_x_r sq_acc_minus_z r sq_r =
  if r = 0 then acc
  else
    let sq_acc_minus_z' = sq_acc_minus_z + acc_x_2_x_r + sq_r in
    ( if sq_acc_minus_z' <= 0 then
        floor_sqrt (acc + r) ((acc_x_2_x_r lsr 1) + sq_r) sq_acc_minus_z'
      else
        floor_sqrt acc (acc_x_2_x_r lsr 1) sq_acc_minus_z) (r lsr 1) (sq_r lsr 2)
let floor_sqrt z = floor_sqrt 0 0 (~-z) (1 lsl 30) (1 lsl 60)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let vs = Array.make n 0 in
  let ws = Array.make n 0 in
  for i = 0 to n - 1 do
    Scanf.scanf "%d %d\n" @@ fun v w ->
      vs.(i) <- v;
      ws.(i) <- w
  done;
  Scanf.scanf "%d\n" @@ fun q ->
    let vls = Array.init q @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun v l -> v, l in
    let maxl = Array.fold_right (fun (_, l) -> max l) vls min_int in
    let n' = floor_sqrt n in
    let dp = Bigarray.Array2.create Bigarray.int Bigarray.c_layout (n' + 1) (maxl + 1) in
    Bigarray.Array2.fill (Bigarray.Array2.sub_left dp 0 1) 0;
    for i = 1 to n' do
      let v = Array.unsafe_get vs (i - 1) in
      let w = Array.unsafe_get ws (i - 1) in
      Bigarray.Array2.blit
        (Bigarray.Array2.sub_left dp (i lsr 1) 1)
        (Bigarray.Array2.sub_left dp i 1);
      for j = w to maxl do
        let d = Bigarray.Array2.unsafe_get dp (i lsr 1) j in
        let d' = v + Bigarray.Array2.unsafe_get dp (i lsr 1) (j - w) in
        if d < d' then Bigarray.Array2.unsafe_set dp i j d'
      done
    done;
    let rec solve l i s m =
      if l < 0
      then m
      else if i <= n'
      then max m (s + Bigarray.Array2.unsafe_get dp i l)
      else solve l (i lsr 1) s @@ solve (l - Array.unsafe_get ws (i - 1)) (i lsr 1) (s + Array.unsafe_get vs (i - 1)) m in
    Array.iter (fun (v, l) -> Printf.printf "%d\n" @@ solve l v 0 min_int) vls

Score : 700 points

Problem Statement

We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N.
Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].

Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i.
Now, process the following query Q times:

Given are a vertex v of the tree and a positive integer L.
Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L.
Find the maximum possible total value of the chosen items.

Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k (k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i.

Constraints

All values in input are integers.

1 \leq N < 2^{18}

1 \leq Q \leq 10^5

1 \leq V_i \leq 10^5

1 \leq W_i \leq 10^5

For the values v and L given in each query, 1 \leq v \leq N and 1 \leq L \leq 10^5.

Input

Let v_i and L_i be the values v and L given in the i-th query.
Then, Input is given from Standard Input in the following format:

N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q

Output

For each integer i from 1 through Q,
the i-th line should contain the response to the i-th query.

Sample Input 1

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

Sample Output 1

0
3
3

In the first query, we are given only one choice: the item with (V, W)=(1,2). Since L = 1, we cannot actually choose it, so our response should be 0.

In the second query, we are given two choices: the items with (V, W)=(1,2) and (V, W)=(2,3). Since L = 5, we can choose both of them, so our response should be 3.

Sample Input 2

15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227

Sample Output 2

256
255
250
247
255
259
223
253


Scanf.scanf "%d %d" (fun a b -> print_int (a * b))

Score : 100 points

Problem Statement

Compute A \times B.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the value A \times B as an integer.

Sample Input 1

2 5

Sample Output 1

10

We have 2 \times 5 = 10.

Sample Input 2

100 100

Sample Output 2

10000


let comp x y =
    if x > y then 1 else if x < y then -1 else 0

let () = Scanf.scanf "%d\n" @@ fun n ->
    let as_ = Array.make n 0 in
    let bs_ = Array.make n 0 in
    let substitute i =
        Scanf.scanf "%d %d\n" @@ fun a b ->
            Array.set as_ i a;
            Array.set bs_ i b;
    in
    ignore @@ Array.map substitute @@ (Array.init n @@ fun i -> i);
    ignore @@ Array.sort comp as_;
    ignore @@ Array.sort comp bs_;
    let res =
        if n mod 2 == 0
        then
            (Array.get bs_ @@ n / 2) + (Array.get bs_ @@ n / 2 - 1)
            - (Array.get as_ @@ n / 2) - (Array.get as_ @@ n / 2 - 1) + 1
        else
            (Array.get bs_ @@ n / 2) - (Array.get as_ @@ n / 2) + 1
    in
    ignore @@ Printf.printf "%d\n" @@ res

Score : 500 points

Problem Statement

There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i.
Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.

Notes

The median of X_1, X_2, \cdots, X_N is defined as follows. Let x_1, x_2, \cdots, x_N be the result of sorting X_1, X_2, \cdots, X_N in ascending order.

If N is odd, the median is x_{(N+1)/2};

if N is even, the median is (x_{N/2} + x_{N/2+1}) / 2.

Constraints

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

1 \leq A_i \leq B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the answer.

Sample Input 1

2
1 2
2 3

Sample Output 1

3

If X_1 = 1 and X_2 = 2, the median is \frac{3}{2};

if X_1 = 1 and X_2 = 3, the median is 2;

if X_1 = 2 and X_2 = 2, the median is 2;

if X_1 = 2 and X_2 = 3, the median is \frac{5}{2}.

Thus, the median can take three values: \frac{3}{2}, 2, and \frac{5}{2}.

Sample Input 2

3
100 100
10 10000
1 1000000000

Sample Output 2

9991


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

    let m = 998244353 in
    let ( +@) a b = (a + b) mod m in
    let ( *@) a b = (a * b) mod m in

    let module M = Map.Make (struct type t = int let compare = compare end) in
    let dp = Array.make (n + 1) M.empty in
    let () = dp.(0) <- M.add 0 1 M.empty in

    for i = 0 to n - 1 do
        let c = a.(i) in
        for j = i downto 0 do
            dp.(j + 1) <-
                M.fold (fun k v acc ->
                    if c + k > s then acc else
                    M.add (c + k) (v +@ try M.find (c + k) acc with _ -> 0) acc) dp.(j) dp.(j + 1)
        done
    done;
    let powmod a b =
        let rec loop r i acc =
            if i = 0 then acc else
                loop (r *@ r) (i lsr 1) (if i land 1 = 1 then acc *@ r else acc)
        in
        loop a b 1
    in
    let rec loop k acc =
        if k > n then acc else
            let acc =
                if M.mem s dp.(k) then acc +@ M.find s dp.(k) *@ powmod 2 (n - k) else acc
            in
            loop (k + 1) acc
    in
    loop 1 0 |> Printf.printf "%d\n"
)

Score : 600 points

Problem Statement

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

For a non-empty subset T of the set \{1, 2, \ldots , N \}, let us define f(T) as follows:

f(T) is the number of different non-empty subsets \{x_1, x_2, \ldots , x_k \} of T such that A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(T) over all 2^N-1 subsets T of \{1, 2, \ldots , N \}. Since the sum can be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq S \leq 3000

1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(T) modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

6

For each T, the value of f(T) is shown below. The sum of these values is 6.

f(\{1\}) = 0

f(\{2\}) = 0

f(\{3\}) = 1 (One subset \{3\} satisfies the condition.)

f(\{1, 2\}) = 1 (\{1, 2\})

f(\{2, 3\}) = 1 (\{3\})

f(\{1, 3\}) = 1 (\{3\})

f(\{1, 2, 3\}) = 2 (\{1, 2\}, \{3\})

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

3296


open Batteries
open Printf

let ($) g f x = g (f x)

module MyList = struct
  include List
  let foldl = fold_left
  let foldli = fold_lefti
  let foldr = fold_right
  let foldri = fold_righti

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i
end

module L = MyList

let swap = Tuple2.swap

let atoi = int_of_string
let itoa = string_of_int
let atof = float_of_string
let ftoa = string_of_float
let ctoi = int_of_char
let itoc = char_of_int

let stocl = String.to_list
let cltos = String.of_list
let spsp s = String.split_on_char ' ' s

module MyString = struct
  include String

  let map' f s = L.map f (stocl s)
  let mapi' f s = L.map f (stocl s)

  let zipf f a b = L.zipf f (stocl a) (stocl b)
  let zipfi f a b = L.zipfi f (stocl a) (stocl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)
end

module S = MyString

module MySet = struct
  include Set

  let fold' f s z = fold f z s
end

module St = MySet

module MyMap = struct
  include Map

  let apply = find
  let apply_or = find_default
end

module Mp = MyMap

let rds () = read_line ()

let rdi () = atoi @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map atoi

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rdf =
  let rec rdv' n =
    if n <= 0 then []
    else (
      let s = rdf () in
      s::(rdv' (n - 1))
    )
  in rdv' n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let puts s = print_endline s
let putyn b = puts (if b then "Yes" else "No")
let puti i = puts @@ itoa i

let set_power ls =
  let rec set_power' ls pls =
    match ls with
    | [] -> pls
    | hd::tl -> set_power' tl (L.flatmap (fun p -> [p; hd::p]) pls)
  in set_power' ls [[]]

let rdhf () = rdhs () |> L.map atof
let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

module Graph = struct

  type 'a t = { nb : (int, int St.t) Mp.t; vdt : (int, 'a) Mp.t }

  let nothing = { nb = Mp.empty; vdt = Mp.empty }

  let add_edge (e : int * int) g =
    let (v1, v2) = e in
    let nbvs = g.nb |> Mp.apply_or St.empty v1 in
    let nb1 = g.nb |> Mp.add v1 (nbvs |> St.add v2) in
    { g with nb = nb1 }

  let add_uedge e g =
    add_edge e (add_edge (swap e) g)

  let from_edges es =
    es |> L.foldl (fun g e -> add_edge e g) nothing

  let from_uedges es =
    es |> L.foldl (fun g e -> add_uedge e g) nothing

end

module G = Graph

let _ =
  let (h1, m1, h2, m2, k) = rdi5 () in
  let dif = (h2 * 60 + m2) - (h1 * 60 + m1) in
  puti @@ max 0 (dif - k)
;;

Score : 100 points

Problem Statement

In this problem, we use the 24-hour clock.

Takahashi gets up exactly at the time H_1 : M_1 and goes to bed exactly at the time H_2 : M_2. (See Sample Inputs below for clarity.)
He has decided to study for K consecutive minutes while he is up.
What is the length of the period in which he can start studying?

Constraints

0 \le H_1, H_2 \le 23

0 \le M_1, M_2 \le 59

The time H_1 : M_1 comes before the time H_2 : M_2.

K \ge 1

Takahashi is up for at least K minutes.

All values in input are integers (without leading zeros).

Input

Input is given from Standard Input in the following format:

H_1 M_1 H_2 M_2 K

Output

Print the length of the period in which he can start studying, as an integer.

Sample Input 1

10 0 15 0 30

Sample Output 1

270

Takahashi gets up at exactly ten in the morning and goes to bed at exactly three in the afternoon.
It takes 30 minutes to do the study, so he can start it in the period between ten o'clock and half-past two. The length of this period is 270 minutes, so we should print 270.

Sample Input 2

10 0 12 0 120

Sample Output 2

0

Takahashi gets up at exactly ten in the morning and goes to bed at exactly noon. It takes 120 minutes to do the study, so he has to start it at exactly ten o'clock. Thus, we should print 0.


let () =
  let str = Bytes.of_string @@ read_line () in
  for i = (Bytes.length str) - 1 downto 0 do
    if Bytes.get str i = '?' then Bytes.set str i 'D'
  done;
  print_endline (Bytes.to_string str)

Score : 200 points

Problem Statement

For a string S consisting of the uppercase English letters P and D, let the doctoral and postdoctoral quotient of S be the total number of occurrences of D and PD in S as contiguous substrings. For example, if S = PPDDP, it contains two occurrences of D and one occurrence of PD as contiguous substrings, so the doctoral and postdoctoral quotient of S is 3.

We have a string T consisting of P, D, and ?.

Among the strings that can be obtained by replacing each ? in T with P or D, find one with the maximum possible doctoral and postdoctoral quotient.

Constraints

1 \leq |T| \leq 2 \times 10^5

T consists of P, D, and ?.

Input

Input is given from Standard Input in the following format:

T

Output

Print one string with the maximum possible doctoral and postdoctoral quotient among the strings that can be obtained by replacing each ? in T with P or D.
If there are multiple such strings, you may print any of them.

Sample Input 1

PD?D??P

Sample Output 1

PDPDPDP

This string contains three occurrences of D and three occurrences of PD as contiguous substrings, so its doctoral and postdoctoral quotient is 6, which is the maximum doctoral and postdoctoral quotient of a string obtained by replacing each ? in T with P or D.

Sample Input 2

P?P?

Sample Output 2

PDPD


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init (n + 1) @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let maximum = Array.make (n + 1) 0 in
  maximum.(0) <- max 0 (1 - as_.(0));
  for i = 0 to n - 1 do
    maximum.(i + 1) <- max 0 @@ 2 * maximum.(i) - as_.(i + 1)
  done;
  try
    let nodes = ref 0 in
    let leafs = ref as_.(n) in
    for i = n - 1 downto 0 do
      let leafs' = min !leafs maximum.(i) in
      if !leafs < leafs' || 2 * leafs' < !leafs then raise Not_found;
      nodes := !nodes + leafs';
      leafs := leafs'
    done;
    Printf.printf "%d\n" @@ !nodes + Array.fold_left ( + ) 0 as_
  with Not_found -> print_endline "-1"

Score : 600 points

Problem Statement

Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex v in a binary tree is the distance from the tree's root to v. (The root has the depth of 0.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

0 \leq N \leq 10^5

0 \leq A_i \leq 10^{8} (0 \leq i \leq N)

A_N \geq 1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_0 A_1 A_2 \cdots A_N

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264


open Num;;

Scanf.scanf "%d" (fun t ->
    let module M = Map.Make (struct type t = int let compare = compare end) in
    for i = 1 to t do
        Scanf.scanf " %d %d %d %d %d" (fun n a b c d ->
            let rec calc =
                let map = ref (M.add 0 (Int 0) (M.singleton 1 (Int d))) in
                fun k ->
                if M.mem k !map then M.find k !map else (
                    let ans = Int k */ Int d in
                    let ans = List.fold_left (fun acc i ->
                        if (k + i) mod 2 <> 0 then acc else
                            min_num acc (calc ((k + i) / 2) +/ Int a +/ Int d */ Int (abs i))
                            ) ans [ -1; 0; 1 ]
                    in
                    let ans = List.fold_left (fun acc i ->
                        if (k + i) mod 3 <> 0 then acc else
                            min_num acc (calc ((k + i) / 3) +/ Int b +/ Int d */ Int (abs i))
                            ) ans [ -1; 0; 1 ]
                    in
                    let ans = List.fold_left (fun acc i ->
                        if (k + i) mod 5 <> 0 then acc else
                            min_num acc (calc ((k + i) / 5) +/ Int c +/ Int d */ Int ( abs i))
                            ) ans [ -2; -1; 0; 1; 2 ]
                    in
                    map := M.add k ans !map;
                    ans
                  )
            in
            Printf.printf "%s\n" @@ string_of_num (calc n)
        )
    done
)

Score : 400 points

Problem Statement

You start with the number 0 and you want to reach the number N.

You can change the number, paying a certain amount of coins, with the following operations:

Multiply the number by 2, paying A coins.

Multiply the number by 3, paying B coins.

Multiply the number by 5, paying C coins.

Increase or decrease the number by 1, paying D coins.

You can perform these operations in arbitrary order and an arbitrary number of times.

What is the minimum number of coins you need to reach N?

You have to solve T testcases.

Constraints

1 \le T \le 10

1 \le N \le 10^{18}

1 \le A, B, C, D \le 10^9

All numbers N, A, B, C, D are integers.

Input

The input is given from Standard Input. The first line of the input is

T

Then, T lines follow describing the T testcases.
Each of the T lines has the format

N A B C D

Output

For each testcase, print the answer on Standard Output followed by a newline.

Sample Input 1

5
11 1 2 4 8
11 1 2 2 8
32 10 8 5 4
29384293847243 454353412 332423423 934923490 1
900000000000000000 332423423 454353412 934923490 987654321

Sample Output 1

20
19
26
3821859835
23441258666

For the first testcase, a sequence of moves that achieves the minimum cost of 20 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 1 to multiply by 2 (x = 4).

Pay 2 to multiply by 3 (x = 12).

Pay 8 to decrease by 1 (x = 11).

For the second testcase, a sequence of moves that achieves the minimum cost of 19 is:

Initially x = 0.

Pay 8 to increase by 1 (x = 1).

Pay 1 to multiply by 2 (x = 2).

Pay 2 to multiply by 5 (x = 10).

Pay 8 to increase by 1 (x = 11).


Scanf.scanf "%d" (fun t ->
    let module M = Map.Make (struct type t = int let compare = compare end) in
    for i = 1 to t do
        Scanf.scanf " %d %d %d %d %d" (fun n a b c d ->
            let rec calc =
                let map = ref (M.add 0 0 (M.singleton 1 d)) in
                fun k ->
                if M.mem k !map then M.find k !map else (
                    let ans = if k < max_int / d then k * d else max_int in
                    let ans = List.fold_left (fun acc i ->
                        if (k + i) mod 2 <> 0 then acc else
                            min acc (calc ((k + i) / 2) + a + d * abs i)
                            ) ans [ -1; 0 ]
                    in
                    let ans = List.fold_left (fun acc i ->
                        if (k + i) mod 3 <> 0 then acc else
                            min acc (calc ((k + i) / 3) + b + d * abs i)
                            ) ans [ -1; 0; 1 ]
                    in
                    let ans = List.fold_left (fun acc i ->
                        if (k + i) mod 5 <> 0 then acc else
                            min acc (calc ((k + i) / 5) + c + d * abs i)
                            ) ans [ -2; -1; 0; 1; 2 ]
                    in
                    map := M.add k ans !map;
                    ans
                  )
            in
            Printf.printf "%d\n" @@ calc n
        )
    done
)


let therefore n =
  let n_mod_10 = n mod 10 in
  if n_mod_10 = 2 then "hon"
  else if n_mod_10 = 4 then "hon"
  else if n_mod_10 = 5 then "hon"
  else if n_mod_10 = 7 then "hon"
  else if n_mod_10 = 9 then "hon"
  else if n_mod_10 = 0 then "pon"
  else if n_mod_10 = 1 then "pon"
  else if n_mod_10 = 6 then "pon"
  else if n_mod_10 = 8 then "pon"
  else "bon"

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

Score: 100 points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a positive integer N not exceeding 999 is as follows:

hon when the digit in the one's place of N is 2, 4, 5, 7, or 9;

pon when the digit in the one's place of N is 0, 1, 6 or 8;

bon when the digit in the one's place of N is 3.

Given N, print the pronunciation of "本" in the phrase "N 本".

Constraints

N is a positive integer not exceeding 999.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of 16 is 6, so the "本" in "16 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon


open Scanf
open Printf

let triple_dots k s =
  if String.length s <= k then s
  else String.sub s 0 k ^ "..."

let k,s = scanf "%d %s" (fun k  s -> (k,s))
let () = printf "%s\n" (triple_dots k s)

Score: 200 points

Problem Statement

We have a string S consisting of lowercase English letters.

If the length of S is at most K, print S without change.

If the length of S exceeds K, extract the first K characters in S, append ... to the end of them, and print the result.

Constraints

K is an integer between 1 and 100 (inclusive).

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:

K
S

Output

Print a string as stated in Problem Statement.

Sample Input 1

7
nikoandsolstice

Sample Output 1

nikoand...

nikoandsolstice has a length of 15, which exceeds K=7.

We should extract the first 7 characters in this string, append ... to the end of them, and print the result nikoand....

Sample Input 2

40
ferelibenterhominesidquodvoluntcredunt

Sample Output 2

ferelibenterhominesidquodvoluntcredunt

The famous quote from Gaius Julius Caesar.


let k = Scanf.sscanf (read_line ()) "%d" @@ fun k -> k
let s = read_line ()

let () = print_endline @@
  if (String.length s > k) then (String.sub s 0 k) ^ "..."
  else s


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 (a,b,h,m) = scan "%f %f %f %f" Tuple4.make

let () =
  let theta = Float.abs 2.0*.Float.pi *. ((h +. m /. 60.0) /. 12.0  -. m /. 60.0) in
  Printf.printf "%.10f\n" @@ Float.sqrt @@ a*.a +. b*.b -. 2.0*.a*.b*.cos theta

Score: 300 points

Problem Statement

Consider an analog clock whose hour and minute hands are A and B centimeters long, respectively.

An endpoint of the hour hand and an endpoint of the minute hand are fixed at the same point, around which each hand rotates clockwise at constant angular velocity. It takes the hour and minute hands 12 hours and 1 hour to make one full rotation, respectively.

At 0 o'clock, the two hands overlap each other. H hours and M minutes later, what is the distance in centimeters between the unfixed endpoints of the hands?

Constraints

All values in input are integers.

1 \leq A, B \leq 1000

0 \leq H \leq 11

0 \leq M \leq 59

Input

Input is given from Standard Input in the following format:

A B H M

Output

Print the answer without units. Your output will be accepted when its absolute or relative error from the correct value is at most 10^{-9}.

Sample Input 1

3 4 9 0

Sample Output 1

5.00000000000000000000

The two hands will be in the positions shown in the figure below, so the answer is 5 centimeters.

Sample Input 2

3 4 10 40

Sample Output 2

4.56425719433005567605

The two hands will be in the positions shown in the figure below. Note that each hand always rotates at constant angular velocity.


let pi = atan(1.) *. 4.
let () =
  Scanf.scanf "%f %f %f %f\n" @@ fun a b h m ->
  let d = let d' = abs_float (h *. 30. -. m *. 5.5) in
    if d' <= 180. then d' else 360. -. d' in
  let ans = sqrt (a**2. +. b**2. -. 2.*.a*.b*.cos(d *. pi /. 180.)) in
  Printf.printf "%.10f\n" ans


open Batteries
let a,b,h,m = Scanf.sscanf (read_line()) "%d %d %d %d" (fun a b h m -> a,b,h,m)
let get_hour_kakudo hour = (15 * (hour+3))
let get_minute_kakudo minutes = (6 * (minutes+15))
let pi = 4.0 *. atan 1.0
let f_a = float_of_int a
let f_b = float_of_int b
let _ = (
  if get_hour_kakudo h = get_minute_kakudo m then (float_of_int @@ abs (a-b)) else (
    let hour_x = f_a *. (cos @@ (((float_of_int @@ get_hour_kakudo h) /. 180.) *. pi))  in
    let hour_y = f_a *. (sin @@ (((float_of_int @@ get_hour_kakudo h) /. 180.) *. pi)) in
    let min_x = f_b *. (cos @@ (((float_of_int @@ get_minute_kakudo m) /. 180.) *. pi)) in
    let min_y = f_b *. (sin @@ (((float_of_int @@ get_minute_kakudo m) /. 180.) *. pi)) in
    (* Printf.printf "%.1f %.8f %.8f %.8f hour %d minutes %d\n" hour_x hour_y min_x min_y (get_hour_kakudo h) (get_minute_kakudo m); *)
    (((min_x -. hour_x) ** 2.) +. ((min_y -. hour_y) ** 2.)) |> sqrt
  )
) |> Printf.printf "%f\n"