open Batteries
module EnumL = Enum.Labels
open Tuple

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

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

let scan_lines n fmt f =
  List.Labels.map
    (List.range 1 `To n)
    ~f:(fun _ -> scan fmt f)
  |> List.enum

let scan_list cnv =
  let l = read_line ()
          |> String.split_on_char ' '
          |> List.map cnv in
  List.enum l

let scan_lists n cnv =
  let ll = List.Labels.map (List.range 1 `To n)
      ~f:(fun _ -> scan_list cnv) in
  List.enum ll

let scan_array n m e conv =
  let arr = Array.make_matrix n m e in
  EnumL.iter (0 --^ n)
    ~f:(fun i -> arr.(i) <- Array.of_enum @@ scan_list conv);
  arr

let (n, m) = scan "%d %d" Tuple2.make
let lights = scan_lists m Int.of_string
let onoff = scan_list Int.of_string

let rec superset e =
  match Enum.get e with
  | None -> List.enum [Enum.empty ()]
  | Some v ->
    let f = superset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun f -> let h = Enum.clone f in push h v; h)
    |>  Enum.append g

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

let () =
  let sets = superset (1 -- n) in
  EnumL.map sets ~f:(fun set ->
      (* EnumL.map (Enum.combine (Enum.clone onoff) (Enum.clone lights)) *)
      EnumL.map (Enum.combine (Enum.clone onoff, Enum.clone lights))
        ~f:(fun (b, l) ->
            let n = Enum.count @@
              intersection set @@ Enum.skip 1 @@ Enum.clone l
            in n mod 2 = b)
      |> EnumL.for_all ~f:((=) true))
  |> EnumL.filter ~f:((=) true)
  |> Enum.count
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


open Batteries
module EnumL = Enum.Labels
open Tuple

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

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

let scan_lines n fmt f =
  List.Labels.map
    (List.range 1 `To n)
    ~f:(fun _ -> scan fmt f)
  |> List.enum

let scan_list cnv =
  read_line ()
  |> String.split_on_char ' '
  |> List.map cnv
  |> List.enum

let scan_lists n cnv =
  List.Labels.map (List.range 1 `To n)
    ~f:(fun _ -> scan_list cnv)
  |> List.enum

let scan_array n m e conv =
  let arr = Array.make_matrix n m e in
  EnumL.iter (0 --^ n)
    ~f:(fun i -> arr.(i) <- Array.of_enum @@ scan_list conv);
  arr

let rec zip xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys ->
    (x, y) :: zip xs ys

let (n, m) = scan "%d %d" Tuple2.make
let lights = scan_lists m Int.of_string
let onoff = scan_list Int.of_string

let rec superset = function
  | [] -> [[]]
  | x :: xs ->
    let ps = superset xs in
    ps @ List.map (fun ss -> x :: ss) ps

let rec intersection l = function
  | [] -> []
  | h::t ->
    if List.exists ((=) h) l then
      h::intersection l t
    else intersection l t

let () =
  let sets = List.enum @@ superset (List.range 1 `To n) in
  EnumL.map sets ~f:(fun set ->
      EnumL.map (Enum.combine ((Enum.clone onoff), (Enum.clone lights)))
        ~f:(fun (b, l) ->
            let n = List.length @@
              intersection set @@ List.of_enum @@ Enum.take 1 @@ Enum.clone l
            in n mod 2 = b)
      |> EnumL.for_all ~f:((=) true))
  |> EnumL.filter ~f:((=) true)
  |> Enum.count
  |> Printf.printf "%d\n"

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

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.


(* O(k M^2) (M = min n k) *)
Scanf.scanf " %d %d" @@ fun n k ->
  let vs = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0 in
  let ans = ref 0 in
  let m = min n k in
  for l = 0 to m do
    for r = 0 to m - l do
      let c = l + r in
      for b = 0 to k - c do
        if b <= c then
          let a = Array.make c 0 in
          let a_i = ref 0 in
          let rec loop acc f i rest =
            if rest <= 0 then acc
            else
              let v = vs.(f i) in
              a.(!a_i) <- v; incr a_i;
              loop (acc + v) f (i + 1) (rest - 1) in
          let sum = ref @@ loop 0 ((+) 0) 0 l + loop 0 ((-) (n - 1)) 0 r in
          Array.sort (-) a;
          for i = 0 to b - 1 do
            sum := !sum - a.(i)
          done;
          ans := max !ans !sum
      done
    done
  done;
  Printf.printf "%d\n" !ans

Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


type t =
  | Leaf
  | Node of body
and body = { left : t; right : t; data : int; l : int; r : int }

let rec drop n l =
  if n = 0 then l else drop (n - 1) (List.tl l)

let rec init l n xs =
  if n = 1
  then
    (Node
      { left = Leaf;
        right = Leaf;
        data = max_int; l;
        r = List.hd xs }, List.hd xs)
  else
    let (left, m) = init l (n / 2) xs in
    let (right, r) = init m ((n + 1) / 2) (drop (n / 2) xs) in
    (Node { left; right; data = max_int; l; r }, r)
let init (x :: xs) = fst @@ init x (List.length xs) xs

let rec update a b x = function
  | Leaf -> Leaf
  | Node ({ left; right; data; l; r } as t) ->
      if b <= l || r <= a || t.data <= x
      then Node t
      else begin
        if a <= l && r <= b
        then Node { t with data = min x t.data }
        else Node { t with left = update a b x left; right = update a b x right }
      end

let rec query acc i = function
  | Leaf -> acc
  | Node { left; right; data; l; r } ->
      if i < l || r <= i
      then acc
      else query (query (min acc data) i left) i right
let query = query max_int

let () = Scanf.scanf "%d %d\n" @@ fun n q ->
  let stxs =
    Array.init n @@ fun _ ->
      Scanf.scanf "%d %d %d\n" @@ fun s t x -> s, t, x in
  let tr =
    Array.fold_right (fun (s, t, x) -> update (s - x) (t - x) x) stxs @@
    init @@
    List.sort_uniq compare @@
    Array.fold_left (fun acc (s, t, x) -> s - x :: t - x :: acc) [] stxs in
  for i = 0 to q - 1 do
    Printf.printf "%d\n" @@ Scanf.scanf "%d\n" @@ fun d ->
      let ans = query d tr in
      if ans = max_int then -1 else ans
  done

Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

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

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.


let a = ref 0;;
let b = ref 0;;
Scanf.scanf "%d %d" (fun x y -> a := x; b := y);;

let p =
  if !a >= 13 then !b
  else if !a >= 6 then !b / 2
  else 0 in
  print_endline(string_of_int p)
;;

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


open Printf
open Scanf

let solve a b =
  if a >= 13 then b
  else if a >= 6 then b / 2
  else 0

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


let answer a b =
  if a >= 13 then b
  else
    if a <= 6 then 0
    else
      b / 2

      let () = Scanf.scanf "%d %d" (fun a b -> print_endline (string_of_int (answer a b)))


let r, d, x2000 = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let x = ref x2000
let _ = for _ = 1 to 10 do x := r * !x - d; Printf.printf "%d\n" !x done

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


let () =
  let r, d, x = Scanf.scanf "%d %d %d\n" (fun a b c -> a, b, c) in
  let rec f x i = if i = 10 then [] else string_of_int (r*x-d) :: f (r*x-d) (i+1) in
  let lst = (f x 0) in List.iter print_endline lst


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

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

let plst = List.init m (
        fun _ ->
                Scanf.sscanf (read_line ()) "%d %d" (
                        fun l r ->
                                (l, r)
                )
)

let rec f lst =
        match lst with
                  [] -> (1, n)
                | (lf, rf) :: rest ->
                        let (lr, rr) = f rest in
                                if lf < lr && rf < rr then
                                        (lr, rf)
                                else
                                if lf < lr && rf > rr then
                                        (lr, rr)
                                else
                                if lf > lr && rf < rr then
                                        (lf, rf)
                                else
                                        (lf, rr)

let () =
        (
                let (l, r) = f plst in
                        if r < l then
                                0
                        else
                                List.range l `To r
                                |> List.length
        ) |> Printf.printf "%d\n"
(*

let slst = List.init m (
        fun _ ->
                Scanf.sscanf (read_line ()) "%d %d" (
                        fun l r ->
                                (l, r)
                )
) |> List.map (fun (l, r) -> Set.of_list (List.range l `To r))

let rec f lst =
        match lst with
                  [] -> Set.of_list []
                | first :: [] ->
                        first
                | first :: rest ->
                        Set.intersect first (f rest)

let () =
        f slst
        |> Set.cardinal
        |> Printf.printf "%d\n"

*)

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


let () =
    let main () =
        let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> a, b) in
        let rec loop i mmin mmax =
            if i = 0 then max 0 (mmax - mmin + 1) else
                let l, r = Scanf.sscanf (read_line ()) "%d %d" (fun l r -> l, r) in
                loop (i - 1) (max mmin l) (min mmax r)
        in
        Printf.printf "%d\n" (loop m 1 n)
    in
    main ()


module Set_ii = Set.Make(struct
  type t = int * int
  let compare (a, b) (d, e) =
    if a <> d then a-d else b-e
end)
module S = Set_ii

type state = { tl: Set_ii.t; tr: Set_ii.t; sl: int; sr: int; b: int }

let update {tl; tr; sl; sr; b=tb} n a b =
  let (vl, _ as el), (vr, _ as er) = S.max_elt tl, S.min_elt tr in
  let tl, ((vm, _) as m), tr, sl, sr =
    if a <= vl then
      let tl' = S.remove el tl in
      (S.add (a, n) tl', el, tr, sl-vl+a, sr)
    else if a <= vr then
      (tl, (a, n), tr, sl, sr)
    else
      let tr' = S.remove er tr in
      (tl, er, S.add (a, n) tr', sl, sr-vr+a)
  in
  if S.cardinal tl > S.cardinal tr then
    {tl; tr = S.add m tr; sl = sl; sr = sr+vm; b = tb+b}
  else
    {tl = S.add m tl; tr; sl = sl+vm; sr; b = tb+b}

let calc {tl; tr; sl; sr; b} =
  let x, _ = S.max_elt tl in
  let _, _ = S.min_elt tr in
  let sum = (S.cardinal tl - S.cardinal tr) * x - sl + sr + b in
  (x, sum)

let rec loop n st =
  if n = 0 then ()
  else Scanf.scanf " %d" @@ function
  | 1 -> Scanf.scanf " %d %d" (update st n) |> loop (n-1)
  | _ -> begin
      let x, fx = calc st in Printf.printf "%d %d\n" x fx;
      loop (n-1) st
    end

let inf = 1000000000000
let _ = Scanf.scanf "%d" @@ fun q -> loop q {
  tl = S.singleton (-inf, -inf) ; tr = S.singleton (inf, inf);
  sl = 0; sr = 0; b = 0
}

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

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

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000


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

let add a s =
  IntMap.add a (1 + try IntMap.find a s with Not_found -> 0) s

let remove a s =
  match IntMap.find a s with
  | exception Not_found -> s
  | 1 -> IntMap.remove a s
  | n -> IntMap.add a (n - 1) s

let _ =
  Array.fold_left (fun (odd, acc, (q, q')) ->
    let (m, _) = IntMap.max_binding q in
    function
    | None ->
        Printf.printf "%d %d\n" m acc;
        (odd, acc, (q, q'))
    | Some (a, b) ->
        let (m', _) = IntMap.min_binding q' in
        not odd,
        (acc + b +
          if odd then
            abs (m - a)
          else
            if a <= m then
              m - a
            else if m' <= a then
              a - m'
            else 0),
        if a < m then
          let q = add a q in
          if odd then
            (remove (fst (IntMap.max_binding q)) q, add (fst (IntMap.max_binding q)) q')
          else
            (q, q')
        else
          let q' = add a q' in
          if odd then
            (q, add a q')
          else
            (add (fst (IntMap.min_binding q')) q), remove (fst (IntMap.min_binding q')) q')
  (false, 0, (IntMap.singleton min_int 1, IntMap.singleton max_int 1)) @@
  Scanf.scanf "%d " @@ fun q ->
    Array.init q @@ fun _ ->
      Scanf.scanf "%d " @@ function
        | 2 -> None
        | 1 -> Scanf.scanf "%d %d " @@ fun a b -> Some (a, b)


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

let add a s =
  IntMap.add a (1 + try IntMap.find a s with Not_found -> 0) s

let remove a s =
  match IntMap.find a s with
  | exception Not_found -> s
  | 1 -> IntMap.remove a s
  | n -> IntMap.add a (n - 1) s

let _ = Scanf.scanf "%d\n1 %d %d\n" @@ fun q a b ->
  Array.fold_left (fun (acc, (n, n', q, q', sum, sum')) ->
    let (m, _) = IntMap.max_binding q in
    function
    | None ->
        Printf.printf "%d %d\n" m
          (acc + (n * m - sum) + (sum' - n' * m));
        (acc, (n, n', q, q', sum, sum'))
    | Some (a, b) ->
        acc + b,
        if a < m then
          if n <= n'
          then (n + 1, n', add a q, q', sum + a, sum')
          else (n, n' + 1, add a (remove m q), add m q', sum + a - m, sum' + m)
        else
          if n' < n
          then (n, n' + 1, q, add a q', sum, sum' + a)
          else (n + 1, n', add m q, add a (remove m q'), sum + m, sum' + a - m))
  (b, (1, 0, IntMap.singleton a 1, IntMap.empty, a, 0)) @@
  Array.init (q - 1) @@ fun _ ->
    Scanf.scanf "%d " @@ function
      | 2 -> None
      | 1 -> Scanf.scanf "%d %d " @@ fun a b -> Some (a, b)


let n, k, s = Scanf.scanf " %d %d %s" @@ fun a b c -> a, b - 1, Bytes.of_string c
let _ = Bytes.set s k @@ Char.lowercase @@ Bytes.get s k; print_endline @@ Bytes.to_string s

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


open Printf open Scanf
open Array

let () = scanf " %d %d %s" @@ fun n k s ->
  let a = init n (fun i -> s.[i]) in
  a.(k-1) <- Char.lowercase @@ a.(k-1);
  iter (print_char) a


let x, y = Scanf.scanf " %2d%2d" @@ fun a b -> a, b
let f n = n < 1 || n > 12
let _ = print_endline @@
  if f x then if f y then "NA" else "YYMM"
  else if f y then "MMYY" else "AMBIGUOUS"

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


Scanf.scanf "%s" @@ fun s ->
  let n1 = String.sub s 0 2 |> int_of_string in
  let n2 = String.sub s 2 2 |> int_of_string in
  print_endline @@ if n1 > 12 || n1 = 0 then
      if n2 > 12 || n2 = 0 then
        "NA"
      else
        "YYMM"
    else
      if n2 > 12 || n2 = 0 then
        "MMYY"
      else
        "AMBIGUOUS"


let () = Scanf.scanf "%2d%2d" @@ fun up low ->
  let yymm = 1 <= low && low <= 12 in
  let mmyy = 1 <= up && up <= 12 in
  print_endline @@
  match yymm, mmyy with
  | true, true -> "AMBIGUOUS"
  | false, false -> "NA"
  | true, false -> "YYMM"
  | false, true -> "MMYY"


let ceil_exponent i k =
  let rec ceil_exponent' i k res =
    if i * (1 lsl res) >= k then res
    else ceil_exponent' i k (res + 1) in
  ceil_exponent' i k 0
;;

let p n = 0.5 ** n;;

let solve n k =
  let rec sum' n k res =
    if n = 0 then res
    else sum' (n - 1) k (res +. (ceil_exponent n k |> float_of_int |> p)) in
  (sum' n k 0.) /. (float_of_int n)
;;

let () = Scanf.scanf "%d %d" (fun n k -> print_float (solve n k));;

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


let f i k =
  let res = ref 0 in
  while i * (1 lsl !res) < k do
    res := !res + 1
  done;
  !res
;;

let g n = 0.5 ** n;;

let rec sum n k p = if n = 0 then 0. else sum (n - 1) k (p +. (f n k |> float_of_int |> g));;

let sum n k = (sum n k 0.) /. (float_of_int n);;

let () = Scanf.scanf "%d %d" (fun n k -> print_float (sum n k));;


let () =
  Scanf.scanf "%d %d" @@ fun n k ->
  Array.init n (fun i ->
    let rec aux c x = if x >= k then c else aux (c+1) (2*x) in
    0.5 ** float_of_int (aux 0 (i+1)))
  |> Array.fold_left (+.) 0.
  |> fun p -> Printf.printf "%.11f\n" (p /. float_of_int n)


(* O(n) *)
Scanf.scanf " %d" @@ fun n ->
  let g = Array.make n [] in
  for _ = 1 to n - 1 do
    Scanf.scanf " %d %d %d" @@ fun u v w ->
      let u, v = u - 1, v - 1 in
      g.(u) <- (v, w mod 2 = 0) :: g.(u);
      g.(v) <- (u, w mod 2 = 0) :: g.(v);
  done;
  let cs = Array.make n 0 in
  let rec dfs v p c =
      cs.(v) <- c;
      let f (v2, w) = if v2 <> p then dfs v2 v @@ if w then c else -c in
      List.iter f g.(v) in
  dfs 0 (-1) 1;
  Array.iter (fun c -> max 0 c |> Printf.printf "%d\n") cs

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

5
2 5 2
2 3 10
1 3 8
3 4 2

Sample Output 2

1
0
1
0
1


type color = Black | White
type node = {color: color option; children: (int * int) list}

let from_white tree =
  let rec inner aux idx =
    match tree.(idx).color with
    | Some _ -> ()
    | None ->
       if aux mod 2 = 0 then
         begin
           tree.(idx) <- {tree.(idx) with color = Some White};
           List.iter (fun (idx', w) -> inner (aux + w) idx') tree.(idx).children
         end
       else
         begin
           tree.(idx) <- {tree.(idx) with color = Some Black};
           List.iter (fun (idx', w) -> inner (aux + w) idx') tree.(idx).children
         end
  in inner 0 0; tree

let str_of_color = function None -> "N" | Some Black -> "1" | Some White -> "0"

let tree_to_answer tree =
  Array.iter (fun node -> node.color |> str_of_color |> print_endline) tree

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let tree = Array.make n {color = None; children = []} in
  for i = 1 to n - 1 do
    Scanf.scanf "%d %d %d\n"
      (fun u v w ->
        tree.(u-1) <- {color=None; children = (v-1, w)::tree.(u-1).children};
        tree.(v-1) <- {color=None; children = (u-1, w)::tree.(v-1).children}
      )
  done;
  from_white tree
  |> tree_to_answer


let () =
  Scanf.scanf "%d" @@ fun n ->
  let g = Array.init n (fun _ -> []) in
  for _ = 2 to n do
    Scanf.scanf " %d %d %d" @@ fun u v w ->
    let u, v = u-1, v-1 in
    g.(u) <- (v, w mod 2) :: g.(u);
    g.(v) <- (u, w mod 2) :: g.(v);
  done;
  let cs = Array.make n (-1) in
  let rec dfs u c p =
    cs.(u) <- c;
    g.(u) |> List.iter (fun (v, w) -> if p <> v then dfs v ((c + w) mod 2) u)
  in
  dfs 0 0 (-1);
  Array.iter (Printf.printf "%d\n") cs;


(* 配列版素集合データ構造 *)
module UnionFind : sig
  type t

  module Class : sig
    type t
    val compare : t -> t -> int
  end

  (* n要素の素集合データ構造を作る *)
  val make : int -> t
  (* 要素がどの集合に属するか調べる *)
  (* 要素は0からn-1の整数である必要がある *)
  val find : t -> int -> Class.t
  (* 与えられた集合同士を合併する *)
  (* 破壊的操作であるため注意 *)
  val unite : t -> Class.t -> Class.t -> unit
  (* 与えられた集合に属する要素の数を求める *)
  val cardinal : t -> Class.t -> int
end = struct
  type t = int array

  module Class = struct
    type t = int
    let compare = compare
  end

  let make n = Array.make n (-1)

  let rec find uf x =
    if uf.(x) < 0 then x
    else begin
      let y = find uf uf.(x) in
      uf.(x) <- y; y
    end

  let unite uf x y =
    if x <> y then begin
      let x, y = if uf.(x) <= uf.(y) then x, y else y, x in
      uf.(x) <- uf.(x) + uf.(y);
      uf.(y) <- x
    end

  let cardinal uf x = ~- (uf.(x))
end

module ClassSet = Set.Make (UnionFind.Class)

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let uf = UnionFind.make n in
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d %d\n" @@ fun x y _ ->
      UnionFind.unite uf
        (UnionFind.find uf (x - 1))
        (UnionFind.find uf (y - 1))
  done;
  Printf.printf "%d\n" @@
  ClassSet.cardinal @@
  Array.fold_right ClassSet.add (Array.init n @@ UnionFind.find uf) ClassSet.empty

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


(* O(n) *)
let solve n k =
  let rec find acc i =
    if i + k - 1 > n then
      acc
    else
      find (acc + 1) (i + 1)
  in
    find 0 1

let read_ints () = read_line () |> Str.split (Str.regexp " ") |> List.map int_of_string

let _ =
  match read_ints () with
  | [n; k] -> solve n k |> string_of_int |> print_endline
  | _ -> ()

Score : 100 points

Problem Statement

Snuke has N integers: 1,2,\ldots,N.
He will choose K of them and give those to Takahashi.

How many ways are there to choose K consecutive integers?

Constraints

All values in input are integers.

1 \leq K \leq N \leq 50

Input

Input is given from Standard Input in the following format:

N K

Output

Print the answer.

Sample Input 1

3 2

Sample Output 1

2

There are two ways to choose two consecutive integers: (1,2) and (2,3).

Sample Input 2

13 3

Sample Output 2

11


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

let () =
  let ans = ref 0 in
  for i = 0 to n / r do
    for j = 0 to n / g do
      let sum = r * i + j * g in
      if sum <= n && (n - sum) mod b = 0 then ans := !ans + 1
    done
  done;
  Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


open Printf open Scanf
open Array

let print_list f ls = List.iter (fun v -> printf "%s " @@ f v) ls; print_newline ()

(* rosetta code *)
let count_substring str sub =
  let sub_len = String.length sub in
  let len_diff = (String.length str) - sub_len
  and reg = Str.regexp_string sub in
  let rec aux i n =
    if i > len_diff then n else
      try
        let pos = Str.search_forward reg str i in
        aux (pos + sub_len) (succ n)
      with Not_found -> n
  in
  aux 0 0

let () = scanf " %d" @@ fun n ->
  let arr = init n (fun _ -> scanf " %s" @@ fun s -> s)
  in
  let kba,kbx,kxa,krest = fold_left (fun (kba,kbx,kxa,krest) s ->
    let bx = s.[0] = 'B' in
    let xa = s.[String.length s-1] = 'A' in
    let ab = bx && xa in
    let kba = if ab then kba + 1 else kba in
    let kbx = if not ab then (
      if bx then kbx+1 else kbx
    ) else kbx in
    let kxa = if not ab then (
      if xa then kxa+1 else kxa
    ) else kxa in
    let krest = krest + count_substring s "AB"
    in
    (kba,kbx,kxa,krest)
  ) (0,0,0,0) arr in
  let hoge =
    if kba >= 1 then (
      let pair_ba = kba - 1 in
      let res = 0 in
      let res,kbx =
        if kbx > 0 then res+1,kbx-1 else res,kbx in
      let res,kxa =
        if kxa > 0 then res+1,kxa-1 else res,kxa in
      pair_ba + res + min kbx kxa
    ) else (
      min kbx kxa
    ) in
  print_int @@ krest + hoge

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


(* O(|s|) *)
let string_count s sub =
  let n = String.length s in
  let sub_len = String.length sub in
  let reg = Str.regexp sub in
  let rec loop acc i =
    try
      if i >= n then
        acc
      else
        let j = Str.search_forward reg s i + sub_len in
        loop (acc + 1) j
    with
    | _ -> acc
  in
    loop 0 0

(* O(n^2) *)
let solve n ss =
  let b_start, a_end, both, ab = List.fold_left
    (fun (b_start, a_end, both, ab) s ->
      let count = string_count s "AB" in
      let new_ab = ab + count in
      let starts_b = s.[0] = 'B' and ends_a = s.[String.length s - 1] = 'A' in
      let new_b_start = if starts_b then b_start + 1 else b_start in
      let new_a_end = if ends_a then a_end + 1 else a_end in
      if starts_b && ends_a then
        new_b_start - 1, new_a_end - 1, both + 1, new_ab
      else
      new_b_start, new_a_end, both, new_ab)
    (0, 0, 0, 0)
    ss
  in
    let pair = min b_start a_end in
    let need = max b_start a_end - pair in
    let addition = if both <= need then
        pair + both
      else
        pair + need + (both - need + 1) / 2 in
    addition + ab

(* O(n) *)
let rec fold_btw f a i n = if i >= n then a else fold_btw f (f a i) (i + 1) n
let fold_int f a n = fold_btw f a 0 n

let _ =
  let n = read_int () in
  fold_int
    (fun acc _ -> read_line () :: acc)
    []
    n |> solve n |> string_of_int |> print_endline


let _ = Scanf.sscanf (read_line ()) "%d %d %d" (fun a b t ->
  let rec generate s =
    match s with
    | s when (s * a) > t -> 0
    | _ -> b + generate (s+1)
  in print_endline (string_of_int (generate 1))
)

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


Scanf.scanf "%d %d %d" @@ fun a b t -> Printf.printf "%d\n" @@ t / a * b


let () = Scanf.scanf "%d\n" @@ fun n ->
  let vs = Array.init n @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let cs = Array.init n @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let ans = Array.fold_left (fun res i -> res + max 0 (vs.(i) - cs.(i)))
    0 @@ Array.init n Fun.id in
  Printf.printf "%d\n" ans

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

The output may not fit into a 32-bit integer type.


let solve n s k	=
let change_string x = if s.[k-1] =  x then s.[k-1] else '*' in
String.map change_string s

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

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

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

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


let solve n = 1

type mode = CSharp | FSharp

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let ar = Array.make (n+1) '#' in
  let cnt = ref 0 in
  for i = 0 to n - 1 do
    Scanf.scanf (if i <> n-1 then "%c" else "%c\n") (fun c -> ar.(i) <- c)
  done;
  let left_sharp = ref 0 in
  let mode = ref CSharp in
  let tmp = ref 0 in
  for i = 0 to n - 1 do
    match !mode with
    | CSharp ->
       if ar.(i) = '#' && ar.(i + 1) = '.' then (left_sharp := !left_sharp + 1; mode := FSharp)
       else if ar.(i) = '#' then left_sharp := !left_sharp + 1
    | FSharp ->
       begin
         if i = n - 1 && ar.(i) = '.' then (tmp := !tmp + 1; cnt := !cnt + (min !tmp !left_sharp))
         else if i = n - 1 then cnt := !cnt + (min !tmp !left_sharp)
         else if ar.(i) = '.' then tmp := !tmp + 1
         else (cnt := !cnt + (min !tmp !left_sharp); left_sharp := 0; tmp := 0; mode := CSharp)
       end
  done;
  print_int !cnt

Score : 300 points

Problem Statement

There are N stones arranged in a row. Every stone is painted white or black.
A string S represents the color of the stones. The i-th stone from the left is white if the i-th character of S is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


let _ =
  let a, b = Scanf.scanf "%d %d" (fun a b -> a, b) in
  let ans =
    if a > b then
      a + (max (a-1) b)
    else b + (max a (b-1))
  in print_int ans

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


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

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


(* O(n) (n = length of list) *)
let rec list_find_fold_left f a = function
| [] -> a, false
| x :: xs ->
  let res, detected = f a x in
  if detected then
    res, detected
  else
    list_find_fold_left f res xs

(* O(n) *)
let can_view i h hs =
  list_find_fold_left
    (fun (res, j) h' ->
      if j >= i then
        (true, j), true
      else
        if h' > h then
          (res, j), true
        else
          (res, j + 1), false)
    (false, 0)
    hs |> fst |> fst

(* O(n^2) *)
let solve n hs =
  List.fold_left
    (fun (count, i) h ->
      if can_view i h hs then
        count + 1, i + 1
      else
        count, i + 1)
    (0, 0)
    hs |> fst

let read_ints () = read_line () |> Str.split (Str.regexp " ") |> List.map int_of_string

let _ =
  let n = read_int () in
  let hs = read_ints () in
  solve n hs |> string_of_int |> print_endline


let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let h_max = ref 0 in
  let res = ref 0 in
  for i = 0 to n - 1 do
    let h =
      Scanf.scanf (if i <> n - 1 then "%d " else "%d\n") (fun h -> h) in
    if h >= !h_max then (res := !res + 1; h_max := h);
  done;
  Printf.printf "%d\n" !res


let s = read_line () in
let n = String.length s in
let rec fill i k acc =
    if i = n then acc else
        fill (i + 1) (1 - k) (acc + if s.[i] = '0' && k = 0 || s.[i] = '1' && k = 1 then 0 else 1)
in
min (fill 0 0 0) (fill 0 1 0) |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


let calc s k =
  if k = 0 then
    Array.fold_left (fun (v, w) (_, x) -> if x = '1' then max v (w+1), w+1 else v, 1) (0, 0) s |> fst else
  let t = Array.make 101010 0 in
  let ans, _, _, _, _ =
    Array.fold_left (fun (ans, cur, cs, ti, p) (i, x) ->
      match p, x with
      | '1', '1' -> (max ans (cur+1), cur+1, cs+1, ti, '1')
      | '0', '0' -> (max ans (cur+1), cur+1, cs+1, ti, '0')
      | '0', '1' -> begin
        t.(ti) <- cs;
        (max ans (cur+1), cur+1, 1, ti+1, '1')
      end
      | _ (* 1, 0 *) -> begin
        if ti < k then
          (max ans (cur+1), cur+1, cs+1, ti, '0')
        else
          (max ans (cur+1-t.(ti-k)), cur+1-t.(ti-k), cs+1, ti, '0')
      end) (0,0,0,0,'1') s
  in
  ans
let () =
  Scanf.scanf "%d %d %s" @@ fun n k s ->
  let s = Array.init n (fun i -> i, s.[i]) in
  max (calc s k) (calc (Array.map (fun (i, x) -> i, (if x = '0' then '1' else '0')) s) (k-1))
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


let () = Scanf.scanf "%d %d\n%s\n" @@ fun n k s ->
  let seqs =
    Array.of_list @@ List.rev @@
    match
      (* 1111 0000 *)
      Array.fold_left (fun (acc, s) c ->
        match s, c with
        | `Ones n, '1' -> (acc, `Ones (n + 1))
        | `Zeros (n, m), '0' -> (acc, `Zeros (n, m + 1))
        | `Ones n, '0' -> (acc, `Zeros (n, 1))
        | `Zeros (n, m), '1' -> ((n, m) :: acc, `Ones 1)) ([], `Ones 0) @@
      Array.init (String.length s) (String.get s)
    with
    | (acc, `Ones n) -> (n, 0) :: acc
    | (acc, `Zeros (n, m)) -> (n, m) :: acc in
  if Array.length seqs <= k
  then Printf.printf "%d\n" n
  else begin
    let acc = Array.make (Array.length seqs + 1) 0 in
    for i = 0 to Array.length seqs - 1 do
      acc.(i + 1) <- acc.(i) + fst seqs.(i) + snd seqs.(i)
    done;
    Printf.printf "%d\n" @@
    Array.fold_left max (acc.(Array.length seqs) - acc.(Array.length seqs - k)) @@
    Array.init (Array.length seqs - k) @@ fun i ->
      acc.(i + k) - acc.(i) + fst seqs.(i + k)
  end


let five_antennas a b c d e k = if e - a > k then ":(" else "Yay!"

let a = read_int()
let b = read_int()
let c = read_int()
let d = read_int()
let e = read_int()
let k = read_int()

let () = Printf.printf "%s\n" (five_antennas a b c d e k)

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.


let round_up n =
  let r = n mod 10 in
    if r = 0 then n
    else n + 10 - r
;;

let add n =
  let r = n mod 10 in
    if r = 0 then 0
    else 10 - r
;;

let r_max a b c d e =
  max (max (max (max (add a) (add b)) (add c)) (add d)) (add e)
;;

let () = Scanf.scanf "%d\n%d\n%d\n%d\n%d" (fun a b c d e -> (
  (round_up a) + (round_up b) + (round_up c) + (round_up d) + (round_up e) - r_max a b c d e |> print_int
));;

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


let xs = Array.init 5 @@ fun _ -> read_int ()
let ws = Array.map (fun x -> (10 - x mod 10) mod 10) xs
let f = Array.fold_left
let _ = f (+) 0 xs + f (+) 0 ws - f max ws.(0) ws |> Printf.printf "%d\n"


let () = Scanf.scanf "%d %d %d %d %d %d" @@ fun n a b c d e ->
  let m = List.fold_left min max_int [ a; b; c; d; e ] in
  Printf.printf "%d\n" @@ (n + m - 1) / m + 4

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


let constr x y =
  let ly = Array.length y in
  let z = Array.(init (length x * ly) (fun i -> x.(i / ly) + y.(i mod ly))) in
  Array.sort (fun x y -> y - x) z; z
let () =
  Scanf.scanf "%d %d %d %d" @@ fun x y z k ->
  let a = Array.init x (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let b = Array.init y (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let c = Array.init z (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let ab = constr a b in
  let abc = constr (Array.sub ab 0 (min (x * y) k)) c in
  Array.sub abc 0 k |> Array.iter (Printf.printf "%d\n");

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


let () = Scanf.scanf "%d\n%s" @@ fun n s ->
  print_endline @@
  if
    ( < ) 0
    @@ Array.fold_left (fun acc c ->
      acc + if c = 'R' then 1 else -1) 0
    @@ Array.init n @@ String.get s
  then "Yes"
  else "No"

Score : 200 points

Problem Statement

There are N people numbered 1 to N. Each person wears a red hat or a blue hat.

You are given a string s representing the colors of the people. Person i wears a red hat if s_i is R, and a blue hat if s_i is B.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

1 \leq N \leq 100

|s| = N

s_i is R or B.

Input

Input is given from Standard Input in the following format:

N
s

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print Yes; otherwise, print No.

Sample Input 1

4
RRBR

Sample Output 1

Yes

There are three people wearing a red hat, and one person wearing a blue hat.

Since there are more people wearing a red hat than people wearing a blue hat, the answer is Yes.

Sample Input 2

4
BRBR

Sample Output 2

No

There are two people wearing a red hat, and two people wearing a blue hat.

Since there are as many people wearing a red hat as people wearing a blue hat, the answer is No.


let double_helix b =
  if b = "A" then "T"
  else if b = "T" then "A"
  else if b = "G" then "C"
  else "G"

let () = Scanf.scanf "%s" double_helix |> Printf.printf "%s\n"

Score : 100 points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter b as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base b.

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


let _ = String.(map (fun c -> "TGCA".[index "ACGT" c]) @@ read_line ()) |> print_endline


let () =
  print_endline @@
  Scanf.scanf "%c" @@ fun c ->
    match c with
    | 'A' -> "T"
    | 'T' -> "A"
    | 'C' -> "G"
    | 'G' -> "C"
    | _ -> assert false


open Batteries

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

let scan_list cnv =
  read_line ()
  |> String.split_on_char ' '
  |> List.map cnv

let rec zip xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys ->
    (x, y) :: zip xs ys

let s = scan "%s" identity

let () =
  let n = String.length s in
  let length i j =
    let sub = String.slice ~first:i ~last:j s in
    if List.for_all
        (fun c -> c = 'A' || c = 'C' || c = 'G' || c = 'T')
      @@ String.to_list sub then
      String.length sub else 0 in
  let rec aux f i j =
    if j > n then
      if i > n - 1 then []
      else
        aux f (i+1) (i+2)
    else
      (f i j) :: aux f i (j+1)
  in
  Printf.printf "%d\n" @@ List.max @@ aux length 0 1

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


let () =
  Scanf.scanf "%d %d %s" @@ fun n q s ->
  let ss = Array.init (n+1) (fun i ->
    if i > 1 && s.[i-2] = 'A' && s.[i-1] = 'C' then 1 else 0) in
  for i = 1 to n do ss.(i) <- ss.(i) + ss.(i-1); done;
  Array.init q (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y))
  |> Array.iter (fun (l,r) ->
      let v = ss.(r) - ss.(l-1) in
      let v = if l > 1 && s.[l-2] = 'A' && s.[l-1] = 'C' then v-1 else v in
      Printf.printf "%d\n" v)

Score : 300 points

Problem Statement

You are given a string S of length N consisting of A, C, G and T. Answer the following Q queries:

Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and (the empty string), but not AC.

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

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

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query 1: the substring of S starting at index 3 and ending at index 7 is ACTAC. In this string, AC occurs twice as a substring.

Query 2: the substring of S starting at index 2 and ending at index 3 is CA. In this string, AC occurs zero times as a substring.

Query 3: the substring of S starting at index 1 and ending at index 8 is ACACTACG. In this string, AC occurs three times as a substring.


(* O(n^2) *)
let n = Scanf.scanf " %d" @@ (+) 0
let bs = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let search_backi a f =
  let i = ref @@ Array.length a - 1 in
  let found = ref false in
  while not !found && !i >= 0 do if f !i a.(!i) then found := true; decr i done;
  !i + if !found then 1 else 0
let remove a i =
  let a' = Array.make (Array.length a - 1) a.(0) in
  Array.iteri (fun j x -> if j < i then a'.(j) <- x else if j > i then a'.(j - 1) <- x) a;
  a'
let rec f acc a n =
  if n = 0 then acc
  else
    let i = search_backi a (fun i x -> i + 1 = x) in
    if i = -1 then (print_endline "-1"; exit 0)
    else f (a.(i) :: acc) (remove a i) @@ n - 1
let ans = f [] bs n
let _ = ans |> List.iter @@ Printf.printf "%d\n"

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).

You are given a sequence b of length N. Determine if it is possible that a is equal to b after N operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

If there is no sequence of N operations after which a would be equal to b, print -1.
If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence a changes as follows:

After the first operation: (1)

After the second operation: (1,1)

After the third operation: (1,2,1)

Sample Input 2

2
2 2

Sample Output 2

-1

2 cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


let rec for_obvious s = function
  | [] -> false
  | b::bs -> if b > s then true else for_obvious (s + 1) bs

let rec dfs ans left bs s n =
  if bs = [] && left = [] then Some ans
  else if s > n then None
  else
    begin
      match bs with
      | [] -> Some ans
      | b::bs ->
         if b > s then None
         else if b = s then
           begin
             match dfs (b::ans)
                     [] (List.fold_left (fun acc l -> l::acc) bs left)
                     1 (n - 1) with
             | None -> dfs ans (b::left) bs (s + 1) n
             | Some ans -> Some ans
           end
         else dfs ans (b::left) bs (s + 1) n
    end

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let bs = Array.make n 0 in
  for i = 0 to n - 1 do
    Scanf.scanf (if i <> n - 1 then "%d " else "%d\n") (fun b -> bs.(i) <- b)
  done;
  let ls = Array.to_list bs in
  if for_obvious 1 ls then print_int (-1)
  else
    dfs [] [] (Array.to_list bs) 1 n
    |> (function | None -> print_int (-1)
                 | Some ans -> List.iter (fun n -> print_endline @@ string_of_int n) ans)


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let s = read_line () |> split_string |> List.sort compare

let m_1e9 = int_of_float 1e9 + 7
let ( +^ ) x y = (x + y) mod m_1e9
let ( -^ ) x y = x - y + if x < y then m_1e9 else 0
let ( *^ ) x y = ((x mod m_1e9) * (y mod m_1e9)) mod m_1e9

let ss = List.fold_left (fun acc n ->
  match acc with
    | [] -> [(n, 1)]
    | (v, cnt) as t :: xs -> if v = n then (v, cnt + 1) :: xs else (n, 1) :: t :: xs
) [] s

let () =
    Printf.printf "%d\n" @@ List.fold_left (fun sum (_, i) -> sum *^ (i + 1)) 1 ss -^ 1

Score : 200 points

Problem Statement

You are given a string S of length N.
Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

1 \leq N \leq 100000

S consists of lowercase English letters.

|S|=N

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of the subsequences such that all characters are different, modulo 10^9+7.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in S itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17


let rec pow acc n m =
  if m = 0 then acc else pow (acc * n) n (m - 1)

let pow = pow 1

let solve n s =
  let p10_9_7 = (pow 10 9) + 7 in
  let counter = Array.make 26 0 in
  let inc c =
    let i = Char.code c - Char.code 'a' in counter.(i) <- counter.(i) + 1 in
  for ic = 0 to (String.length s) - 1 do
    String.get s ic |> inc
  done;
  let result = ref 1 in
  for i = 0 to 25 do
    if counter.(i) > 0 then
      result := (!result * (counter.(i) + 1)) mod p10_9_7
  done;
  (!result - 1)

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let s = Scanf.scanf "%s\n" (fun s -> s) in
  print_int @@ solve n s


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

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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let cs = Array.make (n + 2) 0 in
  for i = 1 to n do
    Scanf.scanf "%d\n" @@ Array.set cs i
  done;
  let dp = Array.make (n + 2) 1 in
  let acc = Array.make (n + 2) IntMap.empty in
  for i = 1 to n do
    dp.(i) <- dp.(i - 1) +^
      if cs.(i) = cs.(i - 1)
      then 0
      else (try IntMap.find cs.(i) acc.(i - 1) with Not_found -> 0);
    acc.(i) <-
      if cs.(i) = cs.(i + 1)
      then acc.(i)
      else IntMap.add cs.(i) (dp.(i - 1) +^ try IntMap.find cs.(i) acc.(i - 1) with Not_found -> 0) acc.(i - 1)
  done;
  Printf.printf "%d\n" dp.(n)

Score : 700 points

Problem Statement

There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.

Snuke will perform the following operation zero or more times:

Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.

Find the number of possible final sequences of colors of the stones, modulo 10^9+7.

Constraints

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

1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
C_1
:
C_N

Output

Print the number of possible final sequences of colors of the stones, modulo 10^9+7.

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

We can make three sequences of colors of stones, as follows:

(1,2,1,2,2), by doing nothing.

(1,1,1,2,2), by choosing the first and third stones to perform the operation.

(1,2,2,2,2), by choosing the second and fourth stones to perform the operation.

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5


let () = Scanf.scanf " %d %d %d" @@ fun n m c ->
  let bs = List.init m @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let ass = List.init n @@ fun _ ->
    List.init m @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let ans = List.length @@
    List.filter (( < ) 0) @@
    List.map (List.fold_left2 (fun acc b a -> acc + b * a) c bs) ass in
  Printf.printf "%d\n" ans

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


let rec aux m cash drinks shops =
  if drinks >= m then cash
  else
    let a, b = List.hd shops in
    let shops = List.tl shops in
    if m - drinks >= b then aux m (cash + a * b) (drinks + b) shops
    else if m - drinks < b then aux m (cash + a * (m - drinks)) m shops
    else assert false

let _ =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> (n, m)) in
  let pairs = ref [] in
  for i=1 to n do
    Scanf.scanf "%d %d\n" (fun a b -> pairs := (a, b)::!pairs)
  done;
  !pairs
  |> List.fast_sort (fun (a, _) (a', _) -> if a > a' then 1 else if a < a' then -1 else 0)
  |> aux m 0 0
  |> print_int

Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.


Scanf.scanf "%d %d %d" (fun a b k ->
    let rec loop i l =
        if i = 0 then l else
            let l = if a mod i = 0 && b mod i = 0 then i :: l else l in
            loop (i - 1) l
    in
    let l = loop (max a b) [] in
    Printf.printf "%d\n" (Array.of_list (List.rev l)).(k - 1)
)

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


let () =
  Scanf.scanf "%d %d %d" @@ fun a b k ->
  let rec f c i =
    if c = k then i+1
    else if a mod i = 0 && b mod i = 0 then f (c+1) (i-1)
    else f c (i-1)
  in f 0 (min a b) |> Printf.printf "%d\n"


(* O(m α(n)) *)
let n, m = Scanf.scanf " %d %d" @@ fun a b -> a, b
let ab_s = Array.init m @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a - 1, b - 1
let ab_s = Array.init m (fun i -> ab_s.(m - 1 - i))
let ps = Array.make n @@ -1
let rec find x =
  if ps.(x) < 0 then x
  else let y = find ps.(x) in ps.(x) <- y; y
let unite x y =
  let x = find x in
  let y = find y in
  if x = y then false
  else
    (if ps.(x) < ps.(y) then (ps.(x) <- ps.(x) + ps.(y); ps.(y) <- x)
    else (ps.(y) <- ps.(y) + ps.(x); ps.(x) <- y);
    true)
let size x = -ps.(find x)
let v = ref @@ n * (n - 1) / 2
let vs = ref []
let _ =
  let f (a, b) =
    vs := !v :: !vs;
    let x, y = size a, size b in
    if unite a b then v := !v - x * y in
  Array.iter f ab_s;
  List.iter (fun v -> Printf.printf "%d\n" v) !vs

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


(* 素集合データ構造 *)
module UnionFind : sig
  type t

  module Class : sig
    type t
    val to_int : t -> int
    val compare : t -> t -> int
  end

  (* n要素の素集合データ構造を作る *)
  val make : int -> t
  (* 要素がどの集合に属するか調べる *)
  (* 要素は0からn-1の整数である必要がある *)
  val find : t -> int -> Class.t
  (* 与えられた要素が属する集合同士を合併する *)
  val unite : t -> int -> int -> unit
end = struct
  type t = { rank : int array; parent : int array }

  module Class = struct
    type t = int
    let to_int c = c
    let compare = compare
  end

  let make n =
    { rank = Array.make n 0;
      parent = Array.init n @@ fun c -> c }

  let rec find uf x =
    if x = uf.parent.(x) then x
    else begin
      let y = find uf uf.parent.(x) in
      uf.parent.(x) <- y; y
    end

  let unite uf i j =
    let x = find uf i in
    let y = find uf j in
    if x <> y then begin
      if uf.rank.(x) < uf.rank.(y) then uf.parent.(x) <- y
      else begin
        uf.parent.(y) <- x;
        if uf.rank.(x) = uf.rank.(y) then
          uf.rank.(x) <- 1 + uf.rank.(x)
      end
    end
end

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let abs = Array.init m @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
  let uf = UnionFind.make n in
  let cnt = Array.make n 1 in
  let ans = Array.make (m + 1) (n * (n - 1) / 2) in
  for i = m - 1 downto 0 do
    let ca = UnionFind.find uf (fst abs.(i) - 1) in
    let cb = UnionFind.find uf (snd abs.(i) - 1) in
    if UnionFind.Class.compare ca cb = 0
    then ans.(i) <- ans.(i + 1)
    else begin
      let cnta = cnt.(UnionFind.Class.to_int ca) in
      let cntb = cnt.(UnionFind.Class.to_int cb) in
      ans.(i) <- ans.(i + 1) - cnta * cntb;
      cnt.(UnionFind.Class.to_int ca) <- cnta + cntb;
      cnt.(UnionFind.Class.to_int cb) <- cnta + cntb;
      UnionFind.unite uf (fst abs.(i) - 1) (snd abs.(i) - 1)
    end
  done;
  for i = 1 to m do
    Printf.printf "%d\n" ans.(i)
  done


let () = Scanf.scanf "%d/%d/%d" @@ fun yyyy mm dd ->
  Printf.printf "%s\n" @@
  if mm <= 4 then "Heisei" else "TBD"

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


let n, a, b, c = Scanf.scanf " %d %d %d %d" @@ fun n a b c -> n, a, b, c
let ls = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let f m l =
  let len = ref 0 in
  let c = ref 0 in
  for i = 0 to n - 1 do
    if m lsr i land 1 = 1 then
      (len := !len + ls.(i); incr c)
  done;
  max 0 (!c - 1) * 10 + (abs @@ l - !len)
let g i j k = f i a + f j b + f k c
let ans = ref max_int
let _ =
  for i = 1 to 255 do
    for j = 1 to 255 do
      if i land j = 0 then
        for k = 1 to 255 do
          if i land k = 0 && j land k = 0 then
            ans := min !ans @@ g i j k
        done
    done
  done;
  Printf.printf "%d\n" !ans

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


(* q log(max a b) *)
let kInf = 20202020202
let a, b, q = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let ns = [|a; b|]
let sts = Array.init 2 @@ fun i ->
  let ds = Array.make (ns.(i) + 2) 0 in
  ds.(0) <- -kInf + i; ds.(ns.(i) + 1) <- kInf + i;
  for j = 1 to ns.(i) do ds.(j) <- Scanf.scanf " %d" @@ (+) 0 done;
  ds
let xs = Array.init q @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let is_ok i key a = a.(i) >= key
let binary_search key a =
  let left, right = ref @@ -1, ref @@ Array.length a in
  while !right - !left > 1 do
    let mid = !left + (!right - !left) / 2 in
    if is_ok mid key a then right := mid
    else left := mid done;
  !right
let g x i =
  let ps = sts.(i) in
  let yi1 = binary_search x ps in
  min (x - ps.(yi1 - 1)) @@ ps.(yi1) - x
let f x =
  let si1, ti1 = binary_search x sts.(0), binary_search x sts.(1) in
  let s0, s1, t0, t1 = sts.(0).(si1 - 1), sts.(0).(si1), sts.(1).(ti1 - 1), sts.(1).(ti1) in
  let ans = ref kInf in
  ans := min !ans @@ if s0 < t0 then x - t0 + g t0 0 else x - s0 + g s0 1;
  ans := min !ans @@ if s1 < t1 then s1 - x + g s1 1 else t1 - x + g t1 0;
  Printf.printf "%d\n" !ans
let _ = Array.iter f xs

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

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

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


let (>>=) xs f = List.map f xs |> List.concat
let lower_bound p arr =
  let len = Array.length arr in
  let rec f l r =
    if l+1 >= r then r
    else
      let m = (l+r) / 2 in
      if p arr.(m) then f l m else f m r
  in f (-1) len
let lower_bound' p arr =
  let idx = lower_bound p arr in
  if idx >= Array.length arr then [] else [arr.(idx)]
let sign = compare 0
let () =
  Scanf.scanf "%d %d %d" @@ fun a b q ->
  let s = Array.init a (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let t = Array.init b (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let s' = Array.init a (fun i -> s.(a-1-i)) in
  let t' = Array.init b (fun i -> t.(b-1-i)) in
  let xs = Array.init q (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  xs |> Array.iter @@ fun x ->
    ((lower_bound' ((<=) x) s @ lower_bound' ((>=) x) s') >>= fun sh ->
     (lower_bound' ((<=) x) t @ lower_bound' ((>=) x) t') >>= fun tp ->
       let v, w = min (abs (sh-x)) (abs (tp-x)), max (abs (sh-x)) (abs (tp-x)) in
       if sign (sh-x) * sign (tp-x) >= 0 then [w] else [2*v + w])
    |> List.fold_left min 10101010101010 |> Printf.printf "%d\n"


Scanf.scanf " %d %d" @@ fun a b ->
  print_int @@
    if b mod a = 0 then a+b else b-a

Score : 100 points

Problem Statement

You are given positive integers A and B.

If A is a divisor of B, print A + B; otherwise, print B - A.

Constraints

All values in input are integers.

1 \leq A \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

If A is a divisor of B, print A + B; otherwise, print B - A.

Sample Input 1

4 12

Sample Output 1

16

As 4 is a divisor of 12, 4 + 12 = 16 should be printed.

Sample Input 2

8 20

Sample Output 2

12

Sample Input 3

1 1

Sample Output 3

2

1 is a divisor of 1.


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

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

let lst = List.init n ( fun _ ->
        List.tl (Str.split (Str.regexp " ") (read_line ()))
        |> List.map int_of_string
        |> Set.of_list
)

let () =
        Set.cardinal (List.fold_left (fun a b -> Set.intersect a b) (List.hd lst) (List.tl lst))
        |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on M kinds of foods and asked N people whether they like these foods or not.

The i-th person answered that he/she only likes the A_{i1}-th, A_{i2}-th, ..., A_{iK_i}-th food.

Find the number of the foods liked by all the N people.

Constraints

All values in input are integers.

1 \leq N, M \leq 30

1 \leq K_i \leq M

1 \leq A_{ij} \leq M

For each i (1 \leq i \leq N), A_{i1}, A_{i2}, ..., A_{iK_i} are distinct.

Constraints

Input is given from Standard Input in the following format:

N M
K_1 A_{11} A_{12} ... A_{1K_1}
K_2 A_{21} A_{22} ... A_{2K_2}
:
K_N A_{N1} A_{N2} ... A_{NK_N}

Output

Print the number of the foods liked by all the N people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, 1 should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3