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 =
      VHash.update d s (Fun.const (Some P.nil));
      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, ups ->
            q := [];
            List.iter (fun (u, p) ->
              Fun.flip (es u).fold () @@ fun (v, e) () ->
                VHash.update d u @@ function
                  | (Some _) as op -> op
                  | None ->
                      let p' = P.snoc p e in
                      q := (v, p') :: !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

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

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

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

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

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.


Scanf.scanf "%d" (fun n ->
    let rec gcd a b = if b = 0 then a else gcd b (a mod b) in
    let agcd a b = gcd (abs a) (abs b) in

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

    let rec loop i map a0 b0 c0 d0 e0 =
        if i = n then map, a0, b0, c0, d0, e0 else
            let a, b = Scanf.scanf " %d %d" (fun a b -> a, b) in
            if a = 0 && b = 0 then loop (i + 1) map a0 b0 (c0 + 1) d0 e0 else
            if a = 0 then loop (i + 1) map (a0 + 1) b0 c0 d0 e0 else
            if b = 0 then loop (i + 1) map a0 (b0 + 1) c0 d0 e0 else
            if a = b then loop (i + 1) map a0 b0 c0 (d0 + 1) e0 else
            if a = -b then loop (i + 1) map a0 b0 c0 d0 (e0 + 1) else
            let g = agcd a b in
            let a = a / g in
            let b = b / g in
            let flag = if a < 0 && b < 0 || a > 0 && b > 0 then 2 else 0 in
            let flag = if abs a < abs b then flag + 1 else flag in
            let key = if abs a < abs b then abs a, abs b else abs b, abs a in
            let (ca, cb, cc, cd) = try M.find key map with _ -> 0, 0, 0, 0 in
            let abcd = if flag = 0 then ca + 1, cb, cc, cd else
                       if flag = 1 then ca, cb + 1, cc, cd else
                       if flag = 2 then ca, cb, cc + 1, cd else
                                        ca, cb, cc, cd + 1
            in
            let map = M.add key abcd map in
            loop (i + 1) map a0 b0 c0 d0 e0
    in
    let map, a0, b0, c0, d0, e0 = loop 0 M.empty 0 0 0 0 0 in
    let m = 1_000_000_007 in
    let ( +@) a b = (a + b) mod m in
    let ( -@) a b = (((a - b) mod m) + m) mod m in
    let ( *@) a b = (a * b) mod m in

    let powmod a b =
        let rec loop r i acc =
            if i = 0 then acc else
                loop (r *@ r) (i lsr 1) (if i land 1 = 1 then r *@ acc else acc)
        in
        loop a b 1
    in

    let ans1 =
        M.fold (fun (k1, k2) (ca, cb, cc, cd) acc ->
            (powmod 2 ca +@ powmod 2 cd -@ 1) *@ (powmod 2 cb +@ powmod 2 cc -@ 1) *@ acc
        ) map 1
    in
    let ans2 = ans1 *@ (powmod 2 d0 +@ powmod 2 e0 -@ 1) in
    let ans3 = ans2 *@ (powmod 2 a0 +@ powmod 2 b0 -@ 1) in
    if c0 = 1 && n = 1 then Printf.printf "%d\n" 1
                       else Printf.printf "%d\n" (ans3 -@ 1)
)


let () =
  let s = read_line () in
  let t = read_line () in
  print_endline @@
    if
      List.for_all (fun i -> s.[i] = t.[i]) @@
      List.init (String.length s) Fun.id
    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


let () = Scanf.scanf "%d\n" @@ fun n ->
  let ss =
    Array.init n @@ fun _ ->
      Scanf.scanf "%s\n" @@ fun s ->
        Array.fold_left (fun (m, c) -> function
          | '(' -> (m, c + 1)
          | ')' -> (min m (c - 1), c - 1)) (0, 0) @@
        Array.init (String.length s) (String.get s) in
  print_endline @@
  if
    ( <> ) 0 @@
    Array.fold_right (fun (_, c) -> ( + ) c) ss 0
  then "No"
  else begin
    Array.sort (fun (m, c) (m', c') -> compare (m' + c', c') (m + c, c)) ss;
    try
      ignore
      (Array.fold_left (fun x (m, c) ->
        if x + m < 0 then raise Not_found; x + c) 0 ss);
      "Yes"
    with Not_found -> "No"
  end


open Scanf
open Printf

let easy_linear a b c k =
  if k <= a then k
  else if k <= a + b then a
  else if k <= a + b + c then a - (k - (a + b))
  else a - c

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

Score : 200 points

Problem Statement

We have A cards, each of which has an integer 1 written on it. Similarly, we also have B cards with 0s and C cards with -1s.

We will pick up K among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

0 \leq A, B, C

1 \leq K \leq A + B + C \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with 1s and one card with a 0.
In this case, the sum of the numbers written on the cards is 2, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000


open Batteries
open Printf
open Scanf

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

module MyList = struct
  include List
  let foldl = fold_left
  let foldr = fold_right

  let flatmap f ls = concat @@ map f ls

  let zipf = map2
  let zipfi = map2i
end

module L = MyList

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

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

module MyString = struct
  include String

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

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

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

module S = MyString

let tup2 a b = (a, b)
let tup3 a b c = (a, b, c)
let tup4 a b c d = (a, b, c, d)

let rds () = read_line ()
let rds2 () = scanf "%s %s\n" tup2

let rdi () = atoi @@ rds ()
let rdi2 () = scanf "%d %d\n" tup2
let rdi3 () = scanf "%d %d %d\n" tup3
let rdi4 () = scanf "%d %d %d %d\n" tup4

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

let rdvs n rdf = L.init n (fun _ -> rdf ())

let rdvi n = rdvs n rdi
let rdvi2 n = rdvs n rdi2
let rdvi3 n = rdvs n rdi3
let rdvi4 n = rdvs 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 _ =
  let (a,b,c,k) = rdi4 () in
  let r =
    if k <= a + b then (min a k)
    else a - (k - (a + b))
  in puti r;;


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

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

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

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

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

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

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

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

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

let 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,x) = scan "%d %d %d" Tuple3.make
let mat = scan_matrix n m ~sep:' ' 0 Int.of_string

let () =
  ListL.map (powerset (0++^n)) ~f:(fun ls ->
      let arr = Array.make m 0 in
      let w = ref 0 in
      ListL.iter ls ~f:(fun i ->
          w := !w + mat.(i).(0);
          ArrayL.iteri (Array.sub mat.(i) 1 m) ~f:(fun i v -> arr.(i) <- arr.(i) + v));
      if ArrayL.for_all arr ~f:((<=) x) then !w
      else Int.max_num)
  |> List.min
  |> (fun v -> if v = Int.max_num then -1 else v)
  |> Printf.printf "%d\n"

Score : 300 points

Problem

Takahashi, who is a novice in competitive programming, wants to learn M algorithms.
Initially, his understanding level of each of the M algorithms is 0.

Takahashi is visiting a bookstore, where he finds N books on algorithms.
The i-th book (1\leq i\leq N) is sold for C_i yen (the currency of Japan). If he buys and reads it, his understanding level of the j-th algorithm will increase by A_{i,j} for each j (1\leq j\leq M).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the M algorithms X or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

1\leq N, M\leq 12

1\leq X\leq 10^5

1\leq C_i \leq 10^5

0\leq A_{i, j} \leq 10^5

Input

Input is given from Standard Input in the following format:

N M X
C_1 A_{1,1} A_{1,2} \cdots A_{1,M}
C_2 A_{2,1} A_{2,2} \cdots A_{2,M}
\vdots
C_N A_{N,1} A_{N,2} \cdots A_{N,M}

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms 10 or higher, at the minimum cost possible.

Sample Input 2

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

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms 10 or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067


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

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

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

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

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

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

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

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

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

let 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,x) = scan "%d %d %d" Tuple3.make
let mat = scan_matrix n m ~sep:' ' 0 Int.of_string

let () =
  ListL.map (permutations (0++n)) ~f:(fun ls ->
      let arr = Array.make m 0 in
      let v = ref 0 in
      ListL.iter ls ~f:(fun i ->
          v := !v + mat.(i).(0);
          ArrayL.iteri (Array.sub mat.(i) 1 (m-1)) ~f:(fun i v ->
              arr.(i) <- arr.(i) + v
            )
        );
      if ArrayL.for_all arr ~f:(fun v -> v >= x) then !v
      else Int.max_num
    )
  |> List.min
  |> (fun v -> if v = Int.max_num then -1 else v)
  |> Printf.printf "%d\n"


let parse s =
  Array.init (String.length s) (fun i -> s.[i])
  |> Array.fold_left (fun (p, b) c ->
      if c = '(' then (p+1, b) else (p-1, min b (p-1))) (0, 0)

let () =
  Scanf.scanf "%d" @@ fun n ->
  let s = Array.init n (fun _ -> Scanf.scanf " %s" parse) in
  Array.sort (fun (a, b) (c, d) -> d - b) s;
  let tp, tb =
    Array.fold_left (fun (tp, tb) (p, b) ->
      (tp + p, min tb (tp + b))) (0, 0) s in

  Printf.printf "%d %d\n" tp tb;
  let ans = if tp = 0 && tb >= 0 then "Yes" else "No" in
  print_endline ans

Score : 600 points

Problem Statement

A bracket sequence is a string that is one of the following:

An empty string;

The concatenation of (, A, and ) in this order, for some bracket sequence A ;

The concatenation of A and B in this order, for some non-empty bracket sequences A and B /

Given are N strings S_i. Can a bracket sequence be formed by concatenating all the N strings in some order?

Constraints

1 \leq N \leq 10^6

The total length of the strings S_i is at most 10^6.

S_i is a non-empty string consisting of ( and ).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

If a bracket sequence can be formed by concatenating all the N strings in some order, print Yes; otherwise, print No.

Sample Input 1

2
)
(()

Sample Output 1

Yes

Concatenating (() and ) in this order forms a bracket sequence.

Sample Input 2

2
)(
()

Sample Output 2

No

Sample Input 3

4
((()))
((((((
))))))
()()()

Sample Output 3

Yes

Sample Input 4

3
(((
)
)

Sample Output 4

No


let s = read_line ()
let () = print_endline @@ if s.[1] = 'B' then "ARC" else "ABC"

Score : 100 points

Problem Statement

AtCoder Inc. holds a contest every Saturday.

There are two types of contests called ABC and ARC, and just one of them is held at a time.

The company holds these two types of contests alternately: an ARC follows an ABC and vice versa.

Given a string S representing the type of the contest held last week, print the string representing the type of the contest held this week.

Constraints

S is ABC or ARC.

Input

Input is given from Standard Input in the following format:

S

Output

Print the string representing the type of the contest held this week.

Sample Input 1

ABC

Sample Output 1

ARC

They held an ABC last week, so they will hold an ARC this week.


Scanf.scanf "%d %d" (fun n k ->
    let snuke = Array.make n false in
    for i = 1 to k do
        Scanf.scanf " %d" (fun d ->
            for j = 1 to d do
                Scanf.scanf " %d" (fun a -> snuke.(a - 1) <- true)
            done
        )
    done;
    Array.fold_left (fun acc v -> if v then acc else acc + 1) 0 snuke |> Printf.printf "%d\n"
)

Score : 200 points

Problem Statement

N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.

There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq K \leq 100

1 \leq d_i \leq N

1 \leq A_{i, 1} < \cdots < A_{i, d_i} \leq N

Input

Input is given from Standard Input in the following format:

N K
d_1
A_{1, 1} \cdots A_{1, d_1}
\vdots
d_K
A_{K, 1} \cdots A_{K, d_K}

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke 1 has Snack 1.

Snuke 2 has no snacks.

Snuke 3 has Snack 1 and 2.

Thus, there will be one victim: Snuke 2.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2


let () =
  let rec make_list n = if n = 0 then [0] else n :: make_list (n-1) in
  let n,m = Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
  let h = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  let arr = Array.make n 0 in
  for i = 1 to m do
    Scanf.scanf "%d %d\n" @@ fun x y ->
    let a = x-1 in let b = y-1 in
    arr.(a) <- (max h.(b) arr.(a)); arr.(b) <- (max h.(a) arr.(b))
  done;
  print_int (List.fold_left (fun i v -> if h.(v) > arr.(v) then i+1 else i) 0 (make_list (n-1)))

Score : 300 points

Problem Statement

There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i.
There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j.

Obs. i is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. i using just one road.
Note that Obs. i is also good when no observatory can be reached from Obs. i using just one road.

How many good observatories are there?

Constraints

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq H_i \leq 10^9

1 \leq A_i,B_i \leq N

A_i \neq B_i

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
H_1 H_2 ... H_N
A_1 B_1
A_2 B_2
:
A_M B_M

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. 1, you can reach Obs. 3 using just one road. The elevation of Obs. 1 is not higher than that of Obs. 3, so Obs. 1 is not good.

From Obs. 2, you can reach Obs. 3 and 4 using just one road. The elevation of Obs. 2 is not higher than that of Obs. 3, so Obs. 2 is not good.

From Obs. 3, you can reach Obs. 1 and 2 using just one road. The elevation of Obs. 3 is higher than those of Obs. 1 and 2, so Obs. 3 is good.

From Obs. 4, you can reach Obs. 2 using just one road. The elevation of Obs. 4 is higher than that of Obs. 2, so Obs. 4 is good.

Thus, the good observatories are Obs. 3 and 4, so there are two good observatories.

Sample Input 2

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

Sample Output 2

3


open Batteries
let x = read_int ()

let rec loop a =
  let rec loop2 b =
    if b >= 100 then (0, 0) else
    if ((a * a * a * a * a) - (b*b*b*b*b)) = x then (a, b) else loop2 (b+1)
  in if a >= 100 then (0, 0) else (
  let a_, b_ = loop2 (-100) in
  if a_ = 0 && b_ = 0 then loop (a+1) else (a_, b_)
)
let a, b = loop (-100)
let _ = Printf.printf "%d %d\n" a b

Score : 400 points

Problem Statement

Give a pair of integers (A, B) such that A^5-B^5 = X.
It is guaranteed that there exists such a pair for the given integer X.

Constraints

1 \leq X \leq 10^9

X is an integer.

There exists a pair of integers (A, B) satisfying the condition in Problem Statement.

Input

Input is given from Standard Input in the following format:

X

Output

Print A and B, with space in between.
If there are multiple pairs of integers (A, B) satisfying the condition, you may print any of them.

A B

Sample Input 1

33

Sample Output 1

2 -1

For A=2 and B=-1, A^5-B^5 = 33.

Sample Input 2

1

Sample Output 2

0 -1


Scanf.scanf "%d" (fun x ->
    let check x i =
        let rec loop c =
            if c < -1000 then None else
                if c * c * c * c * c - (c - i) * (c - i) * (c - i) * (c - i) * (c - i) = x then Some (c, c - i)
                else loop (c - 1)
        in
        loop 1000
    in
    let rec loop i =
        if x mod i = 0 then (
            match check x i with
            | Some (a, b) -> Printf.printf "%d %d\n" a b
            | None -> loop (i + 1)
        ) else loop (i + 1)
    in
    loop 1
)


open Batteries
open Tuple
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 `To (pred m) else []

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

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

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

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

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

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

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

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

let 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,a,b,c) = scan "%d %d %d %d" Tuple4.make
let coms = scan_lines n "%s" id

open Option.Infix
open Option.Monad

let rec solve1 a b c= function
  | [] -> Some []
  | com::rest ->
    match com with
    | "AB" ->
      if a = 0 && b = 0 then None
      else if a = 1 then
        solve1 (pred a) (succ b) c rest >>= fun ret ->
        return ("B" :: ret)
      else
        solve1 (succ a) (pred b) c rest >>= fun ret ->
        return ("A" :: ret)
    | "BC" ->
      if b = 0 && c = 0 then None
      else if b = 1 then
        solve1 a (pred b) (succ c) rest >>= fun ret ->
        return ("C" :: ret)
      else
        solve1 a (succ b) (pred c) rest >>= fun ret ->
        return ("B" :: ret)
    | "AC" ->
      if a = 0 && c = 0 then None
      else if c = 1 then
        solve1 (succ a) b (pred c) rest >>= fun ret ->
        return ("A" :: ret)
      else solve1 (pred a) b (succ c) rest >>= fun ret ->
        return ("C" :: ret)
    | _ ->  None

let rec solven a b c = function
  | [] -> Some []
  | com :: rest ->
    begin
      match com with
      | "AB" ->
        if a > b then
          solven (pred a) (succ b) c rest >>= fun ret ->
          return ("B"::ret)
        else
          solven (succ a) (pred b) c rest >>= fun ret ->
          return ("A"::ret)
      | "BC" ->
        if b > c then
          solven a (pred b) (succ c) rest >>= fun ret ->
          return ("C"::ret)
        else
          solven a (succ b) (pred c) rest >>= fun ret ->
          return ("B"::ret)
      | "AC" ->
        if a > c then
          solven (pred a) (pred b) (succ c) rest >>= fun ret ->
          return ("C"::ret)
        else
          solven (succ a) b (pred c) rest >>= fun ret ->
          return ("A"::ret)
      | _ -> None
    end

let rec solve2 a b c = function
  | [] -> Some []
  | com :: rest ->
    begin
      match com with
      | "AB" ->
        if a = 1 && b = 1 && List.at_opt rest 0 |> Option.is_some then
          let next = List.at rest 0 in
          match next with
          | "AC" -> solve2 (succ a) (pred b) c rest >>= fun ret ->
            return ("A"::ret)
          | "BC" -> solve2 (pred a) (succ b) c rest >>= fun ret ->
            return ("B"::ret)
          | "AB" -> solve2 (pred a) (succ b) c rest >>= fun ret ->
            return ("B"::ret)
          | _ -> None
        else if a = 0 then
          solve2 (succ a) (pred b) c rest >>= fun ret ->
          return ("A" :: ret)
        else
          solve2 (pred a) (succ b) c rest >>= fun ret ->
          return ("B" :: ret)
      | "BC" ->
        if b = 1 && c= 1 && List.at_opt rest 0 |> Option.is_some then
          let next = List.at rest 0 in
          match next with
          | "AB" -> solve2 a (succ b) (pred c) rest >>= fun ret ->
            return ("B" :: ret)
          | "BC" -> solve2 a (pred b) (succ c) rest >>= fun ret ->
            return ("C"::ret)
          | "AC" -> solve2 a (pred b) (succ c) rest >>= fun ret ->
            return ("C"::ret)
          | _ -> None
        else if b = 0 then
          solve2 a (succ b) (pred c) rest >>= fun ret ->
          return ("B" :: ret)
        else
          solve2 a (pred b) (succ c) rest >>= fun ret ->
          return ("C" :: ret)
      | "AC" ->
        if c = 1 && a = 1 && List.at_opt rest 0 |> Option.is_some then
          let next = List.at rest 0 in
          match next with
          | "AB" -> solve2 (succ a) b (pred c) rest >>= fun ret ->
            return ("A" :: ret)
          | "BC" -> solve2 (pred a) b (succ c) rest >>= fun ret ->
            return ("C"::ret)
          | "AC" -> solve2 (succ a) b (pred c) rest >>= fun ret ->
            return ("A"::ret)
          | _ -> None
        else if c = 0 then
          solve2 (pred a) b (succ c) rest >>= fun ret ->
          return ("C" :: ret)
        else
          solve2 (succ a) b (pred c) rest >>= fun ret ->
          return ("A" :: ret)
      | _ -> None
    end

let () =
  (match List.first coms with
   | "AB" when a = 0 && b = 0 -> None
   | "BC" when b = 0 && c = 0 -> None
   | "AC" when a = 0 && c = 0 -> None
   | _ ->
     if a + b + c = 1 then
       solve1 a b c coms
     else if a + b + c = 2 then
       solve2 a b c coms
     else
       solven a b c coms)
  |> Option.map_default (fun ans -> "Yes\n" ^ String.join "\n" ans) "No"
  |> Printf.printf "%s\n"

Score : 600 points

Problem Statement

There is a game that involves three variables, denoted A, B, and C.

As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other.

After each choice, none of A, B, and C should be negative.

Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices.

Constraints

1 \leq N \leq 10^5

0 \leq A,B,C \leq 10^9

N, A, B, C are integers.

s_i is AB, AC, or BC.

Input

Input is given from Standard Input in the following format:

N A B C
s_1
s_2
:
s_N

Output

If it is possible to make N choices under the condition, print Yes; otherwise, print No.

Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice.

Sample Input 1

2 1 3 0
AB
AC

Sample Output 1

Yes
A
C

You can successfully make two choices, as follows:

In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2.

In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.

Sample Input 2

3 1 0 0
AB
BC
AB

Sample Output 2

No

Sample Input 3

1 0 9 0
AC

Sample Output 3

No

Sample Input 4

8 6 9 1
AC
BC
AB
BC
AC
BC
AB
AB

Sample Output 4

Yes
C
B
B
C
C
B
A
A


open Batteries
open Tuple
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 `To (pred m) else []

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

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

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

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

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

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

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

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

let 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,a,b,c) = scan "%d %d %d %d" Tuple4.make
let coms = scan_lines n "%s" id

open Option.Infix
open Option.Monad

let rec solve1 a b c= function
  | [] -> Some []
  | com::rest ->
    match com with
    | "AB" ->
      if a = 0 && b = 0 then None
      else if a = 1 then
        solve1 (pred a) (succ b) c rest >>= fun ret ->
        return ("B" :: ret)
      else
        solve1 (succ a) (pred b) c rest >>= fun ret ->
        return ("A" :: ret)
    | "BC" ->
      if b = 0 && c = 0 then None
      else if b = 1 then
        solve1 a (pred b) (succ c) rest >>= fun ret ->
        return ("C" :: ret)
      else
        solve1 a (succ b) (pred c) rest >>= fun ret ->
        return ("B" :: ret)
    | "AC" ->
      if a = 0 && c = 0 then None
      else if c = 1 then
        solve1 (succ a) b (pred c) rest >>= fun ret ->
        return ("A" :: ret)
      else solve1 (pred a) b (succ c) rest >>= fun ret ->
        return ("C" :: ret)
    | _ ->  None

let rec solven a b c = function
  | [] -> Some []
  | com :: rest ->
    begin
      match com with
      | "AB" ->
        if a = 0 then
          solven (succ a) (pred b) c rest >>= fun ret ->
          return ("A" :: ret)
        else if a = 1 && b = 1 && List.at_opt rest 0 |> Option.is_some then
          let next = List.at rest 0 in
          match next with
          | "AC" -> solven (succ a) (pred b) c rest >>= fun ret ->
            return ("A"::ret)
          | "BC" -> solven (pred a) (succ b) c rest >>= fun ret ->
            return ("B"::ret)
          | "AB" -> solven (pred a) (succ b) c rest >>= fun ret ->
            return ("B"::ret)
          | _ -> None
        else
          solven (pred a) (succ b) c rest >>= fun ret ->
          return ("B" :: ret)
      | "BC" ->
        if b = 0 then
          solven a (succ b) (pred c) rest >>= fun ret ->
          return ("B" :: ret)
        else if b = 1 && c= 1 && List.at_opt rest 0 |> Option.is_some then
          let next = List.at rest 0 in
          match next with
          | "AB" -> solven a (succ b) (pred c) rest >>= fun ret ->
            return ("B" :: ret)
          | "BC" -> solven a (pred b) (succ c) rest >>= fun ret ->
            return ("C"::ret)
          | "AC" -> solven a (pred b) (succ c) rest >>= fun ret ->
            return ("C"::ret)
          | _ -> None
        else
          solven a (pred b) (succ c) rest >>= fun ret ->
          return ("C" :: ret)
      | "AC" ->
        if c = 0 then
          solven (pred a) b (succ c) rest >>= fun ret ->
          return ("C" :: ret)
        else if c = 1 && a = 1 && List.at_opt rest 0 |> Option.is_some then
          let next = List.at rest 0 in
          match next with
          | "AB" -> solven (succ a) b (pred c) rest >>= fun ret ->
            return ("A" :: ret)
          | "BC" -> solven (pred a) b (succ c) rest >>= fun ret ->
            return ("C"::ret)
          | "AC" -> solven (succ a) b (pred c) rest >>= fun ret ->
            return ("A"::ret)
          | _ -> None
        else
          solven (succ a) b (pred c) rest >>= fun ret ->
          return ("A" :: ret)
      | _ -> None
    end

let () =
  (if a + b + c = 0 then None
   else if a + b + c = 1 then
     solve1 a b c coms
   else
     match List.first coms with
     | "AB" when a = 0 && b = 0 -> None
     | "BC" when b = 0 && c = 0 -> None
     | "AC" when a = 0 && c = 0 -> None
     | _ ->
       solven a b c coms)
  |> Option.map_default (fun ans -> "Yes\n" ^ String.join "\n" ans) "No"
  |> Printf.printf "%s\n"


open Batteries

let len = Scanf.scanf "%d\n" (
        fun k ->
                Scanf.scanf "%d %d" (
                        fun a b ->
                                List.range a `To b
                                |> List.filter (fun x -> x mod k = 0)
                )
) |> List.length

let () = Printf.printf "%s\n" (if len = 0 then
                                       "NG"
                               else
                                       "OK"
                              )

Score: 100 points

Problem Statement

Takahashi the Jumbo will practice golf.

His objective is to get a carry distance that is a multiple of K, while he can only make a carry distance of between A and B (inclusive).

If he can achieve the objective, print OK; if he cannot, print NG.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 1000

1 \leq K \leq 1000

Input

Input is given from Standard Input in the following format:

K
A B

Output

If he can achieve the objective, print OK; if he cannot, print NG.

Sample Input 1

7
500 600

Sample Output 1

OK

Among the multiples of 7, for example, 567 lies between 500 and 600.

Sample Input 2

4
5 7

Sample Output 2

NG

No multiple of 4 lies between 5 and 7.

Sample Input 3

1
11 11

Sample Output 3

OK


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 `To (pred m) else []

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

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

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

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

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

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

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

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

let 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 x = scan "%d" id

exception Found of int

let () =
  try
    ListL.fold_left ~init:100
      ~f:(fun acc i  ->
          let w = Int.of_float @@ 1.01 *. Float.of_int acc in
          if w >= x then raise @@ Found i
          else w) (1++4000) |> ignore
  with
  | Found i -> Printf.printf "%d\n" i

Score : 200 points

Problem Statement

Takahashi has a deposit of 100 yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of 1 % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach X yen or above for the first time?

Constraints

101 \le X \le 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X

Output

Print the number of years it takes for Takahashi's balance to reach X yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is 101 yen.

The balance after two years is 102 yen.

The balance after three years is 103 yen.

Thus, it takes three years for the balance to reach 103 yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706


let main x =
  let rec loop i y =
    if x <= y then
      print_int i
    else
      loop (i + 1) (int_of_float (float_of_int (y) *. 0.01))
  in
  loop 0 100;;

Scanf.sscanf (read_line ()) "%d" (fun x ->
    main x
);;


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

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

let id = identity

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

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

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

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

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

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

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

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

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

let 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 inc_seq len m =
  let rec aux rest n =
    if rest = 0 then [[]]
    else if n = succ m then []
    else
      (ListL.map ~f:(fun l -> n::l) @@ aux (pred rest) n)
      @ aux rest (succ n)
  in
  aux len 1

let (n,m,q) = scan "%d %d %d"  Tuple3.make
let qs = scan_lines q "%d %d %d %d" Tuple4.make

let () =
  inc_seq n m
  |> ListL.map ~f:Array.of_list
  (* |> (fun l -> List.print ~sep:"\n" (Array.print Int.print) stderr l; l) *)
  |> ListL.map ~f:(fun l ->
      ListL.map ~f:(fun (a,b,c,d) ->
          if l.(pred b) - l.(pred a) = c then d else 0)
        qs |> List.sum)
  |> List.max
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).

Consider a sequence A satisfying the following conditions:

A is a sequence of N positive integers.

1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.

Let us define a score of this sequence as follows:

The score is the sum of d_i over all indices i such that A_{b_i} - A_{a_i} = c_i. (If there is no such i, the score is 0.)

Find the maximum possible score of A.

Constraints

All values in input are integers.

2 ≤ N ≤ 10

1 \leq M \leq 10

1 \leq Q \leq 50

1 \leq a_i < b_i \leq N ( i = 1, 2, ..., Q )

0 \leq c_i \leq M - 1 ( i = 1, 2, ..., Q )

(a_i, b_i, c_i) \neq (a_j, b_j, c_j) (where i \neq j)

1 \leq d_i \leq 10^5 ( i = 1, 2, ..., Q )

Input

Input is given from Standard Input in the following format:

N M Q
a_1 b_1 c_1 d_1
:
a_Q b_Q c_Q d_Q

Output

Print the maximum possible score of A.

Sample Input 1

3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

Sample Output 1

110

When A = \{1, 3, 4\}, its score is 110. Under these conditions, no sequence has a score greater than 110, so the answer is 110.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1


open Batteries
(* 重複順列 *)
let rec dup_perm n lst =
  if n = 0 then [[]]
  else flatmap (fun x -> List.map (fun y -> x :: y)
                                  (dup_perm (n - 1) lst))
               lst
and flatten = function
  [] -> []
| x::xs -> x @ (flatten xs)
and flatmap func ls = flatten (List.map func ls)

let n, m, q = Scanf.sscanf (read_line()) "%d %d %d" (fun n m q ->
  n, m, q
)
let abcd = List.init q @@ fun a ->Scanf.sscanf (read_line()) "%d %d %d %d" (fun a b c d ->
  (a,b,c,d)
)

let a_list = dup_perm n @@ List.init m @@ fun b -> b+1

let rec check target lst ans =
  match lst with
  | [] -> ans
  | first :: rest ->
    let a,b,c,d = first in
    if target.(b-1) - target.(a-1) = c then check target rest (d+ans) else check target rest ans

let rec loop lst ans =
  match lst with
  | [] -> ans
  | first :: rest -> (
    let target = List.sort compare first |> Array.of_list in
    let r = check target abcd 0 in if r > ans then loop rest r else loop rest ans
  )

let _ = Printf.printf "%d\n" @@ loop a_list 0


let () = Scanf.scanf "%d %d %d" @@ fun a b n ->
    let x = min (b-1) n in
    Printf.printf "%d" @@ (a*x)/b - a * (x/b)

Score : 400 points

Problem Statement

Given are integers A, B, and N.

Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.

Here floor(t) denotes the greatest integer not greater than the real number t.

Constraints

1 ≤ A ≤ 10^{6}

1 ≤ B ≤ 10^{12}

1 ≤ N ≤ 10^{12}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B N

Output

Print the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N, as an integer.

Sample Input 1

5 7 4

Sample Output 1

2

When x=3, floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2. This is the maximum value possible.

Sample Input 2

11 10 9

Sample Output 2

9


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

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

let id = identity

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

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

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

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

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

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

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

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

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

let 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 () =
  (if n mod 2 = 1 then
     ListL.map (1++(n/2)) ~f:(fun i -> (i, n-i))
   else
     (1,2)::(ListL.map (List.combine (3++(n/2+1))
                          (n-1 ++- (n/2+1)))
               ~f:(fun (i,j) -> (i, j))))
  |> List.take m
  |> ListL.iter ~f:(fun (i,j) -> Printf.printf "%d %d\n" i j)

Score : 500 points

Problem Statement

You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.)
N players will participate in this competition, and they are given distinct integers from 1 through N.
The arena has M playing fields for two players. You need to assign each playing field two distinct integers between 1 and N (inclusive).
You cannot assign the same integer to multiple playing fields.
The competition consists of N rounds, each of which proceeds as follows:

For each player, if there is a playing field that is assigned the player's integer, the player goes to that field and fight the other player who comes there.

Then, each player adds 1 to its integer. If it becomes N+1, change it to 1.

You want to ensure that no player fights the same opponent more than once during the N rounds.
Print an assignment of integers to the playing fields satisfying this condition.
It can be proved that such an assignment always exists under the constraints given.

Constraints

1 \leq M

M \times 2 +1 \leq N \leq 200000

Input

Input is given from Standard Input in the following format:

N M

Output

Print M lines in the format below.
The i-th line should contain the two integers a_i and b_i assigned to the i-th playing field.

a_1 b_1
a_2 b_2
:
a_M b_M

Sample Input 1

4 1

Sample Output 1

2 3

Let us call the four players A, B, C, and D, and assume that they are initially given the integers 1, 2, 3, and 4, respectively.

The 1-st round is fought by B and C, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 2, 3, 4, and 1, respectively.

The 2-nd round is fought by A and B, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 3, 4, 1, and 2, respectively.

The 3-rd round is fought by D and A, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 4, 1, 2, and 3, respectively.

The 4-th round is fought by C and D, who has the integers 2 and 3, respectively. After this round, A, B, C, and D have the integers 1, 2, 3, and 4, respectively.

No player fights the same opponent more than once during the four rounds, so this solution will be accepted.

Sample Input 2

7 3

Sample Output 2

1 6
2 5
3 4


Scanf.scanf "%d %d" (fun n m ->
    if n mod 2 = 1 then (
        for i = 1 to m do
            Printf.printf "%d %d\n" i (n - i)
        done
    ) else (
        let m1 = (m + 1) / 2 in
        let m2 = m - m1 in
        for i = 1 to m1 do
            Printf.printf "%d %d\n" i (m1 * 2 + 1 - i)
        done;
        for i = 1 to m2 do
            Printf.printf "%d %d\n" (m1 * 2 + 1 + i) (m1 * 2 + 1 + m2 * 2 + 2 - i)
        done
    )
)


let s, w = Scanf.sscanf (read_line ()) "%d %d" @@ fun s w -> (s, w)
let () = print_endline @@ if s > w then "safe" else "unsafe"

Score : 100 points

Problem Statement

There are S sheep and W wolves.

If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Constraints

1 \leq S \leq 100

1 \leq W \leq 100

Input

Input is given from Standard Input in the following format:

S W

Output

If the wolves will attack the sheep, print unsafe; otherwise, print safe.

Sample Input 1

4 5

Sample Output 1

unsafe

There are four sheep and five wolves. The number of wolves is not less than that of sheep, so they will attack them.

Sample Input 2

100 2

Sample Output 2

safe

Many a sheep drive away two wolves.

Sample Input 3

10 10

Sample Output 3

unsafe


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

module SSet = Set.Make(struct type t = string let compare = compare end)

let () = Printf.printf "%d\n"
  @@ SSet.cardinal
  @@ Array.fold_left (fun set s -> SSet.add s set ) SSet.empty s

Score : 300 points

Problem Statement

You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.

How many kinds of items did you get?

Constraints

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

S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N
S_1
:
S_N

Output

Print the number of kinds of items you got.

Sample Input 1

3
apple
orange
apple

Sample Output 1

2

You got two kinds of items: apple and orange.

Sample Input 2

5
grape
grape
grape
grape
grape

Sample Output 2

1

Sample Input 3

4
aaaa
a
aaa
aa

Sample Output 3

4


module SS = Set.Make(String);;
let () =
  let n = read_int () in
  let s = Array.to_list (Array.init n @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s) in
  let ans = List.fold_right SS.add s (SS.empty) in
  print_int (SS.cardinal ans)


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

Score : 200 points

Problem Statement

Takahashi has N days of summer vacation.

His teacher gave him M summer assignments. It will take A_i days for him to do the i-th assignment.

He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.

What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?

If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

Constraints

1 \leq N \leq 10^6

1 \leq M \leq 10^4

1 \leq A_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 ... A_M

Output

Print the maximum number of days Takahashi can hang out during the vacation, or -1.

Sample Input 1

41 2
5 6

Sample Output 1

30

For example, he can do the first assignment on the first 5 days, hang out on the next 30 days, and do the second assignment on the last 6 days of the vacation. In this way, he can safely spend 30 days hanging out.

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

He can finish his assignments, but he will have no time to hang out.

Sample Input 4

314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3

Sample Output 4

9


open Batteries
let rec sum lst =
  match lst with
  | [] -> 0
  | first :: rest -> first + sum rest

let n, m = Scanf.sscanf (read_line()) "%d %d" (fun n m ->n,m
)
let a = read_line () |> String.split_on_char ' ' |> List.map int_of_string
let _ = (if sum a > n then -1 else n - (sum a)) |> Printf.printf "%d\n"


open Base
open Stdio

let read_line () =
    In_channel.(input_line_exn stdin)

let mapt2 ~f (a, b) = (f a, f b)

let array_replace arr i ~f = arr.(i) <- f (arr.(i))

let n = Int.of_string @@ read_line ()

let sums = Array.create ~len:(n+1) 0
let neg_res = Array.create ~len:(n+1) 0L
let g_hd = Array.create ~len:(n+1) 0
let g_nx = Array.create ~len:(2*n) 0
let g_to = Array.create ~len:(2*n) 0
let g_len = ref 0
let g_add u v =
    g_len := !g_len + 1;
    g_nx.(!g_len) <- g_hd.(u);
    g_to.(!g_len) <- v;
    g_hd.(u) <- !g_len
let g_adj_iter cur x0 f =
    let rec loop e acc = if e = 0 then acc else
        let ch = g_to.(e) in
        loop g_nx.(e) (f ch acc)
    in
    loop g_hd.(cur) x0

let colors = read_line () |> String.split ~on:' ' |> List.map ~f:Int.of_string
    |> List.cons 0 |> Array.of_list

let rec dfs ?(cur=1) ?(par=0) () =
    let memo = sums.(colors.(par)) in
    let tree_size = g_adj_iter cur 1 (fun ch acc ->
        acc + if ch = par then 0 else dfs ~cur:ch ~par:cur ())
    in

    array_replace sums colors.(cur) ((+) 1);
    let component_size = Int64.of_int @@ tree_size - (sums.(colors.(par)) - memo) in
    array_replace neg_res colors.(par) (fun x -> Int64.(x + component_size * (component_size + 1L) / 2L));
    sums.(colors.(par)) <- tree_size + memo;
    tree_size

let () =
    for i = 0 to n - 2 do
        let a, b = read_line () |> String.lsplit2_exn ~on:' ' |> mapt2 ~f:Int.of_string in
        g_add a b;
        g_add b a
    done

let () =
    ignore (dfs ());
    for i = 1 to n do
        let component_size = Int64.of_int @@ n - sums.(i) in
        let n64 = Int64.of_int n in
        let res = Int64.(n64 * (n64 + 1L) / 2L - component_size * (component_size + 1L) / 2L - neg_res.(i)) in
        printf "%Ld\n" res
    done

Score : 600 points

Problem Statement

We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i.
Additionally, each vertex is painted in a color, and the color of Vertex i is c_i. Here, the color of each vertex is represented by an integer between 1 and N (inclusive). The same integer corresponds to the same color; different integers correspond to different colors.

For each k=1, 2, ..., N, solve the following problem:

Find the number of simple paths that visit a vertex painted in the color k one or more times.

Note: The simple paths from Vertex u to v and from v to u are not distinguished.

Constraints

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

1 \leq c_i \leq N

1 \leq a_i,b_i \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
c_1 c_2 ... c_N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

Print the answers for k = 1, 2, ..., N in order, each in its own line.

Sample Input 1

3
1 2 1
1 2
2 3

Sample Output 1

5
4
0

Let P_{i,j} denote the simple path connecting Vertex i and j.

There are 5 simple paths that visit a vertex painted in the color 1 one or more times:

P_{1,1}\,,\,
P_{1,2}\,,\,
P_{1,3}\,,\,
P_{2,3}\,,\,
P_{3,3}

There are 4 simple paths that visit a vertex painted in the color 2 one or more times:

P_{1,2}\,,\,
P_{1,3}\,,\,
P_{2,2}\,,\,
P_{2,3}

There are no simple paths that visit a vertex painted in the color 3 one or more times.

Sample Input 2

1
1

Sample Output 2

1

Sample Input 3

2
1 2
1 2

Sample Output 3

2
2

Sample Input 4

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

Sample Output 4

5
8
10
5
5

Sample Input 5

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

Sample Output 5

18
15
0
14
23
0
23
0


open Base
open Stdio

(* Core.read_line is deprecated *)
let read_line () =
    (* Out_channel.(flush stdout); *)
    In_channel.(input_line_exn stdin)

let mapt2 ~f (a, b) = (f a, f b)

let et_size = ref 0

let n = Int.of_string @@ read_line ()

let sums = Array.create ~len:(n+1) 0
let neg_res = Array.create ~len:(n+1) 0L
let g_hd = Array.create ~len:(n+1) 0
let g_nx = Array.create ~len:(2*n) 0
let g_to = Array.create ~len:(2*n) 0
let g_len = ref 0
let g_add u v =
    g_len := !g_len + 1;
    g_nx.(!g_len) <- g_hd.(u);
    g_to.(!g_len) <- v;
    g_hd.(u) <- !g_len

let colors = read_line () |> String.split ~on:' ' |> List.map ~f:Int.of_string |> (List.cons 0) |> Array.of_list

let rec dfs ?(cur=1) ?(par=0) () =
    let et_in = !et_size in
    let memo = sums.(colors.(par)) in
    et_size := !et_size + 1;
    let rec loop e = if e = 0 then () else
        let ch = g_to.(e) in
        ((if ch = par then () else dfs ~cur:ch ~par:cur ()); loop g_nx.(e)) in
    loop (g_hd.(cur));
    let et_out = !et_size in
    et_size := !et_size + 1;

    sums.(colors.(cur)) <- sums.(colors.(cur)) + 1;
    let tree_size = (et_out - et_in + 1) / 2 in
    let component_size = Int64.of_int @@ tree_size - (sums.(colors.(par)) - memo) in
    neg_res.(colors.(par)) <- Int64.(neg_res.(colors.(par)) + component_size * (component_size + 1L) / 2L);
    sums.(colors.(par)) <- tree_size + memo

let _ =
    for i = 0 to n - 2 do
        let a, b = read_line () |> String.lsplit2_exn ~on:' ' |> mapt2 ~f:Int.of_string in
        g_add a b;
        g_add b a
    done

let _ =
    dfs ();
    let tree_size = !et_size / 2 in
    for i = 1 to n do
        let component_size = Int64.of_int @@ tree_size - sums.(i) in
        let n64 = Int64.of_int n in
        let res = Int64.(n64 * (n64 + 1L) / 2L - component_size * (component_size + 1L) / 2L - neg_res.(i)) in
        printf "%Ld\n" res
    done


let n, k = Scanf.scanf "%d %d\n" @@ fun a b -> a, b
let () = Printf.printf "%d\n" (min (n mod k) (k - n mod k))

Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


let solve k =
  let q = Queue.create () in
  let rec f i =
    if i < 10 then (
      Queue.push i q;
      f (i + 1)
    )
  in
  f 1;
  let rec f i =
    if i <= k then (
      let x = Queue.pop q in
      let m = x mod 10
      and j = ref i in
      let g y =
        if !j = k then print_int y
        else Queue.push y q;
        j := !j + 1
      in
      if m <> 0 then g (10 * x + m - 1);
      g (10 * x + m);
      if m <> 9 then g (10 * x + m + 1);
      f !j
    )
  in
  f 10

let ans k =
  if k < 10 then print_int k
  else solve k

let () = ans (read_int ())

Score : 400 points

Problem Statement

A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:

In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.

For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.

You are given a positive integer K. Find the K-th smallest lunlun number.

Constraints

1 \leq K \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the answer.

Sample Input 1

15

Sample Output 1

23

We will list the 15 smallest lunlun numbers in ascending order:

1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.

Thus, the answer is 23.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

13

Sample Output 3

21

Sample Input 4

100000

Sample Output 4

3234566667

Note that the answer may not fit into the 32-bit signed integer type.


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

Scanf.scanf "%d" (fun nn ->
    let divisors a =
        let rec loop i acc =
            if i * i > a then acc else
                let acc = if a mod i = 0 then S.add (a / i) (S.add i acc) else acc in
                loop (i + 1) acc
        in
        loop 2 (S.singleton a)
    in
    let rec loop n k =
        if n = 1 then true else
            if n < k then false else
            if n mod k = 0 then loop (n / k) k
                           else loop (n mod k) k
    in
    let rec loop2 acc = function
        | [] -> acc
        | hd :: tl ->
                let acc = if loop nn hd then acc + 1 else acc in
                loop2 acc tl
    in
    if nn = 2 then Printf.printf "%d\n" 1 else
        let set = divisors (nn - 1) in
        let set = S.union (divisors nn) set in
        loop2 0 (S.elements set) |> Printf.printf "%d\n"
)

Score : 600 points

Problem Statement

Given is a positive integer N.

We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.

Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K.

In how many choices of K will N become 1 in the end?

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of choices of K in which N becomes 1 in the end.

Sample Input 1

6

Sample Output 1

3

There are three choices of K in which N becomes 1 in the end: 2, 5, and 6.

In each of these choices, N will change as follows:

When K=2: 6 \to 3 \to 1

When K=5: 6 \to 1

When K=6: 6 \to 1

Sample Input 2

3141

Sample Output 2

13

Sample Input 3

314159265358

Sample Output 3

9


let s = read_line () in
print_endline @@ if s.[2] = s.[3] && s.[4] = s.[5] then "Yes" else "No"

Score : 100 points

Problem Statement

A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.

Given a string S, determine whether it is coffee-like.

Constraints

S is a string of length 6 consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is coffee-like, print Yes; otherwise, print No.

Sample Input 1

sippuu

Sample Output 1

Yes

In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.

Sample Input 2

iphone

Sample Output 2

No

Sample Input 3

coffee

Sample Output 3

Yes


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

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

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

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

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

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

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

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

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

let 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 x = scan "%d" id

let () =
  ListL.fold_left [500;5] ~init:(0,x) ~f:(fun (n,x) i ->
      (n+((x/i) * if i = 500 then 1000 else 5), x mod i))
  |> Tuple2.first
  |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)

Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?

(We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.)

Constraints

0 \leq X \leq 10^9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the maximum number of happiness points that can be earned.

Sample Input 1

1024

Sample Output 1

2020

By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned.

Sample Input 2

0

Sample Output 2

0

He is penniless - or yenless.

Sample Input 3

1000000000

Sample Output 3

2000000000

He is a billionaire - in yen.


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

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

let id = identity

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

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

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

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

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

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

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

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

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

let 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 (k,n) = scan "%d %d" Tuple2.make
let ls = scan_list ~sep:' ' Int.of_string

let () =
  let ms = ls@[k+List.first ls] in
  ListL.map (zip ms (List.drop 1 ms)) ~f:(fun (a, b) -> b - a)
  |> List.max
  |> ((-) k)
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

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

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.


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

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

let lst = Str.split (Str.regexp " ") (read_line ())
          |> List.map int_of_string
          |> List.sort compare

let rec f head tail lst =
        match lst with
                  [] -> [0]
                | first :: [] ->
                        [head + (k - tail)] @ f head tail []
                | first :: rest ->
                        [(List.hd rest) - first] @ f head tail rest

let () =
        let tmplst = f (List.min lst) (List.max lst) lst in
        let tmplst2 = List.filter (fun elmnt ->
                elmnt != (List.max tmplst)
        ) tmplst in
                List.fold_right (+) tmplst2 0
                |> Printf.printf "%d\n"


let () =
	let k, n = Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
	let arr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
	let brr = Array.init n @@ fun i ->
    	if i = 0 then k - arr.(n-1) + arr.(i) else arr.(i) - arr.(i-1) in
    print_int ((Array.fold_left (+) 0 brr) - (Array.fold_left max 0 brr))


let id x = x

let init n f =
  let rec g i ns = if i = 0 then 0 :: ns else g (i - 1) (i :: ns) in
  List.map f (g (n - 1) [])

let (n, x, y) = Scanf.scanf "%d %d %d" @@ fun n x y -> (n, x, y)

let ix = init n (fun i -> i + 1)

let pair =
  let xs = fst @@ List.fold_left (fun (ns, ys) i -> ((List.map (fun j -> (i, j)) ys)::ns, List.tl ys)) ([], ix) ix in
  List.fold_left (fun xs ys -> List.rev_append xs ys) [] xs

let f (i, j) =
  let rec min' m = function
    | [] -> m
    | x :: xs -> min' (min m x) xs
  in
  min' max_int [(abs (i - j)); (abs (i - y)) + 1 + (abs (x - j)); (abs (i - x)) + 1 + (abs (y - j))]

let g xs i =
  match xs with
    | [] -> [(i, 1)]
    | (j, c) :: xs -> if i = j then (j, c + 1) :: xs else (i, 1) :: (j, c) :: xs

let () =
  let cs = pair
    |> List.map f
    |> List.fast_sort (fun i j -> i - j)
    |> List.fold_left g [] in
  List.iter (fun k ->
    try Printf.printf "%d\n" (List.assoc k cs)
    with Not_found -> print_endline "0"
  ) (init (n - 1) (fun i -> i + 1))

Score : 400 points

Problem Statement

We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:

For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.

There is an edge between Vertex X and Vertex Y.

For each k=1,2,...,N-1, solve the problem below:

Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.

Constraints

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

1 \leq X,Y \leq N

X+1 < Y

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X Y

Output

For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.

Sample Input 1

5 2 4

Sample Output 1

5
4
1
0

The graph in this input is as follows:

There are five pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 1: (1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5).

There are four pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 2: (1,3)\,,(1,4)\,,(2,5)\,,(3,5).

There is one pair (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 3: (1,5).

There are no pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 4.

Sample Input 2

3 1 3

Sample Output 2

3
0

The graph in this input is as follows:

Sample Input 3

7 3 7

Sample Output 3

7
8
4
2
0
0

Sample Input 4

10 4 8

Sample Output 4

10
12
10
8
4
1
0
0
0


let _ = Scanf.sscanf (read_line()) "%d %d" (fun n m ->
  (n * (n-1) + m * (m-1)) / 2
) |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

We have N+M balls, each of which has an integer written on it.

It is known that:

The numbers written on N of the balls are even.

The numbers written on M of the balls are odd.

Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.

It can be shown that this count does not depend on the actual values written on the balls.

Constraints

0 \leq N,M \leq 100

2 \leq N+M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

2 1

Sample Output 1

1

For example, let us assume that the numbers written on the three balls are 1,2,4.

If we choose the two balls with 1 and 2, the sum is odd;

If we choose the two balls with 1 and 4, the sum is odd;

If we choose the two balls with 2 and 4, the sum is even.

Thus, the answer is 1.

Sample Input 2

4 3

Sample Output 2

9

Sample Input 3

1 1

Sample Output 3

0

Sample Input 4

13 3

Sample Output 4

81

Sample Input 5

0 3

Sample Output 5

3


let is_palindrome s =
  let n = String.length s in
  Array.fold_left ( && ) true @@
  Array.init (n / 2) @@ fun i -> s.[i] = s.[n - i - 1]

let () =
  let s = read_line () in
  let n = String.length s in
  print_endline @@
  if
    is_palindrome s &&
    is_palindrome (String.sub s 0 ((n - 1) / 2)) &&
    is_palindrome (String.sub s ((n + 1) / 2) ((n - 1) / 2))
  then "Yes"
  else "No"

Score : 200 points

Problem Statement

A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:

S is a palindrome.

Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.

The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.

Determine whether S is a strong palindrome.

Constraints

S consists of lowercase English letters.

The length of S is an odd number between 3 and 99 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

If S is a strong palindrome, print Yes;
otherwise, print No.

Sample Input 1

akasaka

Sample Output 1

Yes

S is akasaka.

The string formed by the 1-st through the 3-rd characters is aka.

The string formed by the 5-th through the 7-th characters is aka.
All of these are palindromes, so S is a strong palindrome.

Sample Input 2

level

Sample Output 2

No

Sample Input 3

atcoder

Sample Output 3

No


let () =
  let l = read_float () in
  let l_p = l /. 3. in
  l_p *. l_p *. l_p |> Printf.printf "%f\n"

Score : 300 points

Problem Statement

Given is a positive integer L.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.

Constraints

1 ≤ L ≤ 1000

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

3

Sample Output 1

1.000000000000

For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96.

On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater.

Sample Input 2

999

Sample Output 2

36926037.000000000000


open Batteries
module CountDict = Map.Make(Int)
let count_int lst =
  let rec add_lst dict l =
    match l with
    | [] -> dict
    | first :: rest ->
      if CountDict.mem first dict then add_lst (CountDict.add first ((CountDict.find first dict) + 1) dict) rest else
      add_lst (CountDict.add first 1 dict) rest
  in add_lst CountDict.empty lst

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

let dict = count_int a

let all = (CountDict.fold (fun key value a -> a + (value * (value - 1))) dict 0) / 2

let rec loop lst =
  match lst with
  | [] -> ()
  | first :: rest -> let value = CountDict.find first dict in Printf.printf "%d\n" (all - value + 1); loop rest

let _ = loop a

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

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

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


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

let () = Scanf.scanf "%d %d\n" @@ fun n s ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let result = ref 0 in
  let dp = Array.make 3001 0 in
  for i = 0 to n - 1 do
    for j = s downto as_.(i) + 1 do
      dp.(j) <- dp.(j) +^ dp.(j - as_.(i))
    done;
    dp.(as_.(i)) <- dp.(as_.(i)) +^ (i + 1);
    result := !result +^ dp.(s) *^ (n - i);
    dp.(s) <- 0;
  done;
  Printf.printf "%d\n" @@ !result

Score : 600 points

Problem Statement

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

For a pair of integers (L, R) such that 1\leq L \leq R \leq N, let us define f(L, R) as follows:

f(L, R) is the number of sequences of integers (x_1, x_2, \ldots , x_k) such that L \leq x_1 < x_2 < \cdots < x_k \leq R and A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S.

Find the sum of f(L, R) over all pairs of integers (L, R) such that 1\leq L \leq R\leq N. Since this sum can be enormous, print it modulo 998244353.

Constraints

All values in input are integers.

1 \leq N \leq 3000

1 \leq S \leq 3000

1 \leq A_i \leq 3000

Input

Input is given from Standard Input in the following format:

N S
A_1 A_2 ... A_N

Output

Print the sum of f(L, R), modulo 998244353.

Sample Input 1

3 4
2 2 4

Sample Output 1

5

The value of f(L, R) for each pair is as follows, for a total of 5.

f(1,1) = 0

f(1,2) = 1 (for the sequence (1, 2))

f(1,3) = 2 (for (1, 2) and (3))

f(2,2) = 0

f(2,3) = 1 (for (3))

f(3,3) = 1 (for (3))

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

152


Scanf.scanf "%d %d" (fun h w ->
    let s = Array.init h (fun _ -> Scanf.scanf " %s" (fun s -> s)) in
    let mat = Array.make_matrix h w 100000 in
    mat.(0).(0) <- if s.(0).[0] = '#' then 1 else 0;
    for y = 0 to h - 1 do
        for x = 0 to w - 1 do
            if x < w - 1 then (
                let q = if s.(y).[x] = '.' && s.(y).[x + 1] = '#' then 1 else 0 in
                mat.(y).(x + 1) <- min mat.(y).(x + 1) (mat.(y).(x) + q)
            );
            if y < h - 1 then (
                let q = if s.(y).[x] = '.' && s.(y + 1).[x] = '#' then 1 else 0 in
                mat.(y + 1).(x) <- min mat.(y + 1).(x) (mat.(y).(x) + q)
            );
         done
    done;
    Printf.printf "%d\n" mat.(h - 1).(w - 1)
)

Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
\vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4


Score : 100 points

Problem Statement

Print the K-th element of the following sequence of length 32:

1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51

Constraints

1 \leq K \leq 32

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the K-th element.

Sample Input 1

6

Sample Output 1

2

The 6-th element is 2.

Sample Input 2

27

Sample Output 2

5

The 27-th element is 5.


open Printf
open Scanf

let prod h w =
    if w mod 2 = 0 then (w/2)*h
    else if h mod 2 = 0 then (w/2)*(h/2)+(w+1)/2*(h/2)
    else (w/2)*(h/2)+(w+1)/2*(h+1)/2

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

Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000