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

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

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

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

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

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

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

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

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

    module WMap = Map.Make (W)

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

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

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

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

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

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

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

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

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

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

module G = IntWeightedDirectedGraphByArray.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 :: es.(a - 1);
      es.(b - 1) <- a - 1 :: es.(b - 1);
  done;
  let d = G.dijkstra n (fun u -> { G.fold = fun f ->
    List.fold_right (fun v -> f (v, 1, u + 1)) es.(u) }) 0 in
  if List.exists (fun (d, _) -> d = max_int) @@ List.init n d
  then print_endline "No"
  else begin
    print_endline "Yes";
    for i = 1 to n - 1 do
      Printf.printf "%d\n" @@ snd @@ d i
    done
  end


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

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

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

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

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

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.


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

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

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

type quotient = Nan | Zero | Inf | Quotient of int * int

let quotient_of_intpair = function
  | (0, 0) -> Nan
  | (0, _) -> Zero
  | (_, 0) -> Inf
  | (a, b) ->
      let d = gcd (abs a) (abs b) in
      if b < 0
      then Quotient (~- a / d, ~-b / d)
      else Quotient (a / d, b / d)

let inv = function
  | Zero -> Inf
  | Inf -> Zero
  | Quotient (a, b) -> Quotient (b * compare 0 a, abs a)

module QuotientMap = Map.Make (struct
  type t = quotient
  let compare = compare
end)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let abs = List.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> quotient_of_intpair (a, b) in
  let zeros, m =
    List.fold_left (fun (zeros, m) -> function
      | Nan -> (zeros + 1, m)
      | q ->
          zeros,
          QuotientMap.update q (fun o -> Some (1 + Option.value ~default:0 o)) @@
          QuotientMap.update (inv q) (fun o -> Some (Option.value ~default:0 o)) m) (0, QuotientMap.empty) abs in
  Printf.printf "%d\n" @@
  ( +^ ) (zeros -^ 1) @@
  QuotientMap.fold (fun q n acc ->
    match q with
    | Zero -> acc
    | Quotient (a, _) when a < 0 -> acc
    | _ ->
        let n' = QuotientMap.find (inv q) m in
        acc *^ (power ( *^ ) 1 2 n +^ power ( *^ ) 1 2 n' -^ 1)) m 1


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
    let ans4 = ans3 + c0 in
                       Printf.printf "%d\n" (ans4 -@ 1)
)


open Scanf
open Printf

let () = scanf "%s %s" (fun s t -> if t = s ^ Char.escaped t.[(String.length s) ] then "Yes" else "No")
|>printf "%s"

Score : 100 points

Problem Statement

Takahashi wants to be a member of some web service.

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

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

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

Constraints

S and T are strings consisting of lowercase English letters.

1 \leq |S| \leq 10

|T| = |S| + 1

Input

Input is given from Standard Input in the following format:

S
T

Output

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

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

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

Sample Input 2

snuke
snekee

Sample Output 2

No

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

Sample Input 3

a
aa

Sample Output 3

Yes


open Batteries
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 then a
    else if k <= a + b then a
    else a + (a + b) - k
  in puti r;;

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


let rec kn a k =
        if a <= 0 || k <= 0 then
                0
        else if a < k then
                a
        else
                k

let () = Scanf.scanf "%d %d %d %d" (
fun a b c k ->
        let an = kn a k in
        let bn = kn b (k - an) in
        let cn = kn c (k - an - bn) in
        an - cn
) |> Printf.printf "%d\n"


let () = Scanf.scanf "%d %d %d %d" @@ fun a b c k ->
  let l = min a k in
  let m = min b (k - l) in
  let n = min c (k - l - m) in
  Printf.printf "%d\n" @@ l - n


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

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
open Printf
open Scanf

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

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

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i
end

module L = MyList

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

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

module MyString = struct
  include String

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

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

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

module S = MyString

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

let _ =
  let (n,m,x) = rdi3 () in
  let cas = rdvs n rdhi in
  print_endline "0";;


open Batteries
(* bitの数字の2真数の時の右からn番目の数字が0か1か *)
let is_bit_one bit n = if bit land (1 lsl n) = 0 then false else true
let bit_list bit n =
  let rec get i =
    match i with
    | i when i = n -> []
    | _ -> if is_bit_one bit i then i :: get (i+1) else get (i+1)
  in get 0
(* 文字列をcharのlistにする *)
let explode s = List.init (String.length s) (String.get s)

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

let sankousyo =
  Array.init n @@ fun a -> let k = read_line () |> String.split_on_char ' ' |> List.map int_of_string in (List.hd k, List.tl k |> Array.of_list)

let rec up_rikaido rikaido i up_rikaido_array =
  if i >= Array.length up_rikaido_array then rikaido else (rikaido.(i) <- rikaido.(i) + up_rikaido_array.(i); up_rikaido rikaido (i+1) up_rikaido_array)

let check target_sankousyo_array =
  let rec check_loop i rikaido =
    if i >= Array.length target_sankousyo_array then rikaido else
    (
      let _, up_rikaido_array = target_sankousyo_array.(i) in
      check_loop (i+1) (up_rikaido rikaido 0 up_rikaido_array)
    )
    in if Array.fold_left (fun a b -> if b >= x && a = true then true else false) true (check_loop 0 (Array.init m @@ fun _ -> 0)) then
    Array.fold_left (fun a b -> let c, _ = b in a + c) 0 target_sankousyo_array else max_int

let rec get_sankousyo lst =
  Array.init (List.length lst) @@ fun a -> sankousyo.(List.nth lst a)

let rec bit_loop bit =
  if bit >= n * n then max_int else (
    (* 処理 *)
    let j = check @@ get_sankousyo @@ bit_list bit n in
    min (j) (bit_loop (bit+1))
  )

let p = bit_loop 0
let _ = Printf.printf "%d\n" @@ (if p = max_int then -1 else p)


let () = Scanf.scanf "%d %d %d\n" @@ fun n m x ->
  let icass = List.init n @@ fun i ->
    Scanf.scanf "%d " @@ fun c ->
      (i, c, List.init m @@ fun _ -> Scanf.scanf "%d " Fun.id) in
  let ans =
    List.fold_left min max_int @@
    List.init (1 lsl n) @@ fun bits ->
      let skill = Array.make m 0 in
      let cost =
        List.fold_left (fun cost (i, c, as_) ->
          if bits land (1 lsl i) = 0
          then cost
          else begin
            List.iteri (fun j a ->
              skill.(j) <- a + skill.(j)) as_;
            c + cost
          end) 0 icass in
      if
        List.for_all (( <= ) x) @@
        Array.to_list skill
      then cost
      else max_int in
  Printf.printf "%d\n" @@
  if ans = max_int then -1 else ans


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') (m + c)) ss;
    try
      ignore
      (Array.fold_left (fun x (m, c) ->
        if x + m < 0 || x + c < 0 then raise Not_found; x + c) 0 ss);
      "Yes"
    with Not_found -> "No"
  end

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 () =
  let s = read_line () in
  print_endline @@
    if s = "ABC"
    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.


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 (n, k) = scan "%d %d" Tuple.Tuple2.make
let arr = Array.make n false

let () =
  ListL.iter (0++^k) ~f:(fun _ ->
      let _ = scan "%d" id in
      scan_list (Some ' ') Int.of_string
      |> ListL.iter ~f:(fun i -> arr.(pred i) <- true));
  Array.filter ((=) false) arr
  |> Array.length
  |> 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


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 (n, m) = scan "%d %d" Tuple.Tuple2.make
let heights = scan_array ~sep:' ' Int.of_string
let routes = scan_lines m "%d %d" Tuple.Tuple2.make

let () =
  let max_heights = Array.make n (-1) in
  ListL.iter routes
    ~f:(fun (a, b) ->
        let a, b = pred a, pred b in
        max_heights.(a) <- max max_heights.(a) heights.(b);
        max_heights.(b) <- max max_heights.(b) heights.(a));
  ArrayL.mapi heights ~f:(fun i h ->
      if h > max_heights.(i) then 1 else 0)
  |> Array.sum
  |> Printf.printf "%d\n"

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
class union_find n = object (self)
  val mutable par = ( [| |] : int array)
  method init =
    par <- Array.init n (fun a -> a)
  method get_par = par

  method root s =
    let rec loop x =
      if par.(x) = x then x else (par.(x) <- loop par.(x); par.(x))
    in loop s

  method rank s =
    let rec loop x n =
      if par.(x) = x then n else loop par.(x) (n+1)
    in loop s 1

  method unite x y =
    let xrank = self#rank x in
    let yrank = self#rank x in
    let rx = self#root x in
    let ry = self#root y in
    if rx != ry then (if xrank < yrank then par.(rx) <- ry else par.(ry) <- rx)

  method same x y = self#root x = self#root y

  method members x = (* 要素xが属する木の全ての要素を返す *)
    let r = self#root x in Array.fold_left (fun a y -> if self#root y = r then y :: a else a) [] par

  method roots = (* 全ての根 *) Array.fold_left (fun x y -> if List.mem y x then x else y :: x) [] par

  method tree_count = (* 木の数 *) List.length @@ self#roots
end

let n, m = Scanf.sscanf (read_line()) "%d %d" (fun n m -> n,m)
let h = read_line () |> String.split_on_char ' ' |> List.map int_of_string |> Array.of_list

let tree = new union_find n
let _ = tree#init

let rec loop i =
  if i >= m then () else
  (
    Scanf.sscanf (read_line()) "%d %d" (fun a b -> tree#unite (a-1) (b-1)); loop (i+1)
  )

let _ = loop 0

let rec check_loop i ans =
  if i >= n then ans else (
    let i_height = h.(i) in
    let members = tree#members i in
    let rec check lst =
      match lst with
      | [] -> true
      | first :: rest ->
        if first = i then check rest else (
          if i_height <= h.(first) then false else check rest
        )
    in if check members then check_loop (i+1) (ans+1) else check_loop (i+1) ans
  )

let _ = Printf.printf "%d\n" ((check_loop 0 0) - 1)


module IntMap = Map.Make (struct
  type t = int
  let compare = compare
end)

let () = Scanf.scanf "%d" @@ fun n ->
  let rec pow5s acc i =
    if n < i * i * i * i
    then acc
    else pow5s (IntMap.add (i * i * i * i * i) i acc) (i + 1) in
  let pow5s = pow5s IntMap.empty 0 in
  let Some (a, b) =
    IntMap.fold (fun pow5a a ans ->
      match IntMap.find_opt (abs (pow5a - n)) pow5s with
      | None -> ans
      | Some b -> Some (a, if pow5a - n <= 0 then ~- b else b)) pow5s None in
  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


let rec solve a b c acc ss =
  if a < 0 || b < 0 || c < 0 then raise Not_found;
  match ss with
  | [] -> acc
  | "AB" :: rest ->
      begin try solve (a + 1) (b - 1) c ('A' :: acc) rest with
      | Not_found -> solve (a - 1) (b + 1) c ('B' :: acc) rest
      end
  | "AC" :: rest ->
      begin try solve (a + 1) b (c - 1) ('A' :: acc) rest with
      | Not_found -> solve (a - 1) b (c + 1) ('C' :: acc) rest
      end
  | "BC" :: rest ->
      begin try solve a (b + 1) (c - 1) ('B' :: acc) rest with
      | Not_found -> solve a (b - 1) (c + 1) ('C' :: acc) rest
      end

let () = Scanf.scanf "%d %d %d %d\n" @@ fun n a b c ->
  let ss = List.init n @@ fun _ -> Scanf.scanf "%s\n" Fun.id in
  try
    let ans = solve a b c [] ss in
    print_endline "Yes";
    List.iter (Printf.printf "%c\n") (List.rev ans)
  with Not_found -> print_endline "No"

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


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

let () = print_endline @@ if k - 1 <= b - a then "OK" else "NG"

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


let () =
  let k = int_of_string @@ read_line () in
  Scanf.scanf "%d %d" @@
    fun a b -> let n = (a+k-1) / k in
    if k*n <= b
    then print_endline "OK"
    else print_endline "NG"


let k = read_int ()
let a, b = Scanf.scanf "%d %d\n" @@ fun a b -> a, b
let ans = if a mod k = 0 || a/k*a+k <= b || b mod k = 0 then "OK" else "NG"
let () = print_endline ans


Scanf.scanf "%d" (fun x ->
    let rec loop i acc =
        if acc >= x then i else
            loop (i + 1) (acc + acc / 100)
    in
    loop 0 100 |> Printf.printf "%d\n"
)

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 () = Scanf.scanf "%d" @@ fun x ->
  let cache = Array.make 5000 0 in
  cache.(0) <- 100;
  for i = 0 to 4998 do
    cache.(i + 1) <- cache.(i) + cache.(i) / 100
  done;
  Printf.printf "%d\n" @@
  List.find (fun i -> x <= cache.(i)) @@
  List.init 5000 Fun.id


let a, b, n = Scanf.scanf "%f %f %f\n" @@ fun a b c -> a, b, c
let rec f x m =
  let nm = (floor (a*.x/.b)) -. a*.(floor(x/.b)) in
  if x < 0. then m
  else if nm >= m then f (x-.1.) nm
  else f (x-.1.) m
let () = print_int (int_of_float (f n 0.))

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


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

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


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 (s, w) = scan "%d %d" Tuple2.make

let () =
  if w >= s then Printf.printf "unsafe\n"
  else Printf.printf "safe\n"

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 () = Scanf.scanf "%d %d" @@ fun s w ->
  print_endline @@
    if s <= w
    then "unsafe"
    else "safe"


let s, w = Scanf.scanf "%d %d\n" @@ fun a b -> a, b
let ans = if w >= s then "unsafe" else "safe"
let () = print_endline ans


let n = read_int()

module SS = Set.Make(String)

let rec f i ans set =
  if i = n then ans
  else
    let s = read_line () in
    if SS.mem s set then f (i + 1) ans set
    else f (i + 1) (ans + 1) (SS.add s set)

let () = print_int (f 0 0 SS.empty)

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


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

let n = scan "%d" id
let ls = scan_lines n "%s" id

let () =
  let h = Hashtbl.create n in
  ListL.iter ls ~f:(fun s ->
      Hashtbl.add h s true);
  Printf.printf "%d\n" @@ Hashtbl.length h


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

let sum = List.fold_left (+) 0 a

let () = Printf.printf "%d\n" @@ if sum <= n then n - sum else -1

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 Printf
open Scanf

let id x = x

let solve n m =
  let la = List.init m @@ fun _ -> scanf "%d " id in
  let pd = n - List.fold_left (+) 0 la in
  if pd >= 0 then pd else -1

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


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 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 memo = sums.(colors.(par)) in
    let rec loop e acc = if e = 0 then acc else
        let ch = g_to.(e) in
        let ret = if ch = par then 0 else dfs ~cur:ch ~par:cur () in
        loop g_nx.(e) (ret + acc)
    in
    let tree_size = loop (g_hd.(cur)) 1 in

    sums.(colors.(cur)) <- sums.(colors.(cur)) + 1;
    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;
    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


let n = read_int ()

let rec factors m a acc =
  if a * a > m then acc
  else if a * a = m then a :: acc
  else if m mod a = 0 then factors m (a + 1) (a :: (m / a) :: acc)
  else factors m (a + 1) acc

let fs = factors (n - 1) 1 [] |> List.length

let rec test m k =
  if m = 0 then false else if m mod k = 0 then test (m / k) k else m mod k = 1

let fn =
  factors n 1 []
  |> List.filter (fun x -> x <> 1)
  |> List.map (test n)
  |> List.fold_left (fun acc x -> if x then acc + 1 else acc) 0

;;
print_int (fs - 1 + fn);
print_newline ()

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 rec aux n k =
  if n mod k = 0
  then aux (n / k) k
  else n

let rec solve n k ans =
  if n < k * k
  then ans
  else
    solve n (k + 1) @@
    ans +
    if n mod k = 0
    then (if aux n k mod k = 1 then 1 else 0) + (if aux n (n / k) mod (n / k) = 1 then 1 else 0)
    else if (n - 1) mod k = 0
    then 1 + (if n - 1 = k * k then 0 else 1)
    else 0
let solve n = solve n 2 2

let () = Printf.printf "%d\n" @@ Scanf.scanf "%d" solve


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
    let set = divisors (nn - 1) in
    let set = S.union (divisors nn) set in
    loop2 0 (S.elements set) |> Printf.printf "%d\n"
)


let x = read_int ()
let ans = x / 500 * 1000 + x mod 500 / 5 * 5
let () = print_int ans

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.


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.make n 0 in
  for i = 0 to n-1 do
    print_int i; print_newline ();
    if i = 0 then brr.(n-1) <- abs (arr.(n-1) - arr.(i))
    else brr.(i-1) <- abs (arr.(i) - arr.(i-1))
  done;
  let ans = Array.fold_left
      (fun (m, s) x -> if m < x then (x, s+m) else (m, x+s)) (0, 0) brr in
  print_int (snd ans)

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.


open Batteries
let rec sum lst =
  match lst with
  | [] -> 0
  | first :: rest -> first + sum rest
let kn = Scanf.sscanf (read_line()) "%d %d" (fun k n ->
  [|k; n|]
)
let k = kn.(0)
let n = kn.(1)
let a = read_line () |> String.split_on_char ' ' |> List.map int_of_string |> Array.of_list
let rec get_lengths i =
  if i = (Array.length a) - 1 then [(k-a.(i))+a.(0)] else
  a.(i+1) - a.(i) :: get_lengths (i+1)

let lengths = List.sort compare @@ get_lengths 0
let _ = Printf.printf "%d\n" (sum @@ List.tl @@ List.rev lengths)


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

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

let id = identity

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

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

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

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

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

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

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

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

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

let 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,x,y) = scan "%d %d %d" Tuple3.make

let () =
  let arr = Array.make_matrix (succ n) (succ n) 0 in
  ListL.iter (1++n) ~f:(fun i ->
      ListL.iter (i++n) ~f:(fun j -> arr.(i).(j) <- j - i));
  ListL.iter (1++x) ~f:(fun i ->
      ListL.iter (x+1++n) ~f:(fun j ->
          arr.(i).(j) <- min (arr.(i).(x) + abs (j-y) + 1) arr.(i).(j)));
  ListL.iter (x+1++^y) ~f:(fun i ->
      ListL.iter (i+1++n) ~f:(fun j ->
          arr.(i).(j) <- min ((i-x) + abs (j-y) + 1) arr.(i).(j)));
  let h = Hashtbl.create n in
  ListL.iter (1++n) ~f:(fun i ->
      ListL.iter (i+1++n) ~f:(fun j ->
          Hashtbl.modify_def 0 arr.(i).(j) succ h));
  (* Array.print ~sep:"\n" (Array.print Int.print) stderr arr ; *)
  ListL.iter (1++^n) ~f:(fun i ->
      Printf.printf "%d\n" @@ Hashtbl.find_default h i 0)

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


Scanf.scanf "%d %d" (fun n m -> print_int (n * (n - 1) / 2 + m * (m - 1) / 2))

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 str =
  let n = String.length str in
  List.fold_left (&&) true @@
  List.init (n/2) @@ fun i -> str.[i] = str.[n-1-i]

let () =
  let s = read_line () in
  let n = String.length s in
  Printf.printf "%s\n" @@
  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 s = read_line ()
let rec f s n i =
  if i >= n/2 then true else if s.[i] <> s.[n-i-1] then false
  else f s n (i+1)
let n = String.length s
let ans = if f s n 0 && f s ((n-1) / 2) 0 then "Yes" else "No"
let () = print_endline ans


Scanf.scanf "%f" (fun l -> print_float ((l /. 3.) ** 3.))

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


let () = Scanf.scanf "%d" @@ fun l ->
  let w = float_of_int l /. 3. in
  Printf.printf "%.10f" @@ w *. w *. w


Scanf.scanf "%d %d" (fun n s ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let dp = Array.make_matrix (n + 1) (s + 1) 0 in
    let m = 998244353 in
    let (+@) a b = (a + b) mod m in

    for i = 0 to n - 1 do
        let x = a.(i) in
        if x <= s then
            dp.(i + 1).(x) <- dp.(i + 1).(x) +@ (i + 1);
        for j = 0 to s do
            dp.(i + 1).(j) <- dp.(i + 1).(j) +@ dp.(i).(j);
            if j + x <= s then
                dp.(i + 1).(j + x) <- dp.(i + 1).(j + x) +@ dp.(i).(j)
        done
    done;
    let rec loop i acc =
        if i > n then acc else loop (i + 1) (acc +@ dp.(i).(s))
    in
    loop 0 0 |> Printf.printf "%d\n"
)

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


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern

let (h, w) = Scanf.sscanf (read_line ()) "%d %d" @@ fun h w -> (h, w)
let s = Array.init h @@ fun _ -> Array.of_list @@ split_string @@ read_line ()

let rec loop dp i j =
  if i = h then Printf.printf "%d\n" dp.(h - 1).(w - 1)
  else begin
    dp.(i).(j) <- min
      (if i > 0 then (dp.(i - 1).(j) + if s.(i - 1).(j) = "." && s.(i).(j) = "#" then 1 else 0) else max_int)
      (if j > 0 then (dp.(i).(j - 1) + if s.(i).(j - 1) = "." && s.(i).(j) = "#" then 1 else 0) else max_int);
    if j = w - 1 then loop dp (i + 1) 0 else loop dp i (j + 1)
  end

let () =
  let dp = Array.init h @@ fun _ -> Array.make w 0 in
  if s.(0).(0) = "#" then dp.(0).(0) <- 1;
  loop dp 0 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 = 1 then 1
    else if h = 1 then 1
    else 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


let eqs a b o =
  let a, b, o = if o < 0 then b, a, -o else a, b, o in
  let rec f i =
    if i+o >= String.length a || i >= String.length b then true
    else (a.[i+o] = '?' || b.[i] = '?' || a.[i+o] = b.[i]) && f (i+1)
  in f 0

let max3 a b = max (max a b)
let min3 a b = min (min a b)

let () =
  Scanf.scanf "%s %s %s" @@ fun a b c ->
  let la, lb, lc = String.(length a, length b, length c) in
  let ab = Array.init 4001 (fun i -> eqs a b (i-2000)) in
  let bc = Array.init 4001 (fun i -> eqs b c (i-2000)) in
  let ac = Array.init 4001 (fun i -> eqs a c (i-2000)) in

  let ans = ref 6000 in
  for i = -4000 to 4000 do
    if abs i > 2000 || ab.(i+2000) then
      for j = -4000 to 4000 do
          if (abs j > 2000 || ac.(j+2000)) &&
             (abs (j-i) > 2000 || bc.(j-i+2000))
          then
            ans := min !ans (max3 la (i+lb) (j+lc) - min3 0 i j)
      done;
  done;
  Printf.printf "%d\n" !ans

Score : 500 points

Problem Statement

Snuke has a string s.
From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows:

Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with ?s.

For example, if s is mississippi, we can choose the substring ssissip and replace its 1-st and 3-rd characters with ? to obtain ?s?ssip.

You are given the strings a, b, and c.
Find the minimum possible length of s.

Constraints

1 \leq |a|, |b|, |c| \leq 2000

a, b, and c consists of lowercase English letters and ?s.

Input

Input is given from Standard Input in the following format:

a
b
c

Output

Print the minimum possible length of s.

Sample Input 1

a?c
der
cod

Sample Output 1

7

For example, s could be atcoder.

Sample Input 2

atcoder
atcoder
???????

Sample Output 2

7

a, b, and c may not be distinct.


let s = read_line()

let rec f i b =
  try
    let c = s.[i] in
    if b then
      begin
        if c <> 'h' then "No"
        else f (i+1) false
      end
    else
      if c = 'i' then f (i+1) true
      else "No"
  with Invalid_argument _ -> if b then "Yes" else "No"

let () = print_endline (f 0 true)

Score : 100 points

Problem Statement

A Hitachi string is a concatenation of one or more copies of the string hi.

For example, hi and hihi are Hitachi strings, while ha and hii are not.

Given a string S, determine whether S is a Hitachi string.

Constraints

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

S is a string consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is a Hitachi string, print Yes; otherwise, print No.

Sample Input 1

hihi

Sample Output 1

Yes

hihi is the concatenation of two copies of hi, so it is a Hitachi string.

Sample Input 2

hi

Sample Output 2

Yes

Sample Input 3

ha

Sample Output 3

No


let s = read_line()

let rec f i b =
  try
    let c = s.[i] in
    if b then
      begin
        if c <> 'h' then "No"
        else f (i+1) false
      end
    else
      if c = 'i' then f (i+1) true
      else "No"
  with Invalid_argument _ -> "Yes"

let () = print_endline (f 0 true)


let () = Scanf.scanf "%s" @@ fun s ->
  if s = "AAA" || s = "BBB"
  then print_endline "Yes"
  else print_endline "No"

Score : 100 points

Problem Statement

In AtCoder City, there are three stations numbered 1, 2, and 3.

Each of these stations is operated by one of the two railway companies, A and B. A string S of length 3 represents which company operates each station. If S_i is A, Company A operates Station i; if S_i is B, Company B operates Station i.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of S is A or B.

|S| = 3

Input

Input is given from Standard Input in the following format:

S

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station 1 and 3, while Company B operates Station 2.

There will be a bus service between Station 1 and 2, and between Station 2 and 3, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station 1 and 2, while Company A operates Station 3.

There will be a bus service between Station 1 and 3, and between Station 2 and 3, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.


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

Score : 200 points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation 10^{100} times:

Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.

How many blue balls will be there among the first N balls in the row of balls made this way?

Constraints

1 \leq N \leq 10^{18}

A, B \geq 0

0 < A + B \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

Print the number of blue balls that will be there among the first N balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.


let s, q = Scanf.scanf " %s %d" @@ fun a b -> a, b
let r, fs, bs = ref 0, ref [], ref []
let g s = String.(init (length s) @@ fun i -> s.[length s - i - 1])
let _ = Scanf.(for _ = 1 to q do scanf " %d" @@ fun t -> if t = 1 then r := !r lxor 1 else scanf " %d %s" @@ fun f c -> if !r = f - 1 then fs := c :: !fs else bs := c :: !bs done); List.(if !r = 0 then bs := rev !bs else fs := rev !fs); let f, b = String.(concat "" !fs, concat "" !bs) in print_endline @@ if !r = 0 then f ^ s ^ b else b ^ g s ^ f

Score : 400 points

Problem Statement

Takahashi has a string S consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:

If T_i = 1: reverse the string S.

If T_i = 2: An integer F_i and a lowercase English letter C_i are additionally provided.

If F_i = 1 : Add C_i to the beginning of the string S.

If F_i = 2 : Add C_i to the end of the string S.

Help Takahashi by finding the final string that results from the procedure.

Constraints

1 \leq |S| \leq 10^5

S consists of lowercase English letters.

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

T_i = 1 or 2.

F_i = 1 or 2, if provided.

C_i is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

S
Q
Query_1
:
Query_Q

In the 3-rd through the (Q+2)-th lines, Query_i is one of the following:

1

which means T_i = 1, and:

2 F_i C_i

which means T_i = 2.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be Q = 4 operations. Initially, S is a.

Operation 1: Add p at the beginning of S. S becomes pa.

Operation 2: Reverse S. S becomes ap.

Operation 3: Add c at the end of S. S becomes apc.

Operation 4: Reverse S. S becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be Q = 6 operations. Initially, S is a.

Operation 1: S becomes aa.

Operation 2: S becomes baa.

Operation 3: S becomes aab.

Operation 4: S becomes aabc.

Operation 5: S becomes cbaa.

Operation 6: S becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy


open Batteries

let s = read_line ()
let q = read_int ()

let string_rev s =
  let len = String.length s in
  String.init len (fun i -> s.[len - 1 - i])

let add_p result line_list =
    match List.nth line_list 1 with
    | "1" -> (List.nth line_list 2) ^ result
    | _ -> result ^ (List.nth line_list 2)

let change result line =
    match line.[0] with
    | '1' -> string_rev result
    | _ -> add_p result (String.split_on_char ' ' line)

let rec ans r s =
    match s with
    | 0 -> r
    | _ -> ans (change r (read_line())) (s-1)

let _ = print_endline (ans s q)


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

let () = Scanf.scanf "%d %d\n%s" @@ fun n p s ->
  if p = 2 || p = 5 then begin
    Printf.printf "%d\n" @@
    Array.fold_left ( + ) 0 @@
    Array.init n @@ fun i ->
      if 0 < (Char.code s.[i] - Char.code '0') mod p
      then 0
      else i + 1
  end else begin
    let ( +^ ) x y = (x + y) mod p in
    let ( *^ ) x y = (x * y) mod p in
    let acc = Array.make (n + 1) 0 in
    for i = 0 to n - 1 do
      acc.(i + 1) <- acc.(i) +^ power ( *^ ) (Char.code s.[i] - Char.code '0') 10 ((p - 2) * (i + 1))
    done;
    let ms = Array.make p 0 in
    Array.iter (fun m -> ms.(m) <- 1 + ms.(m)) acc;
    Printf.printf "%d\n" @@
    Array.fold_right (fun m -> ( + ) @@ m * (m - 1) / 2) ms 0
  end

Score : 500 points

Problem Statement

Takahashi has a string S of length N consisting of digits from 0 through 9.

He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in S are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

S consists of digits.

|S| = N

2 \leq P \leq 10000

P is a prime number.

Input

Input is given from Standard Input in the following format:

N P
S

Output

Print the number of non-empty (contiguous) substrings of S that are divisible by P when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here S = 3543. There are ten non-empty (contiguous) substrings of S:

3: divisible by 3.

35: not divisible by 3.

354: divisible by 3.

3543: divisible by 3.

5: not divisible by 3.

54: divisible by 3.

543: divisible by 3.

4: not divisible by 3.

43: not divisible by 3.

3: divisible by 3.

Six of these are divisible by 3, so print 6.

Sample Input 2

4 2
2020

Sample Output 2

10

Here S = 2020. There are ten non-empty (contiguous) substrings of S, all of which are divisible by 2, so print 10.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68


Scanf.sscanf (read_line ()) "%d %d" (fun n p ->
    let s = read_line () in
    if p = 2 || p = 5 then (
        let rec loop i d acc =
            if i = n then acc else (
                let c = int_of_char s.[i] - int_of_char '0' in
                let d = if c mod p = 0 then d + 1 else d in
                let acc = acc + d in
                loop (i + 1) d acc
            )
        in
        loop 0 0 0 |> Printf.printf "%d\n"
    ) else (
        let dp = Array.make p 0 in
        dp.(0) <- 1;
        let rec loop i mul prev acc =
            if i < 0 then acc else
                let c = int_of_char s.[i] - int_of_char '0' in
                let d = (c * mul + prev) mod p in
                let () = dp.(d) <- dp.(d) + 1 in
                loop (i - 1) ((mul * 10) mod p) d (acc + dp.(d) - 1)
        in
        loop (n - 1) 1 0 0 |> Printf.printf "%d\n"
    )
)


Scanf.sscanf (read_line ()) "%d %d" (fun n p ->
    let s = read_line () in
    if p mod 2 = 0 || p mod 5 = 0 then (
        let dp = Array.make_matrix 2 p 0 in
        let rec loop i acc =
            if i = n then acc else (
                let cur = i mod 2 in
                let next = 1 - cur in
                let c = int_of_char s.[i] - int_of_char '0' in
                for j = 0 to p - 1 do dp.(next).(j) <- 0 done;
                for j = 0 to p - 1 do
                    let v = (j * 10 + c) mod p in
                    dp.(next).(v) <- dp.(next).(v) + dp.(cur).(j)
                done;
                dp.(next).(c mod p) <- dp.(next).(c mod p) + 1;
                loop (i + 1) (acc + dp.(next).(0))
            )
        in
        loop 0 0 |> Printf.printf "%d\n"
    ) else (
        let dp = Array.make p 0 in
        let rec loop i mul shift acc =
            if i = n then acc else
                let c = int_of_char s.[i] - int_of_char '0' in
                let d = (c * mul + shift) mod p in
                let () = dp.(d) <- dp.(d) + 1 in
                let mul = (mul * 10) mod p in
                let nextshift = (shift * 10 + c) mod p in
                loop (i + 1) mul nextshift (acc + dp.(shift mod p))
        in
        loop 0 1 0 0 |> Printf.printf "%d\n"
    )
)