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 putyn b = puts (if b then "Yes" else "No")
let puti i = puts @@ i2s i

let rep lb bnd ub f = match bnd with
  | `To -> for i = lb to ub do f i done
  | `Til -> for i = lb to (ub - 1) do f i done

let rep2 lb1 bnd1 ub1 () lb2 bnd2 ub2 f =
  match (bnd1, bnd2) with
  | (`To, `To) -> for i = lb1 to ub1 do for j = lb2 to ub2 do f i j done done
  | (`To, `Til) -> for i = lb1 to ub1 do for j = lb2 to (ub2 - 1) do f i j done done
  | (`Til, `To) -> for i = lb1 to (ub1 - 1) do for j = lb2 to ub2 do f i j done done
  | (`Til, `Til) -> for i = lb1 to (ub1 - 1) do for j = lb2 to (ub2 - 1) do f i j done done

module JunkList = 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 = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = JunkList

module JunkArray = 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 = JunkArray

module JunkString = 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 = JunkString

let spsp s = S.split_on_char ' ' s

module JunkSortedSet = 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 = JunkSortedSet

module JunkSortedMap  = 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 = JunkSortedMap

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

exception ArithmeticException of string

module JunkIntArithmetic = struct

  let rec power x e =
    if e = 0 then x
    else
      let rec loop r x2 e' =
        if e' = 0 then r
        else if e' land 1 = 0 then loop r (x2 * x2) (e' lsr 1)
        else loop (r * x2) (x2 * x2) (e' lsr 1)
      in loop 1 x e

  let rec powers_le_1000 x =
    if x > 32 then [x]
    else
      L.init 9 (fun e -> power x (e + 1))
      |> L.filter (fun y -> y < 1000)

  let primes_le_1000 = [2;3;5;7;11;13;17;19;23;29;31;37;41;
    43;47;53;59;61;67;71;73;79;83;89;97;101;
    103;107;109;113;127;131;137;139;149;151;157;163;167;
    173;179;181;191;193;197;199;211;223;227;229;233;239;
    241;251;257;263;269;271;277;281;283;293;307;311;313;
    317;331;337;347;349;353;359;367;373;379;383;389;397;
    401;409;419;421;431;433;439;443;449;457;461;463;467;
    479;487;491;499;503;509;521;523;541;547;557;563;569;
    571;577;587;593;599;601;607;613;617;619;631;641;643;
    647;653;659;661;673;677;683;691;701;709;719;727;733;
    739;743;751;757;761;769;773;787;797;809;811;821;823;
    827;829;839;853;857;859;863;877;881;883;887;907;911;
    919;929;937;941;947;953;967;971;977;983;991;997]

    let primes_and_powers_le_1000 =
      [2;3;4;5;7;8;9;11;13;16;17;19;23;25;27;29;31;32;37;41;
      43;47;49;53;59;61;64;67;71;73;79;81;83;89;97;
      101;103;107;109;113;121;125;127;128;131;137;139;149;151;
      157;163;167;169;173;179;181;191;193;197;199;211;223;227;
      229;233;239;241;243;251;256;257;263;269;271;277;281;283;
      289;293;307;311;313;317;331;337;343;347;349;353;359;361;
      367;373;379;383;389;397;401;409;419;421;431;433;439;443;
      449;457;461;463;467;479;487;491;499;503;509;512;521;523;
      529;541;547;557;563;569;571;577;587;593;599;601;607;613;
      617;619;625;631;641;643;647;653;659;661;673;677;683;691;
      701;709;719;727;729;733;739;743;751;757;761;769;773;787;
      797;809;811;821;823;827;829;839;841;853;857;859;863;877;
      881;883;887;907;911;919;929;937;941;947;953;961;967;971;
      977;983;991;997]

  let factorize_with ps n =
    let rec loop acc ps e n' =
      if n' <= 1 then ([], n')
      else
        match ps with
        | [] -> (acc, n')
        | p::t ->
          let r = n' mod p in
          if r = 0 then (
            if n' = p then ((p, e + 1) :: acc, 1)
            else loop acc ps (e + 1) (n' / p)
          ) else
            loop (if e = 0 then acc else (p, e) :: acc) t 0 n'
    in
    let (fs, r) = loop [] ps 0 n in
    (L.rev fs, r)

  let factorize_le_million n =
    factorize_with primes_le_1000 n

  let rec to_bits_le n =
    if n = 0 then []
    else (n mod 2) :: to_bits_le (n lsr 1)

  let rec gcd x y =
    match x mod y with
    | 0 -> y
    | z -> gcd y z

  let ext_euclid a b =
    let rec next (r0, s0, t0) (r1, s1, t1) =
      match r1 with
      | 0 -> (r0, s0, t0)
      | r2 ->
        let q = r0 / r1 in
        next (r1, s1, t1) (r0 - q * r1, s0 - q * s1, t0 - q * t1)
    in
    if a < b then
      let (g, y, x) = next (b, 1, 0) (a, 0, 1) in (g, x, y)
    else
      next (a, 1, 0) (b, 0, 1)

  let modinv x m =
    let (g, y, z) = ext_euclid x m in
    match g with
    | 1 -> y mod m
    | _ -> raise @@ ArithmeticException "Not relatively prime"

end

module N = JunkIntArithmetic

module JunkMatrix = struct

  type 'a t = { w : int; h : int; e : 'a array array }

  let make w h e0 =
    { w = w; h = h; e = A.make_matrix w h e0 }

  let from_columns w h e0 elems =
    let matr = make w h e0 in
    elems |> L.iteri (fun j col ->
      col |> L.iteri (fun i x -> matr.e.(i).(j) <- x));
    matr

  let blit (mats, rs, cs, w, h) (matd, rd, cd) =
    rep2 0 `Til w () 0 `Til h (fun i j ->
        matd.e.(rd + i).(cd + j) <- mats.e.(rs + i).(cs + j))

  let expand (w1, h1) (w2, h2) e0 mat =
    let matr = make w2 h2 e0 in
    blit (mat, 0, 0, w1, h1) (matr, 0, 0);
    matr

end

module M = JunkMatrix

module type FieldOps = sig
  type elt
  val zero : elt
  val one : elt
  val neg : elt -> elt
  val rcp : elt -> elt
  val add : elt -> elt -> elt
  val sub : elt -> elt -> elt
  val mul : elt -> elt -> elt
  val div : elt -> elt -> elt
end

module JunkLinearAlgebra (Fop : FieldOps) = struct

  type t = Fop.elt M.t

  let zero w h = M.make w h Fop.zero

  let prod (mat1 : t) (mat2 : t) =
    let matr = zero mat1.w mat2.h in
    rep2 0 `Til mat1.w () 0 `Til mat2.h (fun i j ->
        matr.e.(i).(j) <-
          mat1.e.(i) |> A.foldli (fun
            acc k x -> Fop.add acc (Fop.mul x mat2.e.(k).(i)))
            Fop.zero);
    matr

  exception NotZero of int
  let is_zero (mat : t) =
    try (
      rep 0 `Til mat.w (fun i ->
        if mat.e.(i) |> A.for_all (fun x -> x <> Fop.zero)
          then raise (NotZero 1)
      );
      true
    ) with _ -> false

  let col_addmul c1 (c2, a) (mat : t) =
    rep 0 `Til mat.h (fun i ->
      mat.e.(i).(c1) <- Fop.add mat.e.(i).(c1) (Fop.mul a mat.e.(i).(c2)))

  let col_inner_prod c1 c2 (mat : t) =
    let sum = ref Fop.zero in
    rep 0 `Til mat.h (fun i ->
      sum := Fop.add !sum @@ Fop.mul mat.e.(i).(c1) mat.e.(i).(c2));
    !sum

  (* let orth_extend k0 k1 mat = *)
  (*   let matx = extend (k0, h) ((k0 + k1), h) 0 mat in *)
  (*   rep k0 `Til (k0 + k1) (fun t -> *)
  (*     rep 0 `Til t (fun s ->  *)
  (*       let ip = col_inner_prod s t h matx in *)
  (*       col_addmul t (s, ip) h matx)); *)
  (*   submat (k0, 0) (k0 + k1 - 1, h - 1) matx *)

end

module type OrderedData = sig
  type t
  val compare : t -> t -> int
  val default : t
end

module JunkGraph = struct

  type 'a v_t = int * 'a
  type 'a t = { vs : 'a v_t array; nb : int Ss.t array }

  let empty nv vd =
    let vs0 = Array.make nv (0, vd) in
    for i = 0 to (nv - 1) do vs0.(i) <- (i, vd) done;
    {
      vs = vs0;
      nb = A.make nv Ss.empty
    }

  let add_edge (e : int * int) vd g =
    let (v1, v2) = e in
    g.vs.(v1 - 1) <- (v1, vd);
    g.vs.(v2 - 1) <- (v2, vd);
    g.nb.(v1 - 1) <- g.nb.(v1 - 1) |> Ss.add v2;
    g

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

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

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

end

module G = JunkGraph

module JunkGraphAlgorithms (Vdt : OrderedData) = struct

  type t = Vdt.t G.t

  module V = struct
    type t = int * Vdt.t
    let compare (vi1, vd1) (vi2, vd2) =
      let c1 = Vdt.compare vd1 vd2 in
      if c1 = 0 then compare vi1 vi2
      else c1

    let default i = (i, Vdt.default)
    let index (v : t) = fst v
  end

  module Vset = Ss.Make(V)

  let print_vertices label vs =
    printf "%s: " label;
    vs |> Vset.iter (fun (vi, _) -> printf "%d " vi);
    puts ""

  let nbiter (upd : V.t -> V.t -> t -> t * bool)
    (ui : int) (fr : Vset.t) (cls : int Ss.t) (g : t) =
    let nb = g.nb.(ui - 1) in
    let result = nb |> Ss.foldl (fun (ga, nxfr, nxcls) vi ->
    (* puts "nxcls: "; *)
      (* Ss.iter (fun x -> printf "%d " x) nxcls; puts ""; *)
      if ui = vi || Ss.mem vi nxcls then
        (ga, nxfr, nxcls)
      else
        let ue = g.vs.(ui - 1) and ve = g.vs.(vi - 1) in
        let (gu, close) = upd ue ve ga in
        (gu,
          nxfr |> Vset.add ve,
          if close then nxcls |> Ss.add vi else nxcls)
    ) (g, fr, cls)
    in (* puts "";  *)result

  let traverse (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (ve, fr') = Vset.pop_min fr in
      let (vi, _) = ve in
      let (gu, nxfr, nxcls) = nbiter upd vi fr' cls g' in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let frontier (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (gu, nxfr, nxcls) =
        fr |> Vset.foldl (fun (ga, nxfra, nxclsa) ve ->
          let (vi, _) = ve in
          nbiter upd vi nxfra nxclsa ga
        ) (g', Vset.empty, cls)
      in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let bfs (upd : V.t -> V.t -> t -> t) =
    frontier (fun fr cls g' -> (upd fr cls g', true))

end

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

module Galg = JunkGraphAlgorithms (
  struct
    type t = int
    let compare = compare
    let default = 0
  end)

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 _ =
  let n = rdi () in
  let ass = rdhi () in
  let q = rdi () in
  let bcs = rdvi2 q in

  let rec make_cnt cnt = function
  | [] -> cnt
  | h::t -> cnt.(h) <- cnt.(h) + 1; make_cnt cnt t
  in

  let cnt = make_cnt (Array.make 100001 0) ass in

  let rec replace = function
  | [] -> ()
  | h::t ->
    let (b, c) = h in
    let pb = cnt.(b) and pc = cnt.(c) in
    cnt.(c) <- pc + pb;
    cnt.(b) <- 0;
    let sum = A.sum @@ A.mapi (fun i x -> x * i) cnt in
    puti sum;
    replace t
  in

  replace bcs;

();;

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 Base
open Stdio

let () =
  let (x, y) = Caml.Scanf.scanf "%d %d" (fun x y -> x, y) in
  let ans = ref "No" in
  for i = 0 to x do
    let a = i in
    let b = x - i in
    if phys_equal (2 * a + 4 * b) y
    then ans := "Yes"
  done;
  print_endline !ans;

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

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.

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.


(* Vicfred
 * https://atcoder.jp/contests/abc170/tasks/abc170_b
 * brute force *)
let solve x y =
    let a, b = 4*x - y, y - 2*x in
    if a mod 2 = 0 && b mod 2 = 0 && a >= 0 && b >= 0 then "Yes" else "No"

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


let () = Scanf.scanf "%d %d\n" @@ fun x n ->
  let ps = List.init n @@ fun _ -> Scanf.scanf "%d " Fun.id in
  Printf.printf "%d\n" @@
  List.fold_left (fun y y' ->
    if abs (y - x) <= abs (y' - x) then y else y') 0 @@
  List.filter (fun y -> List.for_all (( <> ) y) ps) @@
  List.init 102 Fun.id

Score : 300 points

Problem Statement

Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.

Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

1 \leq X \leq 100

0 \leq N \leq 100

1 \leq p_i \leq 100

p_1, \ldots, p_N are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X N
p_1 ... p_N

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the one nearest to 6 is 8.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence 4, 7, 10, 6, 5, the ones nearest to 10 are 9 and 11. We should print the smaller one, 9.

Sample Input 3

100 0

Sample Output 3

100

When N = 0, the second line in the input will be empty. Also, as seen here, X itself can be the answer.


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

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

let () =
        let (ans, _) =
                (
                        if lst = [] then
                                (x, 0)
                        else
                                let set =
                                        (
                                                let max = List.max lst in
                                                let pset = List.range 0 `To max
                                                           |> Set.of_list in
                                                let sset = Set.of_list lst in
                                                        Set.diff pset sset
                                        ) in
                                let lst = Set.to_list set in
                                        List.map (fun elmnt -> (elmnt, abs (elmnt - x))) lst
                                        |> List.sort (fun (el1, diff1) (el2, diff2) -> compare diff1 diff2)
                                        |> List.hd
                ) in
                Printf.printf "%d\n" ans


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 = float_of_int
let i2f = int_of_float

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

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

let rep lb bnd ub f = match bnd with
  | `To -> for i = lb to ub do f i done
  | `Til -> for i = lb to (ub - 1) do f i done

let rep2 lb1 bnd1 ub1 () lb2 bnd2 ub2 f =
  match (bnd1, bnd2) with
  | (`To, `To) -> for i = lb1 to ub1 do for j = lb2 to ub2 do f i j done done
  | (`To, `Til) -> for i = lb1 to ub1 do for j = lb2 to (ub2 - 1) do f i j done done
  | (`Til, `To) -> for i = lb1 to (ub1 - 1) do for j = lb2 to ub2 do f i j done done
  | (`Til, `Til) -> for i = lb1 to (ub1 - 1) do for j = lb2 to (ub2 - 1) do f i j done done

module ToyList = 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 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 = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i
end

module L = ToyList

module ToyArray = 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 takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* 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 = 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 = ToyArray

module ToyString = 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 = ToyString

let spsp s = S.split_on_char ' ' s

module ToySortedSet = 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 = ToySortedSet

module ToySortedMap  = 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 = ToySortedMap

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

exception ArithmeticException of string

module ToyIntArithmetic = struct

  let rec to_bits_le n =
    if n = 0 then []
    else (n mod 2) :: to_bits_le (n lsr 1)

  let rec gcd x y =
    match x mod y with
    | 0 -> y
    | z -> gcd y z

  let ext_euclid a b =
    let rec next (r0, s0, t0) (r1, s1, t1) =
      match r1 with
      | 0 -> (r0, s0, t0)
      | r2 ->
        let q = r0 / r1 in
        next (r1, s1, t1) (r0 - q * r1, s0 - q * s1, t0 - q * t1)
    in
    if a < b then
      let (g, y, x) = next (b, 1, 0) (a, 0, 1) in (g, x, y)
    else
      next (a, 1, 0) (b, 0, 1)

  let modinv x m =
    let (g, y, z) = ext_euclid x m in
    match g with
    | 1 -> y mod m
    | _ -> raise @@ ArithmeticException "Not relatively prime"

end

module N = ToyIntArithmetic

module ToyMatrix = struct

  type 'a t = { w : int; h : int; e : 'a array array }

  let make w h e0 =
    { w = w; h = h; e = A.make_matrix w h e0 }

  let from_columns w h e0 elems =
    let matr = make w h e0 in
    elems |> L.iteri (fun j col ->
      col |> L.iteri (fun i x -> matr.e.(i).(j) <- x));
    matr

  let blit (mats, rs, cs, w, h) (matd, rd, cd) =
    rep2 0 `Til w () 0 `Til h (fun i j ->
        matd.e.(rd + i).(cd + j) <- mats.e.(rs + i).(cs + j))

  let expand (w1, h1) (w2, h2) e0 mat =
    let matr = make w2 h2 e0 in
    blit (mat, 0, 0, w1, h1) (matr, 0, 0);
    matr

end

module M = ToyMatrix

module type FieldOps = sig
  type elt
  val zero : elt
  val one : elt
  val neg : elt -> elt
  val rcp : elt -> elt
  val add : elt -> elt -> elt
  val sub : elt -> elt -> elt
  val mul : elt -> elt -> elt
  val div : elt -> elt -> elt
end

module ToyLinearAlgebra (Fop : FieldOps) = struct

  type t = Fop.elt M.t

  let zero w h = M.make w h Fop.zero

  let prod (mat1 : t) (mat2 : t) =
    let matr = zero mat1.w mat2.h in
    rep2 0 `Til mat1.w () 0 `Til mat2.h (fun i j ->
        matr.e.(i).(j) <-
          mat1.e.(i) |> A.foldli (fun
            acc k x -> Fop.add acc (Fop.mul x mat2.e.(k).(i)))
            Fop.zero);
    matr

  exception NotZero of int
  let is_zero (mat : t) =
    try (
      rep 0 `Til mat.w (fun i ->
        if mat.e.(i) |> A.for_all (fun x -> x <> Fop.zero)
          then raise (NotZero 1)
      );
      true
    ) with _ -> false

  let col_addmul c1 (c2, a) (mat : t) =
    rep 0 `Til mat.h (fun i ->
      mat.e.(i).(c1) <- Fop.add mat.e.(i).(c1) (Fop.mul a mat.e.(i).(c2)))

  let col_inner_prod c1 c2 (mat : t) =
    let sum = ref Fop.zero in
    rep 0 `Til mat.h (fun i ->
      sum := Fop.add !sum @@ Fop.mul mat.e.(i).(c1) mat.e.(i).(c2));
    !sum

  (* let orth_extend k0 k1 mat = *)
  (*   let matx = extend (k0, h) ((k0 + k1), h) 0 mat in *)
  (*   rep k0 `Til (k0 + k1) (fun t -> *)
  (*     rep 0 `Til t (fun s ->  *)
  (*       let ip = col_inner_prod s t h matx in *)
  (*       col_addmul t (s, ip) h matx)); *)
  (*   submat (k0, 0) (k0 + k1 - 1, h - 1) matx *)

end

module type OrderedData = sig
  type t
  val compare : t -> t -> int
  val default : t
end

module ToyGraph = struct

  type 'a v_t = int * 'a
  type 'a t = { vs : 'a v_t array; nb : int Ss.t array }

  let empty nv vd =
    let vs0 = Array.make nv (0, vd) in
    for i = 0 to (nv - 1) do vs0.(i) <- (i, vd) done;
    {
      vs = vs0;
      nb = A.make nv Ss.empty
    }

  let add_edge (e : int * int) vd g =
    let (v1, v2) = e in
    g.vs.(v1 - 1) <- (v1, vd);
    g.vs.(v2 - 1) <- (v2, vd);
    g.nb.(v1 - 1) <- g.nb.(v1 - 1) |> Ss.add v2;
    g

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

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

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

end

module G = ToyGraph

module ToyGraphAlgorithms (Vdt : OrderedData) = struct

  type t = Vdt.t G.t

  module V = struct
    type t = int * Vdt.t
    let compare (vi1, vd1) (vi2, vd2) =
      let c1 = Vdt.compare vd1 vd2 in
      if c1 = 0 then compare vi1 vi2
      else c1

    let default i = (i, Vdt.default)
    let index (v : t) = fst v
  end

  module Vset = Ss.Make(V)

  let print_vertices label vs =
    printf "%s: " label;
    vs |> Vset.iter (fun (vi, _) -> printf "%d " vi);
    puts ""

  let nbiter (upd : V.t -> V.t -> t -> t * bool)
    (ui : int) (fr : Vset.t) (cls : int Ss.t) (g : t) =
    let nb = g.nb.(ui - 1) in
    let result = nb |> Ss.foldl (fun (ga, nxfr, nxcls) vi ->
    (* puts "nxcls: "; *)
      (* Ss.iter (fun x -> printf "%d " x) nxcls; puts ""; *)
      if ui = vi || Ss.mem vi nxcls then
        (ga, nxfr, nxcls)
      else
        let ue = g.vs.(ui - 1) and ve = g.vs.(vi - 1) in
        let (gu, close) = upd ue ve ga in
        (gu,
          nxfr |> Vset.add ve,
          if close then nxcls |> Ss.add vi else nxcls)
    ) (g, fr, cls)
    in (* puts "";  *)result

  let traverse (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (ve, fr') = Vset.pop_min fr in
      let (vi, _) = ve in
      let (gu, nxfr, nxcls) = nbiter upd vi fr' cls g' in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let frontier (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (gu, nxfr, nxcls) =
        fr |> Vset.foldl (fun (ga, nxfra, nxclsa) ve ->
          let (vi, _) = ve in
          nbiter upd vi nxfra nxclsa ga
        ) (g', Vset.empty, cls)
      in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let bfs (upd : V.t -> V.t -> t -> t) =
    frontier (fun fr cls g' -> (upd fr cls g', true))

end

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

module Galg = ToyGraphAlgorithms (
  struct
    type t = int
    let compare = compare
    let default = 0
  end)

let _ =
  let (x, n) = rdi2 () in
  if n = 0 then (ignore @@ rds (); puti x)
  else (
    let ps = Ss.of_list @@ rdhi () in
    let nps = L.range 0 `To 101 |> L.filter (fun z -> Ss.nmem z ps) in
    let difs = nps |> L.map (fun z -> (abs (x - z), z)) in
    let (_, p) = difs
      |> L.sort (fun (a, _) (b, _) -> compare a b)
      |> L.hd
    in
    puti p)
;;


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

let () =
  Printf.printf "%d\n" @@
    if n = 0 then x
    else Array.init 102 (fun i -> i - 1)
      |> Array.to_list
      |> List.filter (fun i -> not (List.mem i p))
      (* |> (fun acc -> List.iter (Printf.printf "%d ") acc; acc) *)
      |> List.map (fun i -> (abs (i - x), i))
      |> List.sort compare
      |> (List.hd $ snd)


open Batteries
let x, n = Scanf.sscanf (read_line()) "%d %d" (fun  x n-> x ,n)
let p_ = read_line ()
let p = (if p_ = "" then [] else p_ |> String.split_on_char ' ' |> List.map int_of_string)
let rec loop i =
  if List.mem (x - i) p then
  if List.mem (x + i) p then (loop (i+1))
  else (x + i)
  else (x - i)
let _ = Printf.printf "%d\n" @@ loop 0


let () =
  Scanf.scanf "%s\n" @@ fun s ->
  Printf.printf "%s\n" (String.sub s 0 3)

Score : 100 points

Problem Statement

When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters.
You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.

Constraints

3 \leq |S| \leq 20

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print your answer.

Sample Input 1

takahashi

Sample Output 1

tak

Sample Input 2

naohiro

Sample Output 2

nao


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 rec main_loop i dp =
  if i >= n then print_string "\n" else (
    Printf.printf "%d " dp.(i);
    main_loop (i+1) dp
  )

let rec k_loop l a_ =
  if l >= k then a_ else begin
  let dp = Array.init n @@ fun _ -> 0 in
  let rec do_lamp lamp =
  for i = lamp - a_.(lamp) to lamp + a_.(lamp) do
    if i < 0 || i >= 5 then () else (
      dp.(i) <- dp.(i) + 1
    )
  done in

  let rec loop i =
  if i >= n then () else (
    do_lamp i; loop (i+1)
  )
  in loop 0; k_loop (l+1) dp
  end

let dp1 = k_loop 0 a

let _ = main_loop 0 dp1

Score : 500 points

Problem Statement

We have N bulbs arranged on a number line, numbered 1 to N from left to right.
Bulb i is at coordinate i.

Each bulb has a non-negative integer parameter called intensity.
When there is a bulb of intensity d at coordinate x, the bulb illuminates the segment from coordinate x-d-0.5 to x+d+0.5.
Initially, the intensity of Bulb i is A_i. We will now do the following operation K times in a row:

For each integer i between 1 and N (inclusive), let B_i be the number of bulbs illuminating coordinate i. Then, change the intensity of each bulb i to B_i.

Find the intensity of each bulb after the K operations.

Constraints

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

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

0 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \ldots A_N

Output

Print the intensity A{'}_i of each bulb i after the K operations to Standard Output in the following format:

A{'}_1 A{'}_2 \ldots A{'}_N

Sample Input 1

5 1
1 0 0 1 0

Sample Output 1

1 2 2 1 2

Initially, only Bulb 1 illuminates coordinate 1, so the intensity of Bulb 1 becomes 1 after the operation.
Similarly, the bulbs initially illuminating coordinate 2 are Bulb 1 and 2, so the intensity of Bulb 2 becomes 2.

Sample Input 2

5 2
1 0 0 1 0

Sample Output 2

3 3 4 4 3


open Batteries
let n = read_int ()
let dp = Array.init n @@ fun _ -> [|0; 0|]
let rec vw_loop i =
  if i >= n then () else (
    Scanf.sscanf (read_line()) "%d %d" (fun v w ->
      dp.(i) <- [|v; w|]
    ); vw_loop (i+1)
  )
let _ = vw_loop 0
let dp2 = Array.init (n+1) @@ fun _ -> []
let rec dp_loop i =
  if i >= n then () else (
    if i = 0 then (dp2.(i) <- dp.(i) :: dp2.(i); dp_loop (i+1)) else (
      dp2.(i) <- dp.(i) :: dp2.(i / 2); dp_loop (i+1)
    )
  )
let _ = dp_loop 0
let q = read_int ()

(* ここからナップザック *)
let nap items l =
(* 価値；重さ*)
  let n_ = Array.length items in
  let nap_dp = Array.init (l+1) @@ fun _ -> 0 in
  for i = 0 to (n_-1) do
    let rec w_loop w =
      if w < 0 then () else (
        if w - items.(i).(1) >= 0 then (
          nap_dp.(w) <- max (nap_dp.(w)) (nap_dp.(w - items.(i).(1)) + items.(i).(0));
          w_loop (w-1)
        ) else w_loop (w-1)
      ) in w_loop l
  done; nap_dp.(l)

(* nap [|[|3;2|];[|2;1|];[|6;3|];[|1;2|];[|3;1|];[|85;5|]|] 9;; *)

let rec q_loop i =
  if i >= q then () else (
    Scanf.sscanf (read_line()) "%d %d" (fun v l ->
      Printf.printf "%d\n" @@ nap (Array.of_list dp2.(v-1)) l
    ); q_loop (i+1)
  )

let _ = q_loop 0

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


open Scanf
open Printf
open Big_int

let multiplication lst =
  let rec loop total l = match l with
      [] -> total
    | first :: rest -> if gt_big_int (mult_big_int (big_int_of_int first) (big_int_of_int total))
                                     (big_int_of_int 1_000_000_000_000_000_000) then -1
                       else loop (first * total) rest
  in loop 1 lst

let n = sscanf (read_line ()) "%d" (fun n -> n)
let a_list = List.map (fun n -> int_of_string n) (String.split_on_char ' ' (read_line ()))
let () = printf "%d\n" (multiplication a_list)

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


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 ctos = String.of_char
let stocl = String.to_list
let cltos = String.of_list

module MyString = struct
  include String

  let map_to_list f s = L.map f (stocl s)
  let mapi_to_list 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 spoc = S.split_on_char
let spsp s = spoc ' ' s

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 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 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 n = rdi () in
  let mx = 1000000 in
  let primes_to_1000 = [
  2;3;5;7;11;13;17;19;23;29;31;37;41;43;47;53;59;61;67;71;73;79;83;89;97;101;
  103;107;109;113;127;131;137;139;149;151;157;163;167;173;179;181;191;193;197;
  199;211;223;227;229;233;239;241;251;257;263;269;271;277;281;283;293;307;311;
  313;317;331;337;347;349;353;359;367;373;379;383;389;397;401;409;419;421;431;
  433;439;443;449;457;461;463;467;479;487;491;499;503;509;521;523;541;547;557;
  563;569;571;577;587;593;599;601;607;613;617;619;631;641;643;647;653;659;661;
  673;677;683;691;701;709;719;727;733;739;743;751;757;761;769;773;787;797;809;
  811;821;823;827;829;839;853;857;859;863;877;881;883;887;907;911;919;929;937;
  941;947;953;967;971;977;983;991;997] in

  let rec indivisible k pl = match pl with
    | [] -> true
    | h::t -> if k > h && k mod h = 0 then false else indivisible k t
  in

  let primes = L.range 2 `To mx |> L.filter (fun x -> indivisible x primes_to_1000) in

  let is_prime x = x >= 2 && indivisible x primes in

  let exps_lt x =
    let rec aux el x =
      let y = x * (L.hd el) in
      if y > mx * mx then L.rev el
      else aux (y::el) x
    in aux [x] x
  in

  let prime_exps =
    primes |> L.flatmap (fun x -> exps_lt x)
  in

  let rec divp k c pl = match pl with
    | [] -> (k, c)
    | h::t -> if k = 1 then (k, c)
      else if k mod h = 0 then divp (k / h) (c + 1) t
      else divp k c t
  in
  let (rem, cnt) = divp n 0 prime_exps in

  puti (if n = 1 then 0 else cnt +
    (if rem > mx && is_prime rem then 1 else 0))
;;

Score : 400 points

Problem Statement

Given is a positive integer N. Consider repeatedly applying the operation below on N:

First, choose a positive integer z satisfying all of the conditions below:

z can be represented as z=p^e, where p is a prime number and e is a positive integer;

z divides N;

z is different from all integers chosen in previous operations.

Then, replace N with N/z.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=12.)

Choose z=3 (=3^1). (Now we have N=4.)

Choose z=4 (=2^2). (Now we have N=1.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose z=2 (=2^1). (Now we have N=32.)

Choose z=4 (=2^2). (Now we have N=8.)

Choose z=8 (=2^3). (Now we have N=1.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

z=1000000007 (=1000000007^1). (Now we have N=1.)

Sample Input 5

997764507000

Sample Output 5

7


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.map (fun c ->
    match c with
    | '?' -> 'D'
    | x -> 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
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 :: second :: rest ->
    if first = '?' && second = 'D' then loop ('P' :: result) (second :: rest) else
    if first = '?' then loop ('D' :: result) (second :: rest) else
    loop (first :: result) (second :: rest)
let r = loop [] @@ explode t |> Array.of_list
(* charのlistをstringに *)
let _ = print_endline @@ String.init (Array.length r) @@ fun a -> r.(a)


print_endline (
  match read_int() mod 10 with
    3 -> "bon"
  | 0 | 1 | 6 | 8 -> "pon"
  | _ -> "hon"
)

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


let pronounce n =
  if n mod 10 = 3 then "bon"
  else if n mod 10 = 0 || n mod 10 = 1 || n mod 10 = 6 || n mod 10 = 8 then "pon"
  else "hon"

let () = Scanf.scanf "%d" (fun n -> Printf.printf "%s\n" (pronounce n))


open Batteries
(* 文字列をcharのlistにする *)
let explode s = List.init (String.length s) (String.get s)
let n = List.nth (read_line() |> explode) 2
let _ = (if n = '2' || n = '4' || n = '5' || n = '7' || n = '9' then "hon" else if n = '3' then "bon" else "pon") |> print_endline


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

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

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.


Scanf.scanf "%d %s" (fun k s ->
    let n = String.length s in
    if n <= k then print_endline s
        else Printf.printf "%s...\n" (String.sub s 0 k)
)


open Printf
open Scanf

let solve a b h m =
  let pi = 4.0 *. atan 1.0 in
  let tm = pi *. m /. 30.0 in
  let th = pi *. (h /. 6.0 +. m /. 360.0) in
  sqrt @@ a *. a +. b *. b -. 2.0 *. a *. b *. cos (tm -. th)

let () =
  scanf "%f %f %f %f " solve |> printf "%.10f\n"

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.


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 = float_of_int
let i2f = int_of_float

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

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

let rep lb bnd ub f = match bnd with
  | `To -> for i = lb to ub do f i done
  | `Til -> for i = lb to (ub - 1) do f i done

let rep2 lb1 bnd1 ub1 () lb2 bnd2 ub2 f =
  match (bnd1, bnd2) with
  | (`To, `To) -> for i = lb1 to ub1 do for j = lb2 to ub2 do f i j done done
  | (`To, `Til) -> for i = lb1 to ub1 do for j = lb2 to (ub2 - 1) do f i j done done
  | (`Til, `To) -> for i = lb1 to (ub1 - 1) do for j = lb2 to ub2 do f i j done done
  | (`Til, `Til) -> for i = lb1 to (ub1 - 1) do for j = lb2 to (ub2 - 1) do f i j done done

module ToyList = 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 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 = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i
end

module L = ToyList

module ToyArray = 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 takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* 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 = 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 = ToyArray

module ToyString = 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 = ToyString

let spsp s = S.split_on_char ' ' s

module ToySortedSet = 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 = ToySortedSet

module ToySortedMap  = 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 = ToySortedMap

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

exception ArithmeticException of string

module ToyIntArithmetic = struct

  let rec to_bits_le n =
    if n = 0 then []
    else (n mod 2) :: to_bits_le (n lsr 1)

  let rec gcd x y =
    match x mod y with
    | 0 -> y
    | z -> gcd y z

  let ext_euclid a b =
    let rec next (r0, s0, t0) (r1, s1, t1) =
      match r1 with
      | 0 -> (r0, s0, t0)
      | r2 ->
        let q = r0 / r1 in
        next (r1, s1, t1) (r0 - q * r1, s0 - q * s1, t0 - q * t1)
    in
    if a < b then
      let (g, y, x) = next (b, 1, 0) (a, 0, 1) in (g, x, y)
    else
      next (a, 1, 0) (b, 0, 1)

  let modinv x m =
    let (g, y, z) = ext_euclid x m in
    match g with
    | 1 -> y mod m
    | _ -> raise @@ ArithmeticException "Not relatively prime"

end

module N = ToyIntArithmetic

module type FieldOps = sig
  type elt
  val zero : elt
  val one : elt
  val neg : elt -> elt
  val rcp : elt -> elt
  val add : elt -> elt -> elt
  val sub : elt -> elt -> elt
  val mul : elt -> elt -> elt
  val div : elt -> elt -> elt
end

module ToyMatrix (Fop : FieldOps) = struct

  type t = { w : int; h : int; e : Fop.elt array array }

  let make w h e0 =
    { w = w; h = h; e = A.make_matrix w h e0 }

  let zero w h = make w h Fop.zero

  let from_columns w h elems =
    let matr = zero w h in
    elems |> L.iteri (fun j col ->
      col |> L.iteri (fun i x -> matr.e.(i).(j) <- x));
    matr

  let blit (mats, rs, cs, w, h) (matd, rd, cd) =
    rep2 0 `Til w () 0 `Til h (fun i j ->
        matd.e.(rd + i).(cd + j) <- mats.e.(rs + i).(cs + j))

  let expand (w1, h1) (w2, h2) e mat =
    let matr = make w2 h2 e in
    blit (mat, 0, 0, w1, h1) (matr, 0, 0);
    matr

  let prod mat1 mat2 =
    let matr = zero mat1.w mat2.h in
    rep2 0 `Til mat1.w () 0 `Til mat2.h (fun i j ->
        matr.e.(i).(j) <-
          mat1.e.(i) |> A.foldli (fun
            acc k x -> Fop.add acc (Fop.mul x mat2.e.(k).(i)))
            Fop.zero);
    matr

  exception NotZero of int
  let is_zero mat =
    try (
      rep 0 `Til mat.w (fun i ->
        if mat.e.(i) |> A.for_all (fun x -> x <> Fop.zero)
          then raise (NotZero 1)
      );
      true
    ) with _ -> false

  let col_addmul c1 (c2, a) mat =
    rep 0 `Til mat.h (fun i ->
      mat.e.(i).(c1) <- Fop.add mat.e.(i).(c1) (Fop.mul a mat.e.(i).(c2)))

  let col_inner_prod c1 c2 mat =
    let sum = ref Fop.zero in
    rep 0 `Til mat.h (fun i ->
      sum := Fop.add !sum @@ Fop.mul mat.e.(i).(c1) mat.e.(i).(c2));
    !sum

  (* let orth_extend k0 k1 mat = *)
  (*   let matx = extend (k0, h) ((k0 + k1), h) 0 mat in *)
  (*   rep k0 `Til (k0 + k1) (fun t -> *)
  (*     rep 0 `Til t (fun s ->  *)
  (*       let ip = col_inner_prod s t h matx in *)
  (*       col_addmul t (s, ip) h matx)); *)
  (*   submat (k0, 0) (k0 + k1 - 1, h - 1) matx *)

end

module type OrderedData = sig
  type t
  val compare : t -> t -> int
  val default : t
end

module ToyGraph = struct

  type 'a v_t = int * 'a
  type 'a t = { vs : 'a v_t array; nb : int Ss.t array }

  let empty nv vd =
    let vs0 = Array.make nv (0, vd) in
    for i = 0 to (nv - 1) do vs0.(i) <- (i, vd) done;
    {
      vs = vs0;
      nb = A.make nv Ss.empty
    }

  let add_edge (e : int * int) vd g =
    let (v1, v2) = e in
    g.vs.(v1 - 1) <- (v1, vd);
    g.vs.(v2 - 1) <- (v2, vd);
    g.nb.(v1 - 1) <- g.nb.(v1 - 1) |> Ss.add v2;
    g

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

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

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

end

module G = ToyGraph

module ToyGraphAlgorithms (Vdt : OrderedData) = struct

  type t = Vdt.t G.t

  module V = struct
    type t = int * Vdt.t
    let compare (vi1, vd1) (vi2, vd2) =
      let c1 = Vdt.compare vd1 vd2 in
      if c1 = 0 then compare vi1 vi2
      else c1

    let default i = (i, Vdt.default)
    let index (v : t) = fst v
  end

  module Vset = Ss.Make(V)

  let print_vertices label vs =
    printf "%s: " label;
    vs |> Vset.iter (fun (vi, _) -> printf "%d " vi);
    puts ""

  let nbiter (upd : V.t -> V.t -> t -> t * bool)
    (ui : int) (fr : Vset.t) (cls : int Ss.t) (g : t) =
    let nb = g.nb.(ui - 1) in
    let result = nb |> Ss.foldl (fun (ga, nxfr, nxcls) vi ->
    (* puts "nxcls: "; *)
      (* Ss.iter (fun x -> printf "%d " x) nxcls; puts ""; *)
      if ui = vi || Ss.mem vi nxcls then
        (ga, nxfr, nxcls)
      else
        let ue = g.vs.(ui - 1) and ve = g.vs.(vi - 1) in
        let (gu, close) = upd ue ve ga in
        (gu,
          nxfr |> Vset.add ve,
          if close then nxcls |> Ss.add vi else nxcls)
    ) (g, fr, cls)
    in (* puts "";  *)result

  let traverse (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (ve, fr') = Vset.pop_min fr in
      let (vi, _) = ve in
      let (gu, nxfr, nxcls) = nbiter upd vi fr' cls g' in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let frontier (upd : V.t -> V.t -> t -> t * bool)
    (fr0 : Vset.t) (cls0 : int Ss.t) (g : t) =

    let rec progress fr cls g' =
      let (gu, nxfr, nxcls) =
        fr |> Vset.foldl (fun (ga, nxfra, nxclsa) ve ->
          let (vi, _) = ve in
          nbiter upd vi nxfra nxclsa ga
        ) (g', Vset.empty, cls)
      in
      if Vset.is_empty nxfr then (gu, nxcls)
      else progress nxfr nxcls gu
    in
    progress fr0 cls0 g

  let bfs (upd : V.t -> V.t -> t -> t) =
    frontier (fun fr cls g' -> (upd fr cls g', true))

end

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

module Galg = ToyGraphAlgorithms(
struct
  type t = int
  let compare = compare
  let default = 0
end)

let _ =
  let (n, m) = rdi2 () in
  let es = rdv m rdi2 in
  let graph = G.from_uedges n 0 es in
  let (result, _) = graph |> Galg.bfs (fun (u, p) (v, _) g ->
    (* printf "u = %d; v = %d; p = %d\n" u v p; *)
    g.vs.(v - 1) <- (v, u); g)
      (Galg.Vset.singleton (1, 0)) (Ss.singleton 1)
  in
  puts "Yes";
  A.tail result.vs 1 |> A.iter (fun (_, 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.


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

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

let (n, m) = scan "%d %d" Tuple2.make
let ls = scan_lines m "%d %d" Tuple2.make

let () =
  let mat = Array.make (succ n) [] in
  ListL.iter ls ~f:(fun (a,b) ->
      mat.(a) <- b::mat.(a);
      mat.(b) <- a::mat.(b));
  let q = Queue.create () in
  Queue.add (1,1) q;
  let parents = Array.make (succ n) 0 in
  let rec wfs q =
    if Queue.is_empty q then ()
    else
      let (p, n) = Queue.pop q in
      if parents.(n) <> 0 then wfs q
      else
        (parents.(n) <- p;
         ListL.iter mat.(n) ~f:(fun m ->
             Queue.add (n, m) q);
         wfs q)
  in
  wfs q;
  if Array.exists ((=) 0)@@ Array.sub parents 2 (Array.length parents - 2)  then
    Printf.printf "No\n"
  else
    (Printf.printf "Yes\n";
     ListL.iter (2++n) ~f:(fun i ->
         Printf.printf "%d\n" parents.(i)))


module WeightedDirectedGraph
: sig
  (* 配列を用いたダイクストラ法の実装
     単純な速さでは一番だが，インターフェースが不便 *)
  module ByArray : sig
    module Make :
      functor
      (* 辺の重さ *)
      (Weight : sig
        type t
        val inf : t
        val zero : t
        val ( + ) : t -> t -> t
        val compare : t -> t -> int
      end)
      (* 道の表現 *)
      (Path : sig
        type t
        (* 辺の名前 *)
        type edge
        (* 長さ0の道 *)
        val nil : t
        (* 道の後ろに辺を付け足した道 *)
        val snoc : t -> edge -> t
      end) ->
        sig
          type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

          (* 頂点を[0, n)の自然数に限定したグラフに対してのダイクストラ法
             時間計算量O(E log E)なので，疎なグラフなら速い *)
          val dijkstra :
          (* 頂点数n *)
          int ->
          (* 隣接リスト *)
          (int -> (int * Weight.t * Path.edge) church_list) ->
          (* 始点 *)
          int ->
          (* 始点からの最短距離と，その経路を返す関数
             始点から辿り着けなければ(inf, Path.nil)を返す
             この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
          (int -> Weight.t * Path.t)

          (* 頂点を[0, n)の自然数に限定したグラフに対してのダイクストラ法
             時間計算量O(V^2)なので，密なグラフなら速い *)
          val dijkstra_dense :
          (* 頂点数n *)
          int ->
          (* 隣接リスト *)
          (int -> (int * Weight.t * Path.edge) church_list) ->
          (* 始点 *)
          int ->
          (* 始点からの最短距離と，その経路を返す関数
             始点から辿り着けなければ(inf, Path.nil)を返す
             この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
          (int -> Weight.t * Path.t)
      end
  end

  (* ハッシュテーブルを用いたダイクストラ法の実装
     配列を用いた実装よりは扱いやすいインターフェースを持つ
     ハッシュ関数を上手く選べば配列を用いた実装より1.5倍遅い程度ですむ *)
  module ByHashtbl : sig
    module Make :
      functor
      (* 頂点 *)
      (Vertex : Hashtbl.HashedType)
      (* 辺の重さ *)
      (Weight : sig
        type t
        val inf : t
        val zero : t
        val ( + ) : t -> t -> t
        val compare : t -> t -> int
      end)
      (* 道の表現 *)
      (Path : sig
        type t
        (* 辺の名前 *)
        type edge
        (* 長さ0の道 *)
        val nil : t
        (* 道の後ろに辺を付け足した道 *)
        val snoc : t -> edge -> t
      end) ->
      sig
        type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

        val dijkstra :
        (* 頂点数（Hashtbl.tを用いるので目安程度） *)
        int ->
        (* 隣接リスト *)
        (Vertex.t -> (Vertex.t * Weight.t * Path.edge) church_list) ->
        (* 始点 *)
        Vertex.t ->
        (* 始点からの最短距離と，その経路を返す関数
           始点から辿り着けなければNot_foundを投げる
           この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
        (Vertex.t -> Weight.t * Path.t)
      end
  end

  (* Mapを用いたダイクストラ法の実装
     配列を用いた実装より4倍ぐらい遅いが，
     一番扱いやすいインターフェースを持ち，無限グラフにも対応可能 *)
  module ByMap : sig
    module Make :
      functor
      (* 頂点 *)
      (Vertex : Map.OrderedType)
      (* 辺の重み *)
      (Weight : sig
        type t
        val zero : t
        val ( + ) : t -> t -> t
        val compare : t -> t -> int
      end)
      (* 道の表現 *)
      (Path : sig
        type t
        (* 辺の名前 *)
        type edge
        (* 長さ0の道 *)
        val nil : t
        (* 道の後ろに辺を付け足した道 *)
        val snoc : t -> edge -> t
      end) ->
      sig
        type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

        val dijkstra :
        (* 隣接リスト *)
        (Vertex.t -> (Vertex.t * Weight.t * Path.edge) church_list) ->
        (* 始点 *)
        Vertex.t ->
        (* 始点からの最短距離と，その経路を返す関数
           始点から辿り着けなければNot_foundを投げる
           この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
        (Vertex.t -> Weight.t * Path.t)
      end
  end
end
= struct
  module type Weight = sig
    type t
    val zero : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end

  module type Path = sig
    type t
    type edge
    val nil : t
    val snoc : t -> edge -> t
  end

  (* 最短距離を格納するデータ構造を抽象化したダイクストラ法の実装 *)
  module Core
    (W : Weight)
    (P : Path)
    (* グラフの頂点を添字とした配列 *)
    (VArray : sig
      type t
      type vertex (* グラフの頂点 *)
      val find : t -> vertex -> W.t * P.t (* 最短距離が格納されていなければNot_foundを投げる *)
      val update : t -> vertex -> W.t * P.t -> unit
    end) =
  struct
    type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

    module WMap = Map.Make (W)

    let dijkstra d es s =
      VArray.update d s (W.zero, P.nil);
      let q = ref (WMap.singleton W.zero [s]) in
      (* 既に最短距離が確定した辺へのクエリを高速化するため，
         ヒープの最小要素をメモしておく *)
      let min_binding_opt = ref (Some (W.zero, [s])) in
      let rec dijkstra_aux t =
        match !min_binding_opt with
        (* もう既に全ての頂点までの距離が分かっている *)
        | None -> VArray.find d t
        | Some (w, us) ->
            match VArray.find d t with
            (* 既に終点までの距離が分かっているので返す *)
            | (x, _) as ans when W.compare x w <= 0 -> ans
            (* 終点までの距離が分かっていないので，ダイクストラ法を続行 *)
            | _ | exception Not_found ->
                q := WMap.remove w !q;
                Fun.flip List.iter us (fun u ->
                  match VArray.find d u with
                  | (d, _) when 0 < W.compare w d -> ()
                  | (_, p) ->
                      (* 未だ頂点uを訪れていない *)
                      Fun.flip (es u).fold () @@ fun (v, c, e) () ->
                        let open W in
                        match VArray.find d v with
                        | (d, _) when W.compare d (w + c) <= 0 -> ()
                        | _ | exception Not_found ->
                            VArray.update d v (w + c, P.snoc p e);
                            q := WMap.update (w + c) (fun vs -> Some (v :: Option.value ~default:[] vs)) !q);
                min_binding_opt := WMap.min_binding_opt !q;
                dijkstra_aux t in
      dijkstra_aux
  end

  module ByArray = struct
    module Make (W : sig include Weight val inf : t end) (P : Path) = struct
      module C = Core (W) (P) (struct
        type t = (W.t * P.t) array
        type vertex = int
        let find = Array.get
        let update = Array.set
      end)
      include C

      let dijkstra n e s = C.dijkstra (Array.make n (W.inf, P.nil)) e s

      let dijkstra_dense n es s =
        let d = Array.make n W.inf in
        let r = Array.make n P.nil in
        d.(s) <- W.zero;
        let rec dijkstra_dense_aux = function
          | [] -> ()
          | v :: vs ->
              let u, us = List.fold_left (fun (u, us) v ->
                if W.compare d.(u) d.(v) < 0
                then (u, v :: us)
                else (v, u :: us)) (v, []) vs in
              (es u).fold (fun (v, c, e) () ->
                let open W in
                if 0 < W.compare d.(v) (d.(u) + c) then
                  (d.(v) <- d.(u) + c; r.(v) <- P.snoc r.(u) e)) ();
              dijkstra_dense_aux us in
        dijkstra_dense_aux (List.init n Fun.id);
        fun v -> (d.(v), r.(v))
      end
  end

  module ByHashtbl = struct
    module Make (V : Hashtbl.HashedType) (W : Weight) (P : Path) = struct
      module VHash = Hashtbl.Make (V)
      module C = Core (W) (P) (struct
        type t = (W.t * P.t) VHash.t
        type vertex = V.t
        let find = VHash.find
        let update = VHash.replace
      end)
      include C

      let dijkstra n e s = C.dijkstra (VHash.create n) e s
    end
  end

  module ByMap = struct
    module Make (V : Map.OrderedType) (W : Weight) (P : Path) = struct
      module VMap = Map.Make (V)
      module C = Core (W) (P) (struct
        type t = (W.t * P.t) VMap.t ref
        type vertex = V.t
        let find d v = VMap.find v !d
        let update d v w = d := VMap.add v w !d
      end)
      include C

      let dijkstra e s = C.dijkstra (ref VMap.empty) e s
    end
  end
end

module IntWeightedDirectedGraphByArray = struct
  module Make
    (Path : sig
      type t
      (* 辺の名前 *)
      type edge
      (* 長さ0の道 *)
      val nil : t
      (* 道の後ろに辺を付け足した道 *)
      val snoc : t -> edge -> t
    end)
  = struct
    include (WeightedDirectedGraph.ByArray.Make (struct
      type t = int
      let zero = 0
      let inf = max_int
      let ( + ) = ( + )
      let compare = compare
    end) (Path))

    (* 辺の重さがごく小さい整数の場合は，Mapをキュー代わりに使うより配列を使った方が効率的
       時間計算量はO(E+VW)，空間計算量はO(E+W) *)
    let dijkstra_special :
      (* 頂点数n *)
      int ->
      (* 辺の重さの上限W *)
      int ->
      (* 頂点uを受け取って，
         uから伸びる辺の終点vと重さwの組みのリストを返す関数
         辺の重さwはW以下でなくてはならない *)
      (int -> (int * int * Path.edge) church_list) ->
      (* 始点 *)
      int ->
      (* 始点からの最短距離と，その経路を返す関数
         始点から辿り着けなければ(inf, Path.nil)を返す
         この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
      (int -> int * Path.t)
    = fun n mw es s ->
      (* 各頂点への最短距離を格納するやつ *)
      let d = Array.make n max_int in
      (* 各頂点への最短経路を格納するやつ *)
      let r = Array.make n Path.nil in
      (* キュー *)
      let q = Array.make (mw + 1) [] in
      (* ヒープの最小要素の重み *)
      let w = ref 0 in
      (* ヒープの最小要素がどのインデックスに対応するか *)
      let i = ref 0 in
      (* ヒープに格納されている要素の数 *)
      let m = ref 1 in
      d.(s) <- 0;
      q.(0) <- [s];
      let rec dijkstra_aux t =
        (* 既に終点までの距離が分かっているので返す *)
        if !m <= 0 || d.(t) <= !w then (d.(t), r.(t)) else
        match q.(!i) with
        (* ヒープには重さがwの要素は無かった *)
        | [] ->
            incr w;
            incr i;
            if mw < !i then i := 0;
            dijkstra_aux t
        (* ヒープには重さwの要素uが存在する *)
        | u :: us ->
            (* ヒープから重さwの要素を削除する *)
            decr m;
            q.(!i) <- us;
            if !w <= d.(u) then
              (* 未だ頂点uを訪れていない *)
              (es u).fold (fun (v, c, e) () ->
                if !w + c < d.(v) then begin
                  d.(v) <- !w + c; (* 頂点vの重さを緩和 *)
                  r.(v) <- Path.snoc r.(u) e;
                  (* ヒープにvを追加する *)
                  let j = !i + c - if !i + c <= mw then 0 else mw + 1 in
                  q.(j) <- v :: q.(j);
                  incr m
                end) ();
            dijkstra_aux t in
      dijkstra_aux
  end
end

module Int = struct
  type t = int
  let zero = 0
  let inf = max_int
  let ( + ) = ( + )
  let compare = compare
end

module G = WeightedDirectedGraph.ByMap.Make (Int) (Int)
  (struct
    type t = int
    type edge = int
    let nil = 0
    let snoc _ e = e
  end)

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let es = Array.make n [] in
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- b - 1 :: es.(a - 1);
      es.(b - 1) <- a - 1 :: es.(b - 1);
  done;
  let d = G.dijkstra (fun u -> { G.fold = fun f ->
    List.fold_right (fun v -> f (v, 1, u + 1)) es.(u) }) 0 in
  if
    List.exists (fun v -> try ignore (d v); false with Not_found -> true) @@
    List.init n Fun.id
  then print_endline "No"
  else begin
    print_endline "Yes";
    for i = 1 to n - 1 do
      Printf.printf "%d\n" @@ snd @@ d i
    done
  end


module DirectedGraph
: sig
  (* 配列を用いたBFSの実装 *)
  module ByArray : sig
    module Make :
      functor
        (* 道の表現 *)
        (Path : sig
          type t
          (* 辺の名前 *)
          type edge
          (* 長さ0の道 *)
          val nil : t
          (* 道の後ろに辺を付け足した道 *)
          val snoc : t -> edge -> t
        end) ->
        sig
          type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

          (* BFSにより，重みのないグラフの最短経路を求める *)
          val bfs :
            (* 頂点数n *)
            int ->
            (* 辺の名前が付いた隣接リスト *)
            (int -> (int * Path.edge) church_list) ->
            (* 始点 *)
            int ->
            (* 始点からの最短経路を返す関数
               この関数を覚えておけば，呼び出しごとの途中までの計算結果がシェアされる *)
            (int -> Path.t option)
        end
  end

  (* ハッシュテーブルを用いたBFSの実装 *)
  module ByHashtbl : sig
    module Make :
      functor
        (* 頂点をキーとしたハッシュテーブルの実装 *)
        (VHash : Hashtbl.S)
        (* 道の表現 *)
        (Path : sig
          type t
          (* 辺の名前 *)
          type edge
          (* 長さ0の道 *)
          val nil : t
          (* 道の後ろに辺を付け足した道 *)
          val snoc : t -> edge -> t
        end) ->
        sig
          type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

          (* BFSにより，重みのないグラフの最短経路を求める *)
          val bfs :
            (* 頂点数（ハッシュテーブルを用いるので目安程度） *)
            int ->
            (* 辺の名前が付いた隣接リスト *)
            (VHash.key -> (VHash.key * Path.edge) church_list) ->
            (* 始点 *)
            VHash.key ->
            (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
            (VHash.key -> Path.t option)
        end
  end

  (* Mapを用いたBFSの実装 *)
  module ByMap : sig
    module Make :
      functor
        (* 頂点をキーとしたMapの実装 *)
        (VMap : Map.S)
        (* 道の表現 *)
        (Path : sig
          type t
          (* 辺の名前 *)
          type edge
          (* 長さ0の道 *)
          val nil : t
          (* 道の後ろに辺を付け足した道 *)
          val snoc : t -> edge -> t
        end) ->
        sig
          type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

          (* BFSにより，重みのないグラフの最短経路を求める *)
          val bfs :
            (* 辺の名前が付いた隣接リスト *)
            (VMap.key -> (VMap.key * Path.edge) church_list) ->
            (* 始点 *)
            VMap.key ->
            (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
            (VMap.key -> Path.t option)
        end
  end
end
= struct
  module type Path = sig
    type t
    (* 辺の名前 *)
    type edge
    (* 長さ0の道 *)
    val nil : t
    (* 道の後ろに辺を付け足した道 *)
    val snoc : t -> edge -> t
  end

  (* 最短経路を格納するデータ構造を抽象化したBFSの実装 *)
  module Core
    (P : Path)
    (* グラフの頂点を添字としたハッシュ *)
    (VHash : sig
      type t
      type vertex (* グラフの頂点 *)
      val find_opt : t -> vertex -> P.t option
      val update : t -> vertex -> (P.t option -> P.t option) -> unit
    end)
  = struct
    type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

    let bfs d es s =
      let q = ref [(s, P.nil)] in
      let rec bfs_aux t =
        match VHash.find_opt d t, !q with
        (* もう既に全ての頂点までの経路が分かっている *)
        | None, [] -> None
        (* 既に終点までの経路が分かっているので返す *)
        | Some _ as ans, _ -> ans
        (* 終点までの経路が分かっていないので，BFSを続行 *)
        | None, ((_ :: _) as ups) ->
            q := [];
            List.iter (fun (u, p) ->
              VHash.update d u @@ function
                | (Some _) as op -> op
                | None ->
                    (es u).fold (fun (v, e) () -> q := (v, P.snoc p e) :: !q) ();
                    Some p) ups;
            bfs_aux t in
      bfs_aux
  end

  module ByArray = struct
    module Make (P : Path) = struct
      module C = Core (P) (struct
        type t = P.t option array
        type vertex = int
        let find_opt = Array.get
        let update d v f = d.(v) <- f d.(v)
      end)
      include C

      let bfs n e s = C.bfs (Array.make n None) e s
    end
  end

  module ByHashtbl = struct
    module Make (VHash : Hashtbl.S) (P : Path) = struct
      module C = Core (P) (struct
        type t = P.t VHash.t
        type vertex = VHash.key
        let find_opt = VHash.find_opt
        let update d v f =
          let opt = VHash.find_opt d v in
          match opt, f opt with
          | None, None -> ()
          | None, Some p -> VHash.add d v p
          | Some _, None -> VHash.remove d v
          | Some p, Some p' -> if p != p' then VHash.replace d v p'
      end)
      include C

      let bfs n e s = C.bfs (VHash.create n) e s
    end
  end

  module ByMap = struct
    module Make (VMap : Map.S) (P : Path) = struct
      module C = Core (P) (struct
        type t = P.t VMap.t ref
        type vertex = VMap.key
        let find_opt d v = VMap.find_opt v !d
        let update d v f = d := VMap.update v f !d
      end)
      include C

      let bfs e s = C.bfs (ref VMap.empty) e s
    end
  end
end

module G = DirectedGraph.ByArray.Make
  (struct
    type t = int
    type edge = int
    let nil = 0
    let snoc _ e = e
  end)

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let es = Array.make n [] in
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- (b - 1, a) :: es.(a - 1);
      es.(b - 1) <- (a - 1, b) :: es.(b - 1);
  done;
  let d = G.bfs n (fun v -> { G.fold = fun f -> List.fold_right f es.(v) }) 0 in
  if List.exists Option.is_none @@ List.init n d
  then print_endline "No"
  else begin
    print_endline "Yes";
    for i = 1 to n - 1 do
      Printf.printf "%d\n" @@ Option.get @@ d i
    done
  end


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

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 n = scan "%d" id
let ls = scan_lines n "%d %d" Tuple2.make

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

let () =
  let open ModOp in
  let (ks, ms) = ListL.partition ls ~f:(fun (a,b) -> a = 0 && b = 0) in
  let ms = ListL.map ms ~f:(fun (a, b) ->
      if a = 0 then (0,1)
      else if b = 0 then (1,0)
      else
        let m = gcd (abs a) (abs b) in
        if a < 0 then (-a/m, -b/m)
        else (a/m, b/m)) in
  let h0 = Hashtbl.create n in
  let h1 = Hashtbl.create n in
  ListL.iter ms ~f:(fun (a,b) ->
      if b <= 0 then Hashtbl.modify_def 0 (a,b) succ h0
      else (Hashtbl.modify_def 0 (b,-a) succ h1;
            Hashtbl.modify_def 0 (b,-a) id h0));
  Hashtbl.map (fun v n ->
      let x = Hashtbl.find_default h1 v 0 in
      pow 2 n + pow 2 x - 1) h0
  |> Hashtbl.to_list |> List.map Tuple2.second
  |> ListL.fold_left ~init:1 ~f:( * )
  |> ((+) (List.length ks - 1))
  |> Printf.printf "%d\n"

Score: 500 points

Problem Statement

We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively.

We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time.

The i-th and j-th sardines (i \neq j) are on bad terms if and only if A_i \cdot A_j + B_i \cdot B_j = 0.

In how many ways can we choose the set of sardines to put into the cooler? Since the count can be enormous, print it modulo 1000000007.

Constraints

All values in input are integers.

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

-10^{18} \leq A_i, B_i \leq 10^{18}

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
:
A_N B_N

Output

Print the count modulo 1000000007.

Sample Input 1

3
1 2
-1 1
2 -1

Sample Output 1

5

There are five ways to choose the set of sardines, as follows:

The 1-st

The 1-st and 2-nd

The 2-nd

The 2-nd and 3-rd

The 3-rd

Sample Input 2

10
3 2
3 2
-1 1
2 -1
-3 -9
-8 12
7 7
8 1
8 2
8 4

Sample Output 2

479


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 prime = 1_000_000_007

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

let (+) a b = (a + b) mod prime
let (-) a b = (a + prime - 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)

let () =
  let h = Hashtbl.create n in
  let (ks, ms) = ListL.partition ls ~f:(fun (a,b) -> a = 0 && b = 0) in
  let ms = ListL.map ms ~f:(fun (a, b) ->
      let m = gcd (abs a) (abs b) in (a/m, b/m)) in
  ListL.iter ms ~f:(fun v -> Hashtbl.modify_def 0 v succ h);
  Hashtbl.map (fun (a,b) n ->
      let x = Hashtbl.find_default h (-b,a) 0 in
      let y = Hashtbl.find_default h (b,-a) 0 in
      Hashtbl.remove h (-b,a); Hashtbl.remove h (b,-a);
      pow 2 n - 1 + pow 2 (x+y) - 1 + 1) h
  |> Hashtbl.to_list |> List.map  Tuple2.second
  |> ListL.fold_left ~init:1 ~f:( * )
  |> ((+) (List.length ks - 1))
  |> Printf.printf "%d\n"


module QuotientMap = Map.Make (struct
  type t = int * int
  let compare (a, b) (c, d) =
    compare (a * d) (b * c) * compare (b * d) 0
end)

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

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

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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let abs_ = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> (a * compare b 0 / gcd (abs a) (abs b), abs b / gcd (abs a) (abs b)) in
  let m =
    Array.fold_left (fun acc (a, b) ->
      QuotientMap.update (a, b) (fun o -> Some (1 + Option.value ~default:0 o)) @@
      QuotientMap.update (b * compare 0 a, abs a) (fun o -> Some (Option.value ~default:0 o)) acc) QuotientMap.empty abs_ in
  Printf.printf "%d\n" @@
  Fun.flip ( -^ ) 1 @@
  QuotientMap.fold (fun (a, b) n -> ( *^ ) @@
    if a * compare b 0 < 0
    then 1
    else let n' = QuotientMap.find (b * compare 0 a, abs a) m in (power ( *^ ) 1 2 n +^ power ( *^ ) 1 2 n' -^ 1)) m 1


let id x = x
let s = Scanf.scanf "%s\n" @@ fun s -> s
let t = Scanf.scanf "%s" @@ fun t -> t

let t = String.sub t 0 (String.length t - 1)

let () = print_endline @@ if s = t then "Yes" else "No"

Score : 100 points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID S, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of S as his ID.

He is now trying to register with the ID T. Determine whether this string satisfies the property above.

Constraints

S and T are strings consisting of lowercase English letters.

1 \leq |S| \leq 10

|T| = |S| + 1

Input

Input is given from Standard Input in the following format:

S
T

Output

If T satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

chokudaiz can be obtained by appending z at the end of chokudai.

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes


open Batteries
(* 文字列をcharのlistにする *)
let explode s = List.init (String.length s) (String.get s)
let s = read_line() |> explode
let t = read_line() |> explode
let t2 = List.init (List.length s) @@ fun a -> List.nth s a
let _ = (if s = t2 then "Yes" else "No") |> print_endline


let binom_memo ( *^ ) ( /^ ) n =
  let i = ref 0 in
  let a = Array.make (n / 2 + 1) 1 in
  let rec binom_memo_aux k =
    if k <= !i
    then a.(k)
    else begin
      incr i;
      a.(!i) <- a.(!i - 1) *^ (n - !i + 1) /^ !i;
      binom_memo_aux k
    end in
  fun k -> binom_memo_aux (min k (n - k))

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 = 998244353
let ( +^ ) x y = (x + y) mod m
let ( *^ ) x y = (x * y) mod m
let ( /^ ) x y = power ( *^ ) x y (m - 2)

let () = Scanf.scanf "%d %d %d" @@ fun n m k ->
  let binom = binom_memo ( *^ ) ( /^ ) (n - 1) in
  Printf.printf "%d\n" @@
  List.fold_left ( +^ ) 0 @@
  List.init (k + 1) @@ fun k ->
    power ( *^ ) (m *^ binom k) (m - 1) (n - 1 - k)

Score : 500 points

Problem Statement

There are N blocks arranged in a row. Let us paint these blocks.

We will consider two ways to paint the blocks different if and only if there is a block painted in different colors in those two ways.

Find the number of ways to paint the blocks under the following conditions:

For each block, use one of the M colors, Color 1 through Color M, to paint it. It is not mandatory to use all the colors.

There may be at most K pairs of adjacent blocks that are painted in the same color.

Since the count may be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

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

0 \leq K \leq N - 1

Input

Input is given from Standard Input in the following format:

N M K

Output

Print the answer.

Sample Input 1

3 2 1

Sample Output 1

6

The following ways to paint the blocks satisfy the conditions: 112, 121, 122, 211, 212, and 221. Here, digits represent the colors of the blocks.

Sample Input 2

100 100 0

Sample Output 2

73074801

Sample Input 3

60522 114575 7559

Sample Output 3

479519525


let binom_memo ( * ) ( / ) n =
  let i = ref 0 in
  let a = Array.make (n + 1) 1 in
  let rec binom_memo_aux k =
    if k <= !i
    then a.(k)
    else begin
      incr i;
      a.(!i) <- a.(!i - 1) * (n - !i + 1) / !i;
      binom_memo_aux k
    end in
  binom_memo_aux

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 = 998244353
let ( +^ ) x y = (x + y) mod m
let ( *^ ) x y = (x * y) mod m
let ( /^ ) x y = power ( *^ ) x y (m - 2)

let () = Scanf.scanf "%d %d %d" @@ fun n m k ->
  let binom = binom_memo ( *^ ) ( /^ ) (n - 1) in
  Printf.printf "%d\n" @@
  List.fold_left ( +^ ) 0 @@
  List.init (k + 1) @@ fun k ->
    power ( *^ ) (m *^ binom k) (m - 1) (n - 1 - k)