let () = Scanf.scanf "%d\n" @@ fun n ->
  let cs = Array.init n @@ fun _ -> Scanf.scanf "%c" Fun.id in
  let reds = Array.make (n + 1) 0 in (* th以上の赤 *)
  let whites = Array.make (n + 1) 0 in (* th未満の白 *)
  for i = 0 to n - 1 do
    match cs.(i) with
    | 'R' -> reds.(i) <- reds.(i) + 1
    | 'W' -> whites.(i + 1) <- whites.(i + 1) + 1
  done;
  for i = n - 1 downto 0 do
    reds.(i) <- reds.(i) + reds.(i + 1)
  done;
  for i = 0 to n - 1 do
    whites.(i + 1) <- whites.(i) + whites.(i + 1)
  done;
  Printf.printf "%d\n" @@
  Array.fold_left min max_int @@
  Array.init (n + 1) @@ fun i -> max reds.(i) whites.(i)

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 n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k)
let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i))

let rec f l r =
  if r <= l then r
  else
    let m = (l + r) / 2 in
    let k' = Array.fold_left (fun i j -> i + (j - 1) / m) 0 a in
    if k < k' then f (m + 1) r
    else f l m

let () = Printf.printf "%d\n" (f 1 1000000000)

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

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

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.


(* 0-indexedなBIT *)
module FenwickTree = struct
  (* 可換モノイド *)
  module type CommutativeMonoid = sig
    type t
    val e : t
    val op : t -> t -> t
  end

  module Make (CM : CommutativeMonoid)
  : sig
    type t
    (* n要素の単位元からなるBITを作る *)
    val make : int -> t
    (* 添字iの要素にはf iが入ったn要素のBITを作る *)
    val init : int -> (int -> CM.t) -> t
    (* 与えられたリストの要素が入ったBITを作る *)
    val of_list : CM.t list -> t
    (* i番目の要素にxを加える *)
    val accumulate : t -> int -> CM.t -> unit

    (* 添字が[0, i)の範囲の要素を全て加えた値を求める *)
    val query : t -> int -> CM.t
  end
  = struct
    type t = CM.t array

    let make n = Array.make n CM.e

    let initialize a =
      for i = 0 to Array.length a - 1 do
        if i lor (i + 1) < Array.length a then
          a.(i lor (i + 1)) <- CM.op a.(i) a.(i lor (i + 1))
      done

    let init n f =
      let a = Array.init n f in
      initialize a; a

    let of_list l =
      let a = Array.of_list l in
      initialize a; a

    let rec accumulate a i x =
      if i < Array.length a then begin
        a.(i) <- CM.op x a.(i);
        accumulate a (i lor (i + 1)) x
      end

    let rec query acc a i =
      if i < 0
      then acc
      else query (CM.op acc a.(i)) a ((i land (i + 1)) - 1)
    let query a i = query CM.e a (i - 1)
  end
end

module SumBIT = FenwickTree.Make (struct
  type t = int
  let e = 0
  let op = ( + )
end)

let () = Scanf.scanf "%d %d\n" @@ fun n q ->
  let cs = Array.init n @@ fun _ -> Scanf.scanf "%d " pred in
  let lrs = Array.init q @@ fun i -> Scanf.scanf "%d %d\n" @@ fun l r -> i, l - 1, r - 1 in
  Array.sort (fun (_, _, r) (_, _, r') -> compare r r') lrs;
  let r = ref 0 in
  let ans = Array.make q 0 in
  let bit = SumBIT.make (n + 2) in
  let prev = Array.make n (n + 1) in
  Array.iter (fun (i, l, right) ->
    while !r <= right do
      SumBIT.accumulate bit !r 1;
      SumBIT.accumulate bit prev.(cs.(!r)) (-1);
      prev.(cs.(!r)) <- !r;
      incr r
    done;
    ans.(i) <- SumBIT.query bit (!r + 1) - SumBIT.query bit l) lrs;
  Array.iter (Printf.printf "%d\n") ans

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


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 x = rdi () in
  let q = 8 - ((x - 400) / 200) in
  puti q;
  ()

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.


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let arr = Array.init n @@ fun i -> Scanf.scanf "%d " @@ fun d -> (i+1, d) in
  Printf.printf "%d\n"
    (Array.fold_left (fun s (i,d) -> if i mod 2 = 1 && d mod 2 = 1 then s + 1 else s) 0 arr)

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 () = Scanf.scanf "%d\n" @@ fun n ->
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.init n @@ fun i -> Scanf.scanf "%d " @@ fun a ->
    if i mod 2 = 0 && a mod 2 = 1 then 1 else 0


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 []

module ModOp = struct
  let prime = 1_000_000_007
  let (-) a b = (a + prime - b) mod prime
  let (+) a b = (a + b) mod prime
  let ( * ) a b = (a * b) mod prime

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

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 itoa n = Char.chr (n + Char.code '0')

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

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

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

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

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

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

let n = scan "%d" id
let a = scan_list ~sep:' ' Int.of_string

let () =
  0::(ListL.mapi a ~f:(fun i v ->
      if i mod 2 = 0 && v mod 2 = 1 then 1 else 0
    ))
  |> List.sum
  |> Printf.printf "%d\n"


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

let arr = Array.make 10001 0

let () =
  for i = 1 to 50 do
    for j = 1 to 50 do
      for k = 1 to 50 do
        let t = i * i + j * j + k * k + i * j + j * k + k * i in
        if t <= 10000 then arr.(t - 1) <- arr.(t - 1) + 1;
      done
    done
  done;
  for i = 1 to n do
    Printf.printf "%d\n" arr.(i - 1)
  done

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.


Scanf.scanf "%d %s" (fun n x ->
    let rec loop i acc =
        if i = n then acc else
            if x.[i] = '1' then loop (i + 1) (acc + 1)
                           else loop (i + 1) acc
    in
    let bits = loop 0 0 in
    let calc i =
        let initialmod =
            if bits = 1 && x.[i] = '1' then 0 else
            if bits = 0 && x.[i] = '0' then 0 else
                let bits = if x.[i] = '1' then bits - 1 else bits + 1 in
                let rec loop pos rest =
                    if pos = n then rest else
                        let rest = rest * 2 + (if x.[pos] = '1' then 1 else 0) in
                        let rest = if i = pos then rest lxor 1 else rest in
                        let rest = rest mod bits in
                        loop (pos + 1) rest
                in
                loop 0 0
        in
        let popcount a =
            let rec loop rest acc =
                if rest = 0 then acc else loop (rest lsr 1) (acc + (rest land 1))
            in
            loop a 0
        in
        let rec phase2 md count =
            if md = 0 then count else
                let md = md mod (popcount md) in
                phase2 md (count + 1)
        in
        phase2 initialmod 1
    in
    for i = 0 to n - 1 do
        Printf.printf "%d\n" @@ calc i
    done
)

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


(* unihernandez22
 * https://atcoder.jp/contests/abc173/tasks/abc173_b
 * implementation
 * *)

include Printf;;

Scanf.scanf "%d\n" @@ fun n ->
    let s = Array.init n @@ fun _ -> Scanf.scanf "%s\n" @@ fun x -> x in
    let c = Array.init 4 @@ fun _ -> ref 0 in
    for i = 0 to n-1 do
        if s.(i) = "AC" then c.(0) := !(c.(0)) + 1
        else if s.(i) = "WA" then c.(1) := !(c.(1)) + 1
        else if s.(i) = "TLE" then c.(2) := !(c.(2)) + 1
        else c.(3) := !(c.(3)) + 1
    done;
    printf "AC x %d\n"  !(c.(0));
    printf "WA x %d\n"  !(c.(1));
    printf "TLE x %d\n" !(c.(2));
    printf "RE x %d\n"  !(c.(3));

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 a = Array.make 4 0 in
  for i = 0 to n - 1 do
    let i = Scanf.scanf "%s\n" @@ function
      | "AC" -> 0
      | "WA" -> 1
      | "TLE" -> 2
      | "RE" -> 3 in
    a.(i) <- 1 + a.(i)
  done;
  Printf.printf "AC x %d\nWA x %d\nTLE x %d\nRE x %d\n" a.(0) a.(1) a.(2) a.(3)


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

    let sum = if n = 2 then a.(n - 1) else
                    Array.fold_left (+) 0 a - a.(0) - a.(1) + a.(n - 2)
    in

    Printf.printf "%d\n" sum
)

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" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    Array.sort compare a;

    Printf.printf "%d\n" @@ Array.fold_left (+) 0 a - a.(0)
)


let () =
  Scanf.scanf "%d\n" @@ fun a ->
  Printf.printf "%d\n" (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 a -> Printf.printf "%d\n" @@ a + a * a + a * a * a


let a = read_int()
let _ = (a + a * a + a*a*a)|> print_int


Printf.printf "%d\n" @@
Scanf.scanf "%d %d\n" @@ fun n k ->
    let a = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun i -> i in
    Array.sort (-) a;
    let ans = ref 0 in
    for i = 0 to k-1 do
        ans := !ans + a.(i)
    done;
    !ans;;

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


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let ps = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun p -> p in
  Array.sort compare ps;
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.sub ps 0 k


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let arr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  Scanf.scanf "%d\n" @@ fun q ->
  let brr = Array.init q @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun b c -> (b, c) in
  for i = 0 to q - 1 do
    let (b, c) = brr.(i) in
    let _ = Array.mapi (fun i a -> if a = b then arr.(i) <- c else arr.(i) <- a) arr in
    Printf.printf "%d\n" (Array.fold_left (+) 0 arr)
  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
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 []

module ModOp = struct
  let prime = 1_000_000_007
  let (-) a b = (a + prime - b) mod prime
  let (+) a b = (a + b) mod prime
  let ( * ) a b = (a * b) mod prime

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

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 itoa n = Char.chr (n + Char.code '0')

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

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

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

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

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

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

let n = scan "%d" id
let a = scan_list ~sep:' ' Int.of_string
let q = scan "%d" id
let bc = scan_lines q "%d %d" Tuple2.make

let () =
  let h = Hashtbl.create n in
  ListL.iter a ~f:(fun a ->
      Hashtbl.modify_def 0 a succ h);
  let total = a |> List.sum in
  ListL.fold_left bc ~init:total ~f:(fun total (b,c) ->
      let n = Hashtbl.find_default h b 0 in
      let total = total - b*n + c*n in
      Printf.printf "%d\n" total;
      Hashtbl.remove_all h b;
      Hashtbl.modify_def 0 c ((+) n) h; total
    ) |> ignore


open Batteries
let n = read_int ()
let a = read_line () |> String.split_on_char ' ' |> List.map int_of_string
let all = List.fold_left (fun a b -> a lxor b) 0 a
let rec loop lst =
  match lst with
  | [] -> print_string "\n"
  | first :: rest ->
    Printf.printf "%d " (all lxor first); loop rest
let _ = loop a

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.


Scanf.scanf "%d %s" (fun k s ->
    let n = String.length s in
    let z = 1_000_000_007 in
    let extgcd x y =
        let rec eg r0 r1 a0 a1 b0 b1 =
            if r1 = 0 then a0 else
                let q1 = r0 / r1 in
                eg r1 (r0 mod r1) a1 (a0 - q1 * a1) b1 (b0 - q1 * b1)
        in
        eg x y 1 0 0 1
    in
    let inv x y = (* 1/x in mod y *)
        let c = extgcd x y in
        if c < 0 then c + y else c
    in
    let ( +@) a b = (a + b) mod z in
    let ( *@) a b = (a * b) mod z in
    let ( /@) a b = a *@ inv b z in
    let rec loop i pre acc =
        if i > k then acc else loop (i + 1) (pre *@ (25 * (n + i)) /@ (1 + i)) (acc *@ 26 +@ pre)
    in
    loop 0 1 0 |> Printf.printf "%d\n"
)

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


(* Vicfred
 * https://atcoder.jp/contests/abc170/tasks/abc170_a
 * implementation
 * *)
open Printf
open Scanf

let main =
    let xs = Array.init 5 @@ fun _ -> scanf"%d " @@ fun x -> x in
    for i = 0 to 4 do
        if xs.(i) = 0 then
            printf "%d\n" @@ i + 1
    done

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


(* Vicfred
 * https://atcoder.jp/contests/abc170/tasks/abc170_a
 * implementation
 * *)
open Printf
open Scanf

let solve a b c d e = 15 - a - b - c - d - e

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


let read_ints () =
  let str = read_line() in
  List.map (fun x -> int_of_string x) (Str.split (Str.regexp " +") str)
;;

let rec sum lst =
  match lst with
  |[] -> 0
  |h :: t -> h + sum t
;;

let x = read_ints() in
print_endline (string_of_int (15 - sum x))


module Weighted01DirectedGraph
  (* 道の表現 *)
  (Path : sig
    type t
    (* 辺の名前 *)
    type edge
    (* 長さ0の道 *)
    val nil : t
    (* 道の後ろに辺を付け足した道 *)
    val snoc : t -> edge -> t
  end) :
sig
  val bfs01 :
    (* 頂点数 *)
    int ->
    (* 辺の名前が付いた隣接リスト *)
    (* 辺の重さが0ならfalse，1ならtrue *)
    ('v -> ('v * Path.edge * bool) list) ->
    (* 始点 *)
    'v ->
    (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
    ('v -> Path.t option)
end =
struct
  let bfs01 n es s =
    (* 始点sからの経路 *)
    let d = Hashtbl.create n in
    (* 現在BFSで走査している頂点のリスト *)
    let vps = ref [(s, Path.nil)] in
    let rec bfs t =
      match Hashtbl.find_opt d t, !vps with
      (* もう既に全ての頂点までの経路が分かっている *)
      | None, [] -> None
      (* 既に終点までの経路が分かっているので返す *)
      | Some _ as ans, _ -> ans
      (* 終点までの経路が分かっていないので，01BFSを続行 *)
      | None, _ :: _ -> vps := List.fold_left dfs [] !vps; bfs t
    (* 重さ0の辺をDFSで縮約 *)
    and dfs vps (v, p) =
      if Hashtbl.mem d v then vps
      else begin
        Hashtbl.add d v p;
        List.fold_left (fun vps (u, e, b) ->
          if b
          then (u, Path.snoc p e) :: vps
          else dfs vps (u, Path.snoc p e)) vps (es v)
      end
    in bfs
end

module G = Weighted01DirectedGraph
(struct
  type t = int
  type edge = int
  let nil = 0
  let snoc = ( + )
end)

type dir = Neutral | Left | Right | Up | Down

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 = G.bfs01 (h * w * 40) (fun (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 = Neutral || dir = dir') && s < k
      then Some ((i, j, s + 1, dir'), 0, false)
      else Some ((i, j, 1, dir'), 1, true))
    [(i - 1, j, Up); (i + 1, j, Down); (i, j - 1, Left); (i, j + 1, Right)])
    (x1, y1, 0, Neutral) in
  Printf.printf "%d\n" @@
  max (-1) @@
  succ @@
  Array.fold_left (List.fold_left min) max_int @@
  Array.init k @@ fun s ->
    let s = s + 1 in
    List.map (fun o -> Option.value ~default:max_int o)
    [ d (x2, y2, s, Left); d (x2, y2, s, Right); d (x2, y2, s, Up); d (x2, y2, s, Down) ]


let () =
  let rec tsurukame x y z =
    if x * 4 + y * 2 = z then "Yes"
    else if x < 0 then "No"
    else tsurukame (x-1) (y+1) z in
  Scanf.scanf "%d %d\n" @@ fun x y ->
  Printf.printf "%s" (tsurukame x 0 y)

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.


module WeightedDirectedGraph
  (* 辺の重み *)
  (Weight : sig
    type t
    val zero : t
    val compare : t -> t -> int
  end)
  (* 経路長を優先度としたヒープの実装 *)
  (Heap : sig
    type t
    type elt (* 頂点に相当 *)
    type key = Weight.t (* 経路長に相当 *)
    (* ヒープが空ならNoneを，
       そうでなければ経路長が最小となるbindingを一つ以上返す
       返したbindingは全てヒープから削除される *)
    val take_min_bindings : t -> (key * elt list) option
    (* ヒープにbindingを追加する
       既に同じ頂点についてのbindingが追加されていたら，
       経路長の短い方だけを残しても良いし，何も考えずに追加してもよい．
       前者の実装ならダイクストラ法の実装が時間計算量O((V + E) log V)，
       空間計算量O(V)に改善する *)
    val add : t -> key -> elt -> unit
  end)
  (* 頂点を添字，経路長を要素とした配列の実装 *)
  (Array : sig
    type t
    type key = Heap.elt
    type elt = Heap.key
    val get : t -> key -> elt
    val set : t -> key -> elt -> unit
  end)
: sig
  type weight = Array.elt
  type vertex = Array.key

  (* ダイクストラ法で最短経路を求める関数 *)
  val shortest_path :
    (* 空なヒープ *)
    Heap.t ->
    (* 全ての頂点についての経路長が無限大で初期化された配列
       Array.getした時に極端に大きな経路長が返ってくる実装でも良いし，
       Not_foundが投げられる実装でも良い *)
    Array.t ->
    (* 最短経路を求めたいグラフの，ある頂点から伸びる辺に対してのイテレータ *)
    (vertex -> (vertex -> (weight -> weight) (* 辺を通った際のコストを加算する関数 *) -> unit) -> unit) ->
    (* 始点 *)
    vertex ->
    (* 終点を受け取って，始点からの最短距離を返す関数
       始点から辿り着けない場合，無限大を返すかNot_foundを投げる（Arrayの実装依存）
       この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
    (vertex -> weight)
end
= struct
  type weight = Array.elt
  type vertex = Array.key

  let shortest_path q d es s =
    (* 始点への経路長を0にする *)
    Array.set d s Weight.zero;
    (* 既に最短距離が確定した辺へのクエリを高速化するため，
       ヒープの最小要素をメモしておく *)
    let min_bindings = ref (Some (Weight.zero, [s])) in
    let rec dijkstra t =
      match !min_bindings with
      (* もう既に全ての頂点までの距離が分かっている *)
      | None -> Array.get d t
      | Some (w, us) ->
          match Array.get d t with
          (* 既に終点までの距離が分かっているので返す *)
          | x when 0 <= Weight.compare w x -> x
          (* 終点までの距離が分かっていないので，ダイクストラ法を続行 *)
          | _ | exception Not_found ->
              List.iter (fun u ->
                (* 未だ頂点uを訪れていない *)
                if 0 <= Weight.compare (Array.get d u) w then
                  es u @@ fun v f ->
                    (* uからvに伸びる辺を通った際の経路長 *)
                    let c = f w in
                    if 0 < Weight.compare (Array.get d v) c then
                      (Heap.add q c v; Array.set d v c)) us;
              min_bindings := Heap.take_min_bindings q;
              dijkstra t in
    dijkstra
end

module Int = struct
  type t = int
  let zero = 0
  let compare = compare
end

module IntMap = Map.Make (Int)

module G = WeightedDirectedGraph (Int)
  (struct
    type t = int array list IntMap.t ref
    type key = int
    type elt = int array
    let take_min_bindings q =
      match IntMap.min_binding !q with
      | exception Not_found -> None
      | (w, _) as p -> q := IntMap.remove w !q; Some p
    let add q w v  =
      q := IntMap.update w (fun vs -> Some (v :: Option.value ~default:[] vs)) !q
  end)
  (struct
    type t = (int, Bigarray.int_elt, Bigarray.c_layout) Bigarray.Genarray.t
    type elt = int
    type key = int array
    let get = Bigarray.Genarray.get
    let set = Bigarray.Genarray.set
  end)

let () = Scanf.scanf "%d %d %d\n%d %d %d %d\n" @@ fun h w k x1 y1 x2 y2 ->
  let css = Array.init h @@ fun _ -> Scanf.scanf "%s\n" Fun.id in
  let dx = [| 1; 0; -1; 0 |] in
  let dy = [| 0; 1; 0; -1 |] in
  let d = G.shortest_path (ref IntMap.empty)
    (let d = Bigarray.Genarray.create Bigarray.int Bigarray.c_layout [| h; w; 4 |] in Bigarray.Genarray.fill d max_int; d)
    (fun [| i; j; dir |] f ->
      f [| i; j; (dir + 1) mod 4 |] (fun c -> c + k - 1 - (c + k - 1) mod k);
      let i = i + dx.(dir) in
      let j = j + dy.(dir) in
      if 0 <= i && i < h && 0 <= j && j < w && css.(i).[j] <> '@' then
        f [| i; j; dir |] succ)
    [| x1 - 1; y1 - 1; 0 |] in
  Printf.printf "%d\n" @@
  (fun x -> if max_int <= x then -1 else (x + k - 1) / k) @@
  Array.fold_left min max_int @@
  Array.init 4 @@ fun dir -> d [| x2 - 1; y2 - 1; dir |]

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


module Weighted01DirectedGraph
  (* 道の表現 *)
  (Path : sig
    type t
    (* 辺の名前 *)
    type edge
    (* 長さ0の道 *)
    val nil : t
    (* 道の後ろに辺を付け足した道 *)
    val snoc : t -> edge -> t
  end) :
sig
  val bfs01 :
    (* 頂点数 *)
    int ->
    (* 辺の名前が付いた隣接リスト *)
    (* 辺の重さが0ならfalse，1ならtrue *)
    ('v -> ('v * Path.edge * bool) list) ->
    (* 始点 *)
    'v ->
    (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
    ('v -> Path.t option)
end =
struct
  let bfs01 n es s =
    (* 始点sからの経路 *)
    let d = Hashtbl.create n in
    (* 現在BFSで走査している頂点のリスト *)
    let vps = ref [(s, Path.nil)] in
    let rec bfs t =
      match Hashtbl.find_opt d t, !vps with
      (* もう既に全ての頂点までの経路が分かっている *)
      | None, [] -> None
      (* 既に終点までの経路が分かっているので返す *)
      | Some _ as ans, _ -> ans
      (* 終点までの経路が分かっていないので，01BFSを続行 *)
      | None, _ :: _ -> vps := List.fold_left dfs [] !vps; bfs t
    (* 重さ0の辺をDFSで縮約 *)
    and dfs vps (v, p) =
      if Hashtbl.mem d v then vps
      else begin
        Hashtbl.add d v p;
        List.fold_left (fun vps (u, e, b) ->
          if b
          then (u, Path.snoc p e) :: vps
          else dfs vps (u, Path.snoc p e)) vps (es v)
      end
    in bfs
end

module G = Weighted01DirectedGraph
(struct
  type t = int
  type edge = int
  let nil = 0
  let snoc = ( + )
end)

type dir = Neutral | Left | Right | Up | Down

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 = G.bfs01 (h * w * 400) (fun (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 = Neutral || dir = dir') && s < k
      then Some ((i, j, s + 1, dir'), 0, false)
      else Some ((i, j, 1, dir'), 1, true))
    [(i - 1, j, Up); (i + 1, j, Down); (i, j - 1, Left); (i, j + 1, Right)])
    (x1, y1, 0, Neutral) in
  Printf.printf "%d\n" @@
  max (-1) @@
  succ @@
  Array.fold_left (List.fold_left min) max_int @@
  Array.init k @@ fun s ->
    let s = s + 1 in
    List.map (fun o -> Option.value ~default:max_int o)
    [ d (x2, y2, s, Left); d (x2, y2, s, Right); d (x2, y2, s, Up); d (x2, y2, s, Down) ]


let rec range a b = if a >= b then Seq.empty else fun () -> Seq.Cons (a, range (a+1) b)

let n = Scanf.scanf "%d" Fun.id
let vw = List.init n (fun _ -> Scanf.scanf " %d %d" (fun v w -> v, w))
let varr = List.to_seq vw |> Seq.map fst |> Array.of_seq
let warr = List.to_seq vw |> Seq.map snd |> Array.of_seq

let rec items arr x =
  if x = 1 then [arr.(0)]
  else arr.(x-1) :: items arr (x / 2)

let enumerate t lim va wa =
  let ve = Array.make (1 lsl t) 0 in
  let we = Array.make (1 lsl t) 0 in
  range 0 (1 lsl t) |> Seq.iter (fun b ->
    let ws = range 0 t |> Seq.fold_left (fun ws i ->
      if b land (1 lsl i) > 0 then ws + wa.(i) else ws) 0 in
    if ws <= lim then (
      let vs = range 0 t |> Seq.fold_left (fun vs i ->
        if b land (1 lsl i) > 0 then vs + va.(i) else vs) 0 in
      we.(b) <- ws;
      ve.(b) <- vs;
  ));
  (ve, we)

let solve x l =
  let module A = Array in
  let vs = A.of_list @@ items varr x in
  let ws = A.of_list @@ items warr x in
  let t = A.length vs in

  let lvs = A.sub vs 0 (t/2) in
  let rvs = A.sub vs (t/2) (t-t/2) in
  let lws = A.sub ws 0 (t/2) in
  let rws = A.sub ws (t/2) (t-t/2) in

  let ve1, we1 = enumerate (t/2) l lvs lws in
  let ve2, we2 = enumerate (t-t/2) l rvs rws in

  let ans = ref 0 in
  for i = 0 to (1 lsl (t/2)) - 1 do
    let v1 = ve1.(i) in
    let w1 = we1.(i) in
    for j = 0 to (1 lsl (t-t/2)) - 1 do
      let v2 = ve2.(j) in
      let w2 = we2.(j) in
      if w1 + w2 <= l then
        ans := max !ans (v1 + v2);
    done;
  done;
  !ans

let () =
  Scanf.scanf " %d" @@ fun q ->
  for i = 1 to q do
    Scanf.scanf " %d %d" solve
    |> Printf.printf "%d\n"
  done

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


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' = min n ((1 lsl 10) - 1) 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


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 x, y = scan "%d %d" (fun x y -> x, y)

let () =
  Printf.printf "%d\n" (x*y)

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 () = Scanf.scanf "%d %d" (fun a b -> Printf.printf "%d\n" (a*b))


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

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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let abs = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
  let r =
    upper_bound 0 10000000000 @@ fun m ->
      (n + 1) / 2 <=
        Array.fold_left (fun acc (_, b) ->
          acc + if m <= b then 1 else 0) 0 abs in
  let l =
    lower_bound 0 10000000000 (fun m ->
      ( <= ) ((n + 1) / 2) @@
      Array.fold_left (fun acc (a, _) ->
        acc + if a <= m then 1 else 0) 0 abs) in
  Printf.printf "%d\n" @@
  if n mod 2 = 1
  then r - l + 1
  else
    2 * r
    - (if (n + 3) / 2 <=
      Array.fold_left (fun acc (_, b) ->
        acc + if r <= b then 1 else 0) 0 abs then 0 else 1)
    - 2 * l
    - (if (n + 3) / 2 <=
      Array.fold_left (fun acc (a, _) ->
        acc + if a <= l then 1 else 0) 0 abs then 0 else 1)
    + 1

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 rec loop i dp =
        if i = n then dp.(s) else (
            let ndp = Array.map (fun a -> a +@ a) dp in
            let c = a.(i) in
            for j = 0 to s - c do
                ndp.(j + c) <- ndp.(j + c) +@ dp.(j)
            done;
            loop (i + 1) ndp
        )
    in
    let dp = Array.make (s + 1) 0 in
    let () = dp.(0) <- 1 in
    loop 0 dp |> 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


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 (s + 1) M.empty in
    let () = dp.(0) <- M.add 0 1 M.empty in

    for i = 0 to n - 1 do
        for j = s - a.(i) downto 0 do
            dp.(j + a.(i)) <-
                M.fold (fun k v acc ->
                    M.add (k + 1) (v +@ try M.find (k + 1) acc with _ -> 0) acc) dp.(j) dp.(j + a.(i))
        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
    M.fold (fun k v acc -> acc +@ v *@ powmod 2 (n - k)) dp.(s) 0 |> Printf.printf "%d\n"
)


let () = Scanf.scanf "%d %d %d %d %d\n" @@ fun h1 m1 h2 m2 k ->
  Printf.printf "%d\n" @@
  max 0 @@ 60 * (h2 - h1) + (m2 - m1) - 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.


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 soc = split_on_char

  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 t = rds () in
  let result = S.replace_chars (fun c ->
    match c with
    | '?' -> "D"
    | x -> S.of_char x
  ) t in
  puts result
;;

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


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 soc = split_on_char

  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 t = rds () in
  let spt = stocl t in
  let rec pdpd sl = function
    | [] -> sl
    | h::m::t when m = '?' ->
      if h = 'P' then pdpd ('P'::'D'::sl) t else pdpd ('D'::'D'::sl) t
    | h::t when h = '?' -> pdpd ('D'::sl) t
    | h::t -> pdpd (h::sl) t
  in
  let sl = L.rev @@ pdpd [] spt in
  let result = cltos sl in
  puts result
;;


open Batteries
let t = Scanf.sscanf (read_line()) "%s" (fun t -> t)
(* 文字列をcharのlistにする *)
let explode s = List.init (String.length s) (String.get s)
let rec loop result lst =
  match lst with
  | [] -> result |> List.rev
  | first :: [] -> if first = '?' then loop ('D' :: result) [] else loop (first :: result) []
  | first :: rest ->
    if first = '?' then loop ('D' :: result) (rest) else
    loop (first :: result) (rest)
let r = loop [] @@ explode t |> Array.of_list
(* charのlistをstringに *)
let _ = print_endline @@ String.init (Array.length r) @@ fun a -> r.(a)


let () =
  let s = Bytes.of_string @@ read_line () in
  if Bytes.get s (Bytes.length s - 1) = '?' then
    s.[Bytes.length s - 1] <- 'D';
  for i = Bytes.length s - 2 downto 0 do
    if Bytes.get s i = '?' then
      s.[i] <- if Bytes.get s (i + 1) = 'D' then 'P' else 'D'
  done;
  print_endline @@ Bytes.to_string s


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let a = read_line () |> split_string ~pattern:" " |> List.map int_of_string

let rec range res acc = match res, acc with
  | [], _ -> failwith "program error"
  | res, [] -> res
  | (l, r) :: _, x :: xs -> range (((l + 1) / 2 + x, r + x) :: res) xs
let range = function
  | [] -> failwith "program error"
  | x :: xs -> range [(x, x)] xs

let rec build sum prev rs ns = match rs, ns with
  | _, [] -> sum
  | (l, r) :: rs, n :: ns -> let t = min (prev * 2) r in build (sum + t) (t - n) rs ns
  | _ -> failwith "program error"

let () =
  let acc = range (List.rev a) in
  match acc, a with
    | x :: xs, n :: ns -> Printf.printf "%d\n" @@ if fst x = 1 then build 1 1 xs ns else -1
    | _ -> failwith "program error"

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 ]
                    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).


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

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 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 _ =
  let n = rdi () in
  let hpb = match n mod 10 with
  | 3 -> "bon"
  | 0 | 1 | 6 | 8 -> "pon"
  | _ -> "hon"
  in puts hpb;;

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 = sscanf (read_line ()) "%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 = read_int () in
let str = read_line () in
if String.length str <= k then
  print_endline str
else
  print_endline ((Str.string_before str k) ^ "...")


open Base
open Stdio

let () =
  match In_channel.input_line In_channel.stdin with
  | None -> failwith "cannot read input"
  | Some k -> let k = Int.of_string k in
    match In_channel.input_line In_channel.stdin with
    | None -> failwith "cannot read input"
    | Some x -> let length = String.length x in
      if length <= k
      then print_endline x
      else print_endline ((String.sub x ~pos:0 ~len:k) ^ "...")


let read_floats () =
  let str = read_line() in
  List.map (fun x -> float_of_string x) (Str.split (Str.regexp " +") str)
;;

let input = read_floats() in
let a = List.nth input 0 in
let b = List.nth input 1 in
let h = List.nth input 2 in
let m = List.nth input 3 in
let pi = acos (-1.) in
let x1 = a *. cos (h /. 12. *. 2. *. pi +. m /. 720. *. 2. *. pi) in
let y1 = a *. sin (h /. 12. *. 2. *. pi +. m /. 720. *. 2. *. pi) in
let x2 = b *. cos (m /. 60. *. 2. *. pi) in
let y2 = b *. sin (m /. 60. *. 2. *. pi) in
let sqx = (x1 -. x2) *. (x1 -. x2) in
let sqy = (y1 -. y2) *. (y1 -. y2) in
print_endline (string_of_float (sqrt (sqx +. sqy)))

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 (a, b, h, m) = Scanf.sscanf (read_line ()) "%d %d %d %d" @@ fun a b h m -> (a, b, h, m)

let pi = 3.14159265358

let () =
  let t = 2. *. (float h /. 12. +. float m /. 60. /.12.) in
  let s = 2. *. (float m /. 60.) in
  let diff = ref (t -. s) in
  if !diff < 0. then diff := -1. *. !diff;
  let c2 = (float @@ a * a) +. (float @@ b * b) -. (float @@ 2 * a * b) *. cos (!diff *. pi) in
  print_float @@ sqrt c2;


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 (Ord : Set.OrderedType) = struct
  include Set.Make(Ord)

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

module St = MySet

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

  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 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
  module Vs = St(Int)
  module Vm = Mp(Int)

  type 'a t = { nb : Vs.t Vm.t; vdt : 'a Vm.t }

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

  let add_edge (e : int * int) g =
    let (v1, v2) = e in
    let nbvs = g.nb |> Vm.apply_or Vs.empty v1 in
    let nb1 = g.nb |> Vm.add v1 (nbvs |> Vs.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
module Vs = G.Vs
module Vm = G.Vm

let _ =
  let (n, m) = rdi2 () in
  let es = rdv m rdi2 in
  let graph = G.from_uedges es in

  let expand v vp =
    let nb = (graph.nb |> Vm.apply v) in
    nb |> Vs.fold' (fun nbv (nfr, cvp) ->
      if Vm.mem nbv cvp then
        (nfr, cvp)
      else
        (nfr |> Vs.add nbv,
          cvp |> Vm.add nbv v)
    ) (Vs.empty, vp) in

  let rec march fr vp =
    if Vs.is_empty fr then
      vp
    else
      let (nfr, nvp) =
        fr |> Vs.fold' (fun v (nfr, cvp) ->
          let (nfr1, nvp) = expand v cvp in
          (Vs.union nfr nfr1, nvp)
        ) (Vs.empty, vp)
      in
      march nfr nvp
  in

  let rvp = march (Vs.singleton 1) (Vm.singleton 1 0) in
  let result = L.tl @@ Vm.bindings rvp in

  puts "Yes";
  result |> L.iter (fun (v, p)-> puti p)
;;

Score: 400 points

Problem Statement

There is a cave.

The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room 1. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room 1.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room 1 after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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

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

A_i \neq B_i\ (1 \leq i \leq M)

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print N lines. The first line should contain Yes, and the i-th line (2 \leq i \leq N) should contain the integer representing the room indicated by the signpost in Room i.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room 2, you will reach Room 1 after traversing one passage: (2) \to 1. This is the minimum number of passages possible.

Starting in Room 3, you will reach Room 1 after traversing two passages: (3) \to 2 \to 1. This is the minimum number of passages possible.

Starting in Room 4, you will reach Room 1 after traversing two passages: (4) \to 2 \to 1. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

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

Sample Output 2

Yes
6
5
5
1
1

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