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

let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then ( if flag then cur :: acc else acc) else (
                match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let check a =
        let rep = Array.length a / 3 in
        let hist = Array.fold_left (fun map v -> M.add v (1 + try M.find v map with _ -> 0) map) M.empty a in
        let cont = Array.of_list (M.fold (fun k v acc -> (k, v) :: acc) hist []) in
        match Array.length cont with
        | 1 -> fst cont.(0) = 0
        | 2 -> let (k1, v1) = cont.(0) in
               let (k2, v2) = cont.(1) in
               if v1 = rep * 2 && v2 = rep then (
                   k2 = 0
               ) else if v2 = rep * 2 && v1 = rep then (
                   k1 = 0
               ) else false
        | 3 -> let (k1, v1) = cont.(0) in
               let (k2, v2) = cont.(1) in
               let (k3, v3) = cont.(2) in
               v1 = rep && v2 = rep && v3 = rep && k1 lxor k2 lxor k3 = 0
        | _ -> false

    in
    let main () =
        let n = int_of_string (read_line ()) in
        let a = Array.of_list (split (read_line ())) in
        let flag = if n mod 3 = 0 then (
            check a
        ) else Array.fold_left (+) 0 a = 0
        in
        print_endline (if flag then "Yes" else "No")
    in
    main ()


let () =
    let main () =
        let n = int_of_string (read_line ()) in
        if n = 1 || (n + 1) land n <> 0 then print_endline "No" else
            let () = print_endline "Yes" in
            for i = 1 to n * 2 - 1 do
                Printf.printf "%d %d\n" i (i + 1)
            done

    in
    main ()

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

Score : 700 points

Problem Statement

You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.

Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.

Constraints

N is an integer.

1 \leq N \leq 10^{5}

Input

Input is given from Standard Input in the following format:

N

Output

If there exists a tree satisfying the condition in the statement, print Yes; otherwise, print No.
Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:

a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}

Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.

Sample Input 1

3

Sample Output 1

Yes
1 2
2 3
3 4
4 5
5 6

The sample output represents the following graph:

Sample Input 2

1

Sample Output 2

No

There is no tree satisfying the condition.

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.


open Printf
open Scanf

let solve n a b = min (n * a) b

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

Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


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


let n, a, b = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = Printf.printf "%d\n" @@ min b @@ n * a


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


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

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


let ans, n, xss = Scanf.(scanf "%d %d" @@ fun n d -> ref 0, n, Array.(init n @@ fun _ -> init d @@ fun _ -> scanf " %d" (+) 0))
let rec f i n = if i * i >= n then i * i = n else f (i + 1) n
let g n = n * n
let _ = Array.(iteri (fun i xs -> for j = i + 1 to n - 1 do if f 1 @@ fold_left (+) 0 @@ mapi (fun k x -> g (x - xss.(j).(k))) xs then incr ans done) xss); Printf.printf "%d\n" !ans


let n, d = Scanf.scanf " %d %d" @@ fun a b -> a, b
let xss = Array.init n @@ fun _ -> Array.init d @@ fun _ -> Scanf.scanf " %d" (+) 0
let g x = x * x
let f ys zs = Array.mapi (fun i y -> g @@ y - zs.(i)) ys |> Array.fold_left (+) 0
let h n = let rec f i = if i * i >= n then i * i = n else f (i + 1) in f 0
let ans = ref 0
let _ = Array.iteri (fun i xs -> for j = i + 1 to n - 1 do if h @@ f xs xss.(j) then incr ans done) xss; Printf.printf "%d\n" !ans


let n, d = Scanf.scanf " %d %d" @@ fun a b -> a, b
let xss = Array.init n @@ fun _ -> Array.init d @@ fun _ -> Scanf.scanf " %d" (+) 0
let g x = x * x
let f ys zs = Array.fold_left (+) 0 @@ Array.init d @@ fun i -> g @@ ys.(i) - zs.(i)
let ans = ref 0
let _ =
  for i = 0 to n - 1 do
    for j = i + 1 to n - 1 do
      let x = ref 0 in
      let b = f xss.(i) xss.(j) in
      while !x * !x < b do incr x done;
      if !x * !x = b then incr ans done done;
  Printf.printf "%d\n" !ans


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

let () = Scanf.scanf "%d %d\n" @@ fun n q ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d %d %d\n" @@ fun a b c d ->
      es.(a - 1) <- (b - 1, c, d) :: es.(a - 1);
      es.(b - 1) <- (a - 1, c, d) :: es.(b - 1)
  done;
  let dist = Array.make n (-1) in
  let depth = Array.make n 0 in
  let count_colors = Array.make n IntMap.empty in
  let acc_colors = Array.make n IntMap.empty in
  let parent = Array.make_matrix 17 n 0 in
  let rec visit c cd d dp u v =
    if 0 <= dist.(v) then ()
    else begin
      dist.(v) <- d;
      depth.(v) <- dp;
      parent.(0).(v) <- u;
      acc_colors.(v) <- cd;
      count_colors.(v) <- c;
      List.iter (fun (u, c', d') ->
        visit
          (IntMap.add c'
            (1 +
              try IntMap.find c' c
              with Not_found -> 0) c)
          (IntMap.add c'
            (d' +
              try IntMap.find c' cd
              with Not_found -> 0) cd)
          (d + d') (1 + dp) v u) es.(v)
    end in
  visit IntMap.empty IntMap.empty 0 0 0 0;
  for i = 1 to 16 do
    for v = 0 to n - 1 do
      parent.(i).(v) <- parent.(i - 1).(parent.(i - 1).(v))
    done
  done;
  let rec up d v i =
    if i < 0 then v
    else up d (if d land (1 lsl i) = 0 then v else parent.(i).(v)) (i - 1) in
  let up d v = up d v 16 in
  let rec lca u v = function
    | 0 ->
        if parent.(0).(u) = parent.(0).(v)
        then parent.(0).(u)
        else parent.(1).(u)
    | i ->
        ( if parent.(i).(u) = parent.(i).(v)
          then lca u v
          else lca (parent.(i).(u)) (parent.(i).(u)) ) (i - 1) in
  let lca u v =
    if u = v then u
    else
      lca
        (if depth.(u) <= depth.(v) then u else up (depth.(u) - depth.(v)) u)
        (if depth.(v) <= depth.(u) then v else up (depth.(v) - depth.(u)) v) 16 in
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d %d %d\n" @@ fun x y u v ->
      let w = lca (u - 1) (v - 1) in
      Printf.printf "%d\n" @@
      (dist.(u - 1) - (try IntMap.find x acc_colors.(u - 1) with Not_found -> 0) + y * (try IntMap.find x count_colors.(u - 1) with Not_found -> 0))
      + (dist.(v - 1) - (try IntMap.find x acc_colors.(v - 1) with Not_found -> 0) + y * (try IntMap.find x count_colors.(v - 1) with Not_found -> 0))
      - 2 * (dist.(w) - (try IntMap.find x acc_colors.(w) with Not_found -> 0) + y * (try IntMap.find x count_colors.(w) with Not_found -> 0))
  done

Score : 600 points

Problem Statement

There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.

Answer the following Q queries:

Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

1 \leq a_i, b_i \leq N

1 \leq c_i \leq N-1

1 \leq d_i \leq 10^4

1 \leq x_j \leq N-1

1 \leq y_j \leq 10^4

1 \leq u_j < v_j \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q

Output

Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.

Sample Input 1

5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4

Sample Output 1

130
200
60

The graph in this input is as follows:

Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line.

Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130.

Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200.

Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have their original lengths.


Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


let s = Scanf.scanf " %c%c%c%c" @@ fun a b c d -> [|a; b; c; d|]
let _ =
  Array.sort compare s;
  print_endline @@ if s.(0) = s.(1) && s.(2) = s.(3) && s.(1) <> s.(2) then "Yes" else "No"


let () = Scanf.scanf "%d" @@ fun n ->
  let ps = Array.init n @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let ids = Array.init (n - 2) @@ fun i -> i + 1 in
  let check acm id = if (ps.(id - 1) < ps.(id) && ps.(id) < ps.(id + 1)) || (ps.(id - 1) > ps.(id) && ps.(id) > ps.(id + 1))
                      then acm + 1 else acm in
  let ans = Array.fold_left check 0 ids in
  Printf.printf "%d\n" ans

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


let n = Scanf.scanf " %d" @@ (+) 0
let ps = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let ans = ref 0
let _ =
  for i = 0 to n - 3 do
    if (ps.(i) < ps.(i + 1) && ps.(i + 1) < ps.(i + 2)) || (ps.(i + 2) < ps.(i + 1) && ps.(i + 1) < ps.(i)) then incr ans done;
  Printf.printf "%d\n" !ans


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let memo = Array.make_matrix 3000 3000 @@ -1
let rec comb n k =
  if memo.(n).(k) > -1 then memo.(n).(k)
  else
    (memo.(n).(k) <- if n < k then 0 else if n = k then 1 else if k = 0 then 1
      else (comb (n - 1) (k - 1) + comb (n - 1) k) mod 1_000_000_007;
    memo.(n).(k))
let _ =
  for i = 1 to k do
    Printf.printf "%d\n" @@
      if n - k = i - 1 then 1
      else if n - k < i - 1 then 0
      else comb (k - 1) (i - 1) * comb (n - k + 1) i mod 1_000_000_007 done

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


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

let () =
    let main () =
        let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun n m -> n, m) in
        let uv = Array.init m (fun _ -> Scanf.sscanf (read_line ()) "%d %d" (fun u v -> u, v)) in
        let s, t = Scanf.sscanf (read_line ()) "%d %d" (fun s t -> s, t) in
        let u = Array.make (n + 1) S.empty in
        Array.iter (fun (uu, vv) -> u.(uu) <- S.add vv u.(uu)) uv;
        let v = Array.make (n + 1) S.empty in
        for i = 1 to n do
            let set = S.fold (fun k s2 -> S.union u.(k) s2) u.(i) S.empty in
            v.(i) <-  S.fold (fun k s2 -> S.union u.(k) s2) set   S.empty
        done;
        let visited = Array.make (n + 1) (-1) in
        visited.(s) <- 0;
        let rec loop step frontier =
            if S.cardinal frontier = 0 then (-1) else
                let frontier =
                    S.fold (fun e next_frontier ->
                        S.fold (fun f next_frontier ->
                            if visited.(f) >= 0 then next_frontier else (
                                visited.(f) <- step;
                                S.add f next_frontier
                            )
                        ) v.(e) next_frontier
                    ) frontier S.empty
                in
                if visited.(t) >= 0 then visited.(t) else loop (step + 1) frontier
        in
        let result = loop 1 (S.singleton s) in
        Printf.printf "%d\n" result
    in
    main ()

Score : 500 points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G.
G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.

First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq \min(10^5, N (N-1))

1 \leq u_i, v_i \leq N(1 \leq i \leq M)

u_i \neq v_i (1 \leq i \leq M)

If i \neq j, (u_i, v_i) \neq (u_j, v_j).

1 \leq S, T \leq N

S \neq T

Input

Input is given from Standard Input in the following format:

N M
u_1 v_1
:
u_M v_M
S T

Output

If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1.
If he can, print the minimum number of ken-ken-pa needed to reach vertex T.

Sample Input 1

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

Sample Output 1

2

Ken can reach Vertex 3 from Vertex 1 in two ken-ken-pa, as follows: 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 in the first ken-ken-pa, then 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex 1, so he cannot reach Vertex 2, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex S and Vertex T may be disconnected.

Sample Input 4

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

Sample Output 4

2


module DirectedGraph
  (* 道の表現 *)
  (Path : sig
    type t
    (* 辺の名前 *)
    type edge
    (* 長さ0の道 *)
    val nil : t
    (* 道の後ろに辺を付け足した道 *)
    val snoc : t -> edge -> t
  end) :
sig
  (* BFSにより，重みのないグラフの最短経路を求める *)
  val bfs :
    (* 頂点数（Hashtblを用いるので目安程度） *)
    int ->
    (* 辺の名前が付いた隣接リスト *)
    ('v -> ('v * Path.edge) list) ->
    (* 始点 *)
    'v ->
    (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
    ('v -> Path.t option)
end = struct
  let rec bfs_aux es d frontier t =
    try Some (Hashtbl.find d t) with
    | Not_found ->
        match !frontier with
        | [] -> None
        | _ :: _ ->
            frontier := List.fold_right (fun u ->
              List.fold_right (fun (v, e) frontier ->
                if Hashtbl.mem d v
                then frontier
                else (Hashtbl.add d v (Path.snoc (Hashtbl.find d u) e); v :: frontier))
              (es u)) !frontier [];
            bfs_aux es d frontier t

  (*
   * 終点に辿り着いた時点で探索を切り上げるが，
   * 戻り値の関数を覚えておくと，途中まで探索した結果が再利用される
   * （#trace bfs_aux すると分かりやすい）
   *)
  let bfs n es s =
    let d = Hashtbl.create n in
    Hashtbl.add d s Path.nil;
    let frontier = ref [s] in
    bfs_aux es d frontier
end

module G = DirectedGraph (struct
  type t = int
  type edge = unit
  let nil = 0
  let snoc t _ = t + 1
end)

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let es = Array.make n [] in
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d\n" @@ fun u v ->
      es.(u - 1) <- v - 1 :: es.(u - 1)
  done;
  Scanf.scanf "%d %d\n" @@ fun s t ->
  let dp = G.bfs (3 * n) (fun (v, m) ->
    List.map (fun u -> ((u, (m + 1) mod 3), ())) es.(v)) (s - 1, 0) in
  match dp (t - 1, 0) with
  | None -> print_endline "-1"
  | Some d -> Printf.printf "%d\n" @@ d / 3


let () = Scanf.scanf "%s" @@ fun s ->
  let cond = (s.[0] = s.[1]) || (s.[1] = s.[2]) || (s.[2] = s.[3]) in
  let ans = if cond then "Bad" else "Good" in
  Printf.printf "%s\n" ans

Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


let n = read_int ()
let a, b, c, d = n / 1000, n / 100 - (n / 1000) * 10, n mod 100 - n mod 10, n mod 10
let () = print_endline (if a = b || b = c || c = d then "Bad" else "Good")


let s = read_line ()
let _ = print_endline @@ if s.[0] = s.[1] || s.[1] = s.[2] || s.[2] = s.[3] then "Bad" else "Good"


let inp : unit -> string = fun () ->
  input_line stdin
let () =
  let s = inp () in
  let rec loop s n pred =
    if n = 0 then true
    else
      let a = s.[n - 1] in
      if a = pred then false
      else loop s (n - 1) a
  in
  if loop s 4 'a' then
    print_endline "Good"
  else
    print_endline "Bad"


(* unihernandez22
 * https://atcoder.jp/contests/abc131/tasks/abc131_b
 * implementation
 * *)

let rec solution n l i cum eat =
    if i > n then cum-eat
    else
        let curr = i+l-1 in
        if abs curr < abs eat then
            solution n l (i+1) (cum+curr) curr
        else
            solution n l (i+1) (cum+curr) eat;;

Printf.printf "%d\n" @@
Scanf.scanf "%d %d\n" @@ fun n l ->
    solution n l 1 0 300;;

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


open List
let i_inp_list : unit -> int list = fun () ->
  let inp_split = Str.split (Str.regexp " ") (input_line stdin) in
  map (fun x -> int_of_string x) (inp_split)
let () =
  let [n; l] = i_inp_list () in
  let last = n + l - 1 in
  let ans =
    if last < 0 then
      (n - 1) * (l + last - 1) / 2
    else if l < 0 && last > 0 then
      n * (l + last) / 2
    else
      (n - 1) * (l + 1 + last)
  in
  print_int ans;
  print_newline ()


let a, b, c, d = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> a, b, c, d
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec lcm a b = a / gcd a b * b
let f x = x / c + x / d - x / lcm c d
let _ = b - a + 1 - (f b - f (a - 1)) |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


let split c s = (
    let res = ref [] in
    let i = ref 0 in
    let n = String.length s in
    while !i < n do
      let j = !i in
      while !i < n && s.[!i] <> c do i := !i + 1 done;
      res := String.sub s j (!i - j) :: !res;
      i := !i + 1;
    done;
    List.rev !res
  );;

let rec range a b = if a > b then [] else a :: range (a + 1) b;;
let read_ints () = read_line () |> split ' ' |> List.map int_of_string;;

let n = read_int ();;
let ab = Array.make n (0, 0);;
for i = 0 to n - 1 do
  let [x; y] = read_ints () in
  ab.(i) <- (x, y);
done;;
Array.sort (fun (a, b) (c, d) -> compare b d) ab;;

let curr = ref 0;;
let all = ref true;;
for i = 0 to n - 1 do
  curr := !curr + fst ab.(i);
  all := !all && (!curr <= snd ab.(i));
done;;

if !all then
  print_endline "Yes"
else
  print_endline "No";;

Score: 400 points

Problem Statement

Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.

Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.

It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B_i, and he must complete the job before or at this time.

Kizahashi cannot work on two or more jobs simultaneously, but when he completes a job, he can start working on another immediately.

Can Kizahashi complete all the jobs in time? If he can, print Yes; if he cannot, print No.

Constraints

All values in input are integers.

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

1 \leq A_i, B_i \leq 10^9 (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
A_1 B_1
.
.
.
A_N B_N

Output

If Kizahashi can complete all the jobs in time, print Yes; if he cannot, print No.

Sample Input 1

5
2 4
1 9
1 8
4 9
3 12

Sample Output 1

Yes

He can complete all the jobs in time by, for example, doing them in the following order:

Do Job 2 from time 0 to 1.

Do Job 1 from time 1 to 3.

Do Job 4 from time 3 to 7.

Do Job 3 from time 7 to 8.

Do Job 5 from time 8 to 11.

Note that it is fine to complete Job 3 exactly at the deadline, time 8.

Sample Input 2

3
334 1000
334 1000
334 1000

Sample Output 2

No

He cannot complete all the jobs in time, no matter what order he does them in.

Sample Input 3

30
384 8895
1725 9791
170 1024
4 11105
2 6
578 1815
702 3352
143 5141
1420 6980
24 1602
849 999
76 7586
85 5570
444 4991
719 11090
470 10708
1137 4547
455 9003
110 9901
15 8578
368 3692
104 1286
3 4
366 12143
7 6649
610 2374
152 7324
4 7042
292 11386
334 5720

Sample Output 3

Yes


open List
let i_inp : unit -> int = fun () ->
  int_of_string (input_line stdin)

let i_inp_list : unit -> int list = fun () ->
  let inp_split = Str.split (Str.regexp " ") (input_line stdin) in
  map (fun x -> int_of_string x) (inp_split)

(* inp_loop i_inp_list 10  のように使う *)
let rec inp_loop : (unit -> 'a) -> int -> 'a list = fun inp_fun n ->
  if n = 0 then []
  else
    let x = inp_fun () in
    x :: inp_loop inp_fun (n - 1)

let () =
  let n = i_inp () in
  let list =
    inp_loop
      (fun () ->
        let [a; b] = i_inp_list ()
        in (a, b))
      n in
  let list = fast_sort
               (fun (a1, b1) (a1, b1) -> if (b1, a1) > (b1, a1) then 1 else if (a1, b1) = (a1, b1) then 0 else -1)
               list in
  let rec loop t list =
    match list with
      [] -> true
    | (a, b) :: rest ->
       if t + a > b then false
       else loop (t + a) rest
  in
  if loop 0 list then
    print_endline "Yes"
  else
    print_endline "No"


let () =
    let main () =
        let n = Scanf.sscanf (read_line ()) "%d" (fun n -> n) in
        let ab = Array.init n (fun _ -> Scanf.sscanf (read_line ()) "%d %d" (fun a b -> b, a)) in
        Array.sort compare ab;
        let a = Array.init n (fun i -> snd ab.(i)) in
        let b = Array.init n (fun i -> fst ab.(i)) in
        let c = Array.make n 0 in
        let rec loop time i =
            if i < n then (
                let time = time + a.(i) in
                c.(i) <- time;
                loop time (i + 1)
            )
        in
        loop 0 0;
        let rec loop i =
            if i = n then "Yes" else if c.(i) > b.(i) then "No" else loop (i + 1)
        in
        print_endline (loop 0)
    in
    main ()


let scan_int () = Scanf.scanf " %d" (fun x -> x)
let print_int n = Printf.printf "%d\n" n

module Union_find :
  sig
    type t
    val init  : int -> t
    val get   : t -> int -> int
    val find  : t -> int -> int
    val size  : t -> int -> int
    val unite : t -> int -> int -> unit
    val same  : t -> int -> int -> bool
  end =
  struct
    type t = int array
    let init n = Array.make (n+1) (-1)
    let get data x = data.(x)
    let rec find data x =
      if data.(x) < 0 then x
      else let _ = data.(x) <- find data data.(x) in data.(x)
    let size data x = - data.(find data x)
    let unite data x y =
      let x = find data x and y = find data y in
      if x <> y then
        if data.(x) < data.(y) then
          let _ = data.(x) <- data.(x) + data.(y) in
          data.(y) <- x
        else
          let _ = data.(y) <- data.(x) + data.(y) in
          data.(x) <- y
    let same data x y =
      let x = find data x and y = find data y in (x == y)
  end

let () =
  let n = scan_int() in
  let max_n = 100000 in
  let v = Array.make (max_n+1) [] in
  let uf = Union_find.init max_n in
  let _ =
    for i = 1 to n do
      let a = scan_int() and b = scan_int() in
      v.(a) <- b :: v.(a)
    done in
  let _ =
    for i = 1 to max_n do
      if List.length v.(i) > 1 then
        let f x = Union_find.unite uf (List.hd v.(i)) x in
        List.iter f v.(i)
    done in
  let rec calc arr i ret =
    let ret =
      if List.length v.(i) > 0 then ret + Union_find.size uf (List.hd v.(i))
      else ret in
    if i == max_n then ret
    else calc arr (i+1) ret in
  print_int (calc v 0 (-n))

Score : 600 points

Problem Statement

There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).

We will repeat the following operation as long as possible:

Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position.

We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation.

Constraints

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq 10^5

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the maximum number of times we can do the operation.

Sample Input 1

3
1 1
5 1
5 5

Sample Output 1

1

By choosing a = 1, b = 1, c = 5, d = 5, we can add a dot at (1, 5). We cannot do the operation any more, so the maximum number of operations is 1.

Sample Input 2

2
10 10
20 20

Sample Output 2

0

There are only two dots, so we cannot do the operation at all.

Sample Input 3

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

Sample Output 3

16

We can do the operation for all choices of the form a = 1, b = 1, c = i, d = j (2 \leq i,j \leq 5), and no more. Thus, the maximum number of operations is 16.


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

let () =
    let main () =
        let n = Scanf.sscanf (read_line ()) "%d" (fun n -> n) in
        let xy = Array.init n (fun _ -> Scanf.sscanf (read_line ()) "%d %d" (fun x y -> x, y)) in
        let xmap = Array.fold_left (fun map (x, y) ->
            M.add x (S.add y (try M.find x map with _ -> S.empty)) map) M.empty xy in
        let ymap = Array.fold_left (fun map (x, y) ->
            M.add y (S.add x (try M.find y map with _ -> S.empty)) map) M.empty xy in
        let cx = Array.make 100002 true in
        let cy = Array.make 100002 true in
        let rec dfs_x px set ax ay =
            cx.(px) <- false;
            S.fold (fun py ((ax, ay) as acc) ->
                if cy.(py) then dfs_y py (M.find py ymap) ax ay else acc) set (ax + 1, ay)
        and dfs_y py set ax ay =
            cy.(py) <- false;
            S.fold (fun px ((ax, ay) as acc) ->
                if cx.(px) then dfs_x px (M.find px xmap) ax ay else acc) set (ax, ay + 1)
        in
        let acc = M.fold (fun x set acc ->
            if cx.(x) && S.cardinal set > 0 then let sx, sy = dfs_x x set 0 0 in acc + sx * sy else acc) xmap 0 in
        let acc = M.fold (fun y set acc ->
            if cy.(y) && S.cardinal set > 0 then let sx, sy = dfs_y y set 0 0 in acc + sx * sy else acc) ymap acc in
        Printf.printf "%d\n" (acc - n)
    in
    main ()


let n = read_int ();;

type unionfind = { size : int array; parent : int array };;
let init_unionfind n = {size = Array.make n 1; parent = Array.init n (fun i -> i)};;
let rec find uf x = (
    if uf.parent.(x) = x then
      x
    else (
      let y = find uf (uf.parent.(x)) in
      uf.parent.(x) <- y;
      y
    )
  );;
let unite uf x y = (
    let x = find uf x in
    let y = find uf y in
    if x <> y then (
      let x, y = if uf.size.(x) > uf.size.(y) then x, y else y, x in
      uf.size.(x) <- uf.size.(x) + uf.size.(y);
      uf.parent.(y) <- x;
    );
  );;

let uf = init_unionfind 200000;;

for i = 0 to n - 1 do
  let x, y = Scanf.scanf " %d %d" (fun x y -> x - 1, y - 1 + 100000) in
  unite uf x y
done

let row = Array.make 200000 0;;
let col = Array.make 200000 0;;

for i = 0 to 99999 do
  let j = find uf i in
  row.(j) <- row.(j) + 1;
done;;

for i = 100000 to 199999 do
  let j = find uf i in
  col.(j) <- col.(j) + 1;
done;;

let ans = ref (-n);;
for i = 0 to 199999 do
  ans := !ans + row.(i) * col.(i);
done;;

Printf.printf "%d\n" !ans;;


open Printf
open Scanf

let solve x a = if x >= a then 10 else 0

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

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


let () = Scanf.scanf "%d %d" @@ fun x a -> Printf.printf "%d" @@ if x < a then 0 else 10


let n, x = Scanf.scanf " %d %d" @@ fun a b -> a, b
let ls = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let d = ref 0
let ans = ref 0
let _ =
  for i = 0 to n - 1 do
    if !d <= x then incr ans;
    d := !d + ls.(i)
  done;
  Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


let w, h, x, y = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> a, b, c, d
let _ =
  if x * 2 = w || y * 2 = h || x = 0 || y = 0 || h * x = w * y then
    (Printf.printf "%.12f " @@ float w *. float h /. 2.;
    print_endline @@ if x * 2 = w && y * 2 = h then "1" else "0")
  else
    Printf.printf "%.12f 0\n" @@ float @@ max (min x (w - x) * h) (min y (h - y) * w)

Score : 300 points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H).
You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

1 \leq W,H \leq 10^9

0\leq x\leq W

0\leq y\leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

W H x y

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most 10^{-9}.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line x=1 gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1


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

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let ss = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun s -> s in
  let ts = Array.init m @@ fun _ -> Scanf.scanf "%d " @@ fun t -> t in
  let dp = Array.make_matrix (n + 1) (m + 1) 1 in
  for i = 0 to n - 1 do
    for j = 0 to m - 1 do
      dp.(i + 1).(j + 1) <-
        dp.(i).(j + 1) +^ dp.(i + 1).(j)
        -^ if ss.(i) = ts.(j) then 0 else dp.(i).(j)
    done
  done;
  Printf.printf "%d\n" dp.(n).(m)

Score : 500 points

Problem Statement

You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).

In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?

Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.

For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Since the answer can be tremendous, print the number modulo 10^9+7.

Constraints

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

The length of S is N.

The length of T is M.

1 \leq S_i, T_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

Output

Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

Sample Input 1

2 2
1 3
3 1

Sample Output 1

3

S has four subsequences: (), (1), (3), (1, 3).

T has four subsequences: (), (3), (1), (3, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

Sample Input 2

2 2
1 1
1 1

Sample Output 2

6

S has four subsequences: (), (1), (1), (1, 1).

T has four subsequences: (), (1), (1), (1, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 2 \times 2 pairs of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (1,1), for a total of six pairs.
Note again that we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Sample Input 3

4 4
3 4 5 6
3 4 5 6

Sample Output 3

16

Sample Input 4

10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7

Sample Output 4

191

Sample Input 5

20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Sample Output 5

846527861

Be sure to print the number modulo 10^9+7.


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = Printf.printf "%d\n" @@ if k = 1 then 0 else n - k

Score : 100 points

Problem Statement

Takahashi is distributing N balls to K persons.

If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls?

Constraints

1 \leq K \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the maximum possible difference in the number of balls received.

Sample Input 1

3 2

Sample Output 1

1

The only way to distribute three balls to two persons so that each of them receives at least one ball is to give one ball to one person and give two balls to the other person.

Thus, the maximum possible difference in the number of balls received is 1.

Sample Input 2

3 1

Sample Output 2

0

We have no choice but to give three balls to the only person, in which case the difference in the number of balls received is 0.

Sample Input 3

8 5

Sample Output 3

3

For example, if we give 1, 4, 1, 1, 1 balls to the five persons, the number of balls received between the person with the most balls and the person with the fewest balls would be 3, which is the maximum result.


(* O(n) *)
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let ps = Array.make_matrix 2 n 0
let pc = Array.make 2 0
let ms = [|[|max_int; min_int|]; [|max_int; min_int|]|]
let mis = Array.make_matrix 2 2 0
let ds = Array.make_matrix 2 n false
let xys = ref []
let f i a =
  let j = if a < 0 then 1 else 0 in
  ps.(j).(pc.(j)) <- a; pc.(j) <- pc.(j) + 1;
  if a < ms.(j).(0) then (ms.(j).(0) <- a; mis.(j).(0) <- i);
  if a >= ms.(j).(1) then (ms.(j).(1) <- a; mis.(j).(1) <- i)
let show_result () =
  Printf.printf "%d\n" ps.(0).(0);
  List.rev !xys |> List.iter (fun (x, y) -> Printf.printf "%d %d\n" x y)
let g () =
  for i = 2 to pc.(0) - 1 do
    let x, y = ps.(0).(1), ps.(0).(i) in
    xys := (x, y) :: !xys;
    ps.(0).(1) <- x - y
  done;
  let x, y = ps.(0).(0), ps.(0).(1) in
  xys := (x, y) :: !xys;
  show_result ()
let _ =
  Array.iteri f a_s;
  let i, j, k, l = if pc.(0) = 0 then 0, 1, 1, 0 else if pc.(1) = 0 then 1, 0, 0, 1 else -1, -1, -1, -1 in
  if i <> -1 then
    (if pc.(j) = 2 then
      let x, y = max ps.(j).(0) ps.(j).(1), min ps.(j).(0) ps.(j).(1) in
      Printf.printf "%d\n%d %d\n" (x - y) x y; exit 0
    else ();
    let x, y = ps.(j).(mis.(j).(k)), ps.(j).(mis.(j).(l)) in
    if x = y && i = 1 then (g (); exit 0);
    xys := (x, y) :: !xys;
    ds.(j).(mis.(j).(k)) <- true;
    ds.(j).(mis.(j).(l)) <- true;
    ps.(i).(0) <- x - y;
    pc.(i) <- 1)
  else ();
  let h (i0, j0) =
    for i = i0 to pc.(1 - j0) - 1 do
      if not ds.(1 - j0).(i) then
        let x, y = ps.(j0).(0), ps.(1 - j0).(i) in
        xys := (x, y) :: !xys;
        ps.(j0).(0) <- x - y;
        ds.(1 - j0).(i) <- true;
    done in
  List.iter h [1, 1; 0, 0]; show_result ()

Score : 500 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on a blackboard.

We will repeat the following operation N-1 times so that we have only one integer on the blackboard.

Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

2 \leq N \leq 10^5

-10^4 \leq A_i \leq 10^4

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value M of the final integer on the blackboard, and a sequence of operations x_i, y_i that maximizes the final integer, in the format below.

Here x_i and y_i represent the integers x and y chosen in the i-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

M
x_1 y_1
:
x_{N-1} y_{N-1}

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose x = -1 and y = 1 in the first operation, the set of integers written on the blackboard becomes (-2, 2).

Then, if we choose x = 2 and y = -2 in the second operation, the set of integers written on the blackboard becomes (4).

In this case, we have 4 as the final integer. We cannot end with a greater integer, so the answer is 4.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0


let p, q, r = Scanf.scanf "%d %d %d\n" @@ fun a b c -> a, b, c
let ans = min (min (p + q) (q + r)) (p + r)
let () = print_int ans

Score : 100 points

Problem Statement

There are three airports A, B and C, and flights between each pair of airports in both directions.

A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours.

Consider a route where we start at one of the airports, fly to another airport and then fly to the other airport.

What is the minimum possible sum of the flight times?

Constraints

1 \leq P,Q,R \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

P Q R

Output

Print the minimum possible sum of the flight times.

Sample Input 1

1 3 4

Sample Output 1

4

The sum of the flight times in the route A \rightarrow B \rightarrow C: 1 + 3 = 4 hours

The sum of the flight times in the route A \rightarrow C \rightarrow C: 4 + 3 = 7 hours

The sum of the flight times in the route B \rightarrow A \rightarrow C: 1 + 4 = 5 hours

The sum of the flight times in the route B \rightarrow C \rightarrow A: 3 + 4 = 7 hours

The sum of the flight times in the route C \rightarrow A \rightarrow B: 4 + 1 = 5 hours

The sum of the flight times in the route C \rightarrow B \rightarrow A: 3 + 1 = 4 hours

The minimum of these is 4 hours.

Sample Input 2

3 2 3

Sample Output 2

5


module A = Array
module C = Char
module I = Int64
module L = List
module Q = Queue

let pf = Printf.printf

let read_int () = Scanf.scanf "%d " (fun x -> x)
let read_float () = Scanf.scanf "%f " (fun x -> x)
let read_string () = Scanf.scanf "%s " (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())

let range s t = A.init (t - s) @@ (+) s
let foreach fold_f init s t map_f =
  range s t |> A.map map_f |> A.fold_left fold_f init

module S = struct
  include String
  let of_array a = String.init (A.length a) (A.get a)
  let to_array s = A.init (String.length s) (String.get s)
end;;

let () =
  let p = read_int () in
  let q = read_int () in
  let r = read_int () in
  let res = L.fold_left min max_int [p + q; q + r; r + p] in
  Printf.printf "%d\n" res


open List
(* 1行読み込みする関数 *)
(* i_inp : 1行読み込んで整数に変換, f_inp, s_inpもある *)
let inp : unit -> string = fun () ->
	input_line stdin
let s_inp = inp
let i_inp : unit -> int = fun () ->
	int_of_string (inp ())
let f_inp : unit -> float = fun () ->
	float_of_string (inp ())

(* 1行読み込んで、空白で分割する関数 *)
let inp_list : unit -> string list = fun () ->
	Str.split (Str.regexp " ") (inp ())
let s_inp_list : unit -> string list = inp_list
let i_inp_list : unit -> int list = fun () ->
	map (fun x -> int_of_string x) (inp_list ())
let f_inp_list : unit -> float list = fun () ->
  map (fun x -> float_of_string x) (inp_list ())

(* n行読み込む関数 *)
let rec inp_loop : (unit -> 'a) -> int -> 'a list = fun inp_fun n ->
  if n = 0 then []
  else
    let x = inp_fun () in
    x :: inp_loop inp_fun (n - 1)

(* 関数本体 *)
let () =
  let [n; m] = i_inp_list () in
  let brokens = Array.make (n + 1) false in
  let rec inp_loop m =
    if m = 0 then ()
    else
      let x = i_inp () in
      (brokens.(x) <- true;
       inp_loop (m - 1)) in
  let () = inp_loop m in
  let memo = Array.make (n + 1) None in
  let rec loop a =
    match memo.(a) with
      None ->
       if brokens.(a) then 0
       else
         if a + 2 <= n then
           let x = (loop (a + 1) + loop (a + 2)) mod 1000000007 in
           memo.(a) <- Some x;
           x
         else if a + 1 <= n then
           let x = (loop (a + 1)) mod 1000000007 in
           memo.(a) <- Some x;
          x
         else
           (memo.(a) <- Some 1;
            1)
    | Some x -> x
  in
  print_int (loop 0);
  print_newline ()

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


let rec fold_for a b v f = if a >= b then v else fold_for (a+1) b (f a v) f
let () =
  Scanf.scanf "%d %d" @@ fun h w ->
  let s = Array.init h (fun _ -> Scanf.scanf " %s" (fun x -> x)) in
  let f x y = s.(x).[y] in

  let t = Array.make_matrix h w (-3) in
  let g x y v = t.(x).(y) <- t.(x).(y) + v in

  let rec loop n f g h w =
    if n <= 0 then ()
    else begin
      for i = 0 to h-1 do
        ignore @@ fold_for 1 w (if f i 0 = '.' then 1 else 0) @@ fun j v ->
        let v' = if f i j = '.' then v+1 else 0 in
        g i j v'; v'
      done;
      loop (n-1) (fun x y -> f (h-1-y) x) (fun x y -> g (h-1-y) x) w h
    end
  in
  loop 4 f g h w;

  Array.fold_left (Array.fold_left max) 0 t
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


Scanf.scanf " %d %d %d %d %d" @@ fun n a b c d ->
  let a, b, c, d = a - 1, b - 1, c - 1, d - 1 in
  let s = Scanf.scanf " %s" @@ fun s -> s in
  let l, l_end, r, r_end = if a < b then a, c, b, d else b, d, a, c in
  let dp = Array.make n false in
  dp.(r) <- true;
  dp.(r + 1) <- s.[r + 1] <> '#';
  for i = r + 2 to n - 1 do
    dp.(i) <- s.[i] <> '#' && (dp.(i - 1) || dp.(i - 2))
  done;
  if not dp.(r_end) then (print_endline "No"; exit 0);
  let dp = Array.make n false in
  dp.(l) <- true;
  dp.(l + 1) <- s.[l + 1] <> '#';
  for i = l + 2 to n - 1 do
    dp.(i) <- s.[i] <> '#' && (dp.(i - 1) || dp.(i - 2))
  done;
  if not dp.(l_end) then (print_endline "No"; exit 0);
  let b = Bytes.of_string s in
  for i = 0 to n - 1 do
    if Bytes.get b i = '.' then Bytes.set b i '_';
  done;
  let s = Bytes.to_string b in
  print_endline @@
    if s.[r_end - 1] = '#' || (r_end + 1 < n && s.[r_end + 1] = '#') then
      try
        let i = Str.search_forward (Str.regexp "___") s r in
        if i < r_end then "Yes" else "No" with
      | _ -> "No"
    else "Yes"

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

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

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes


let () =
    let main () =
        let n, a, b, c, d = Scanf.sscanf (read_line ()) "%d %d %d %d %d" (fun n a b c d -> n, a, b, c, d) in
        let s = read_line () in
        let reachable a b =
            let rec loop i prev =
                if i = b then true else
                    if s.[i - 1] = '.' then loop (i + 1) false else
                        if prev then false else loop (i + 1) true
            in
            loop a false
        in
        let three_space a b c d =
            let rec loop i =
                if i + 2 > c then 0 else
                    if s.[i - 1] = '.' && s.[i] = '.' && s.[i + 1] = '.' then i else
                        loop (i + 1)
            in
            let r = loop (b - 1) in
            if r = 0 || r + 1 > d then false else
                reachable b (r + 1) && reachable (r + 1) d &&
                reachable a r && reachable (r + 2) c
        in
        let flag =
            if c < d then reachable a c && reachable b d else
                three_space a b c d
        in
        Printf.printf "%s\n" (if flag then "Yes" else "No")
    in
    main ()


Printf.printf "%d\n" (Scanf.scanf "%d" (fun n -> 180*(n-2)))

Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


let f x s = let n = ref 0 in String.iter (fun c -> if c = x then incr n) s; !n
let _ = print_endline @@ if f 'x' @@ read_line () < 8 then "YES" else "NO"

Score : 200 points

Problem Statement

Takahashi is competing in a sumo tournament.
The tournament lasts for 15 days, during which he performs in one match per day.
If he wins 8 or more matches, he can also participate in the next tournament.

The matches for the first k days have finished.
You are given the results of Takahashi's matches as a string S consisting of o and x.
If the i-th character in S is o, it means that Takahashi won the match on the i-th day; if that character is x, it means that Takahashi lost the match on the i-th day.

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO if there is no such possibility.

Constraints

1 \leq k \leq 15

S is a string of length k consisting of o and x.

Input

Input is given from Standard Input in the following format:

S

Output

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO otherwise.

Sample Input 1

oxoxoxoxoxoxox

Sample Output 1

YES

Takahashi has 7 wins and 7 losses before the last match. If he wins that match, he will have 8 wins.

Sample Input 2

xxxxxxxx

Sample Output 2

NO


Scanf.scanf "%d %d" @@ fun n m ->
  let sss = Array.init m @@ fun _ ->
    let k = Scanf.scanf " %d" @@ (+) 0 in
    Array.init k @@ fun _ -> Scanf.scanf " %d" @@ fun s -> s - 1 in
  let ps = Array.init m @@ fun _ -> Scanf.scanf " %d" @@ (+) 0 in
  let array_count f = Array.fold_left (fun n x -> if f x then n + 1 else n) 0 in
  let array_for_all f xs = Array.length xs = array_count f xs in
  let flags = Array.make n false in
  let is_on i =
    let ss = sss.(i) in
    let c = ref 0 in
    for j = 0 to Array.length ss - 1 do
      if flags.(ss.(j)) then incr c
    done;
    !c mod 2 = ps.(i) in
    (* let c = array_count ((=) true) flags in c mod 2 = ps.(i) in *)
  let judge () = array_for_all is_on @@ Array.init m @@ (+) 0 in
  let ans = ref 0 in
  let rec find i =
    (* Array.iter (fun x -> print_string @@ if x then "true " else "false ") flags;
    print_newline (); *)
    (* Printf.printf "%d %d\n" i n; *)
    if i >= n then
      (if judge () then incr ans)
    else
      (flags.(i) <- true;
      find (i + 1);
      flags.(i) <- false;
      find (i + 1)) in
  find 0;
  Printf.printf "%d\n" !ans

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


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

let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then ( if flag then cur :: acc else acc) else (
                match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let main () =
        let n, k = Scanf.sscanf (read_line ()) "%d %d" (fun n k -> n, k) in
        let v = Array.of_list (split (read_line ())) in
        let calc l r k =
            let rec loop i acc =
                if i = l then acc else loop (i + 1) (v.(i) :: acc)
            in
            let acc = loop 0 [] in
            let rec loop i acc =
                if i = r then acc else loop (i - 1) (v.(i) :: acc)
            in
            let acc = loop (n - 1) acc in
            let l = List.sort compare acc in
            let rec drop i list =
                if i = 0 then list else
                    match list with
                    | [] -> []
                    | hd :: tl -> if hd < 0 then drop (i - 1) tl else tl
            in
            List.fold_left (+) 0 (drop k l)
        in
        let rec loop k mx sets =
            if k = 0 then mx else
                let mx, next =
                    S.fold (fun (l, r) (mx, next) ->
                        let mx = max mx (calc l r k) in
                        let next = if l <= r then S.add (l+1, r) next else next in
                        let next = if l <  r then S.add (l, r-1) next else next in
                        mx, next) sets (mx, S.empty)
                in
                loop (k - 1) mx next
        in
        let init = S.add (0, n - 1) S.empty in
        let ans = loop k 0 init in
        Printf.printf "%d\n" ans
    in
    main ()

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.


let () = Scanf.scanf "%d %d" @@ fun a b ->
  let ans =
    if a >= 13 then b
    else if a >= 6 then b / 2
    else 0
  in
  Printf.printf "%d\n" ans

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.


let () = Scanf.scanf "%d %d" @@ fun a b ->
  Printf.printf "%d\n" @@
  if a <= 5 then 0 else if a <= 12 then b / 2 else b


let () = Scanf.scanf "%d %d %d" @@ fun r d x2000 ->
  let xs = Array.make 11 0 in
  xs.(0) <- x2000;
  for i = 1 to 10 do
    xs.(i) <- r * xs.(i - 1) - d;
    Printf.printf "%d\n" xs.(i)
  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 () = Scanf.scanf "%d %d %d" (fun r d x -> (
  let xi = ref x in
  for i = 1 to 10 do
    xi := r * !xi - d;
    print_endline(string_of_int !xi);
  done
))


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


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) ->
        not odd,
        ( acc + b +
          if odd then
            abs (m - a)
          else
            let (m', _) = IntMap.min_binding q' in
            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 not odd
          then (q, q')
          else (remove (fst (IntMap.max_binding q)) q, add (fst (IntMap.max_binding q)) q')
        else
          let q' = add a q' in
          if odd
          then (q, 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)

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 _ = 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 if n = n' + 1
          then (n, n' + 1, add a (remove m q), add m q', sum + a - m, sum' + m)
          else raise Not_found
        else
          if n = n' + 1
          then (n, n' + 1, q, add a q', sum, sum' + a)
          else if n = n'
          then (n + 1, n', add m q, add a (remove m q'), sum + m, sum' + a - m)
          else raise Not_found)
  (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)


module MultiSet = struct
  (* 多重集合 *)
  module type OrderedType =
    sig
      type t
      val compare: t -> t -> int
    end

  module type S =
    sig
      type elt
      type t
      (* 空集合 *)
      val empty : t
      (* 要素数 *)
      val cardinal : t -> int
      (* 要素xをn個追加 *)
      val add : elt -> int -> t -> t
      (* 要素xをn個削除 要素がn個以上存在しない場合は全て削除 *)
      val remove : elt -> int -> t -> t
      (* 要素xの数を数える *)
      val count : elt -> t -> int
      (* xより小さい要素の数を数える *)
      val count_lt : elt -> t -> int
      (* xより大きい要素の数を数える *)
      val count_gt : elt -> t -> int
      (* 昇順に見た時のn番目の要素 範囲外ならNot_foundを投げる *)
      val nth_inc : int -> t -> elt
      (* 降順に見た時のn番目の要素 範囲外ならNot_foundを投げる *)
      val nth_dec : int -> t -> elt
      (* 昇順に見てn要素を取り出す n要素に満たなければ全ての要素を昇順に列挙する *)
      val take_inc : int -> t -> elt list
      (* 降順に見てn要素を取り出す n要素に満たなければ全ての要素を降順に列挙する *)
      val take_dec : int -> t -> elt list
      (* 全ての要素を昇順に列挙する *)
      val elements_inc : t -> elt list
      (* 全ての要素を降順に列挙する *)
      val elements_dec : t -> elt list
      (* 昇順に要素を畳み込む *)
      val fold_inc : ('a -> elt -> 'a) -> 'a -> t -> 'a
      (* 降順に要素を畳み込む *)
      val fold_dec : (elt -> 'a -> 'a) -> t -> 'a -> 'a
      (* 最小の要素 空集合が与えられた場合はNot_foundを投げる *)
      val min_elt : t -> elt
      (* 最大の要素 空集合が与えられた場合はNot_foundを投げる *)
      val max_elt : t -> elt
    end

  module Make (Ord : OrderedType) : S with type elt = Ord.t =
    struct
      type elt = Ord.t

      (* MapからパクったのでAVL木の変種（高さの差を2以下まで許容する） *)
      type t =
        | Empty
        | Node of body
      and body =
        { left : t;
          data : elt;
          count : int;
          right : t;
          height : int;
          cardinal : int }

      let empty = Empty

      let height = function
        | Empty -> 0
        | Node { height } -> height

      let cardinal = function
        | Empty -> 0
        | Node { cardinal } -> cardinal

      let create ~left ~data ~count ~right =
        Node
          { left; data; count; right;
            height = 1 + max (height left) (height right);
            cardinal = count + cardinal left + cardinal right }

      let balance ~left:l ~data:x ~count:d ~right:r =
        let hl = height l in
        let hr = height r in
        if hl > hr + 2 then begin
          match l with
          | Empty -> invalid_arg "MultiSet.balance" | Node { left = ll; data = lv; count = ld; right = lr } ->
              if height ll >= height lr then
                create ll lv ld (create lr x d r)
              else begin
                match lr with
                | Empty -> invalid_arg "MultiSet.balance"
                | Node { left = lrl; data = lrv; count = lrd; right = lrr } ->
                    create (create ll lv ld lrl) lrv lrd (create lrr x d r)
              end
        end else if hr > hl + 2 then begin
          match r with
          | Empty -> invalid_arg "MultiSet.balance"
          | Node { left = rl; data = rv; count = rd; right = rr } ->
              if height rr >= height rl then
                create (create l x d rl) rv rd rr
              else begin
                match rl with
                | Empty -> invalid_arg "MultiSet.balance"
                | Node { left = rll; data = rlv; count = rld; right = rlr } ->
                    create (create l x d rll) rlv rld (create rlr rv rd rr)
              end
        end else create l x d r

      let rec add x n = function
        | Empty -> create Empty x n Empty
        | Node { left; data = y; count; right } ->
            match Ord.compare x y with
            | 0 ->
                create left x (count + n) right
            | c when c < 0 ->
                balance (add x n left) y count right
            | _ ->
                balance left y count (add x n right)

      (* 最小の要素とその数を返す *)
      let rec count_min_elt = function
        | Empty -> raise Not_found
        | Node { left = Empty; data; count } -> (data, count)
        | Node { left } -> count_min_elt left

      (* 最小の要素を全て削除する *)
      let rec clear_min_elt = function
        | Empty -> invalid_arg "MultiSet.clear_min_elt"
        | Node { left = Empty; right } -> right
        | Node { left; data; count; right } -> balance (clear_min_elt left) data count right

      let merge t1 t2 =
        match t1, t2 with
        | Empty, t
        | t, Empty -> t
        | Node _, Node _ ->
            let (x, c) = count_min_elt t2 in
            balance t1 x c (clear_min_elt t2)

      let rec remove x n = function
        | Empty -> Empty
        | Node { left; data = y; count; right } ->
            match Ord.compare x y with
            | 0 ->
                if count <= n then
                  merge left right
                else
                  create left y (count - n) right
            | c when c < 0 ->
                balance (remove x n left) y count right
            | _ ->
                balance left y count (remove x n right)

      let rec count x = function
        | Empty -> 0
        | Node { left; data = y; count = n; right } ->
            match Ord.compare x y with
            | 0 -> n
            | c when c < 0 ->
                count x left
            | _ ->
                count x right

      let rec count_lt x = function
        | Empty -> 0
        | Node { left; data = y; count; right } ->
            match Ord.compare x y with
            | 0 ->
                cardinal left
            | c when c < 0 ->
                count_lt x left
            | _ ->
                count_lt x right + count + cardinal left

      let rec count_gt x = function
        | Empty -> 0
        | Node { left; data = y; count; right } ->
            match Ord.compare x y with
            | 0 ->
                cardinal right
            | c when 0 < c ->
                count_gt x right
            | _ ->
                count_gt x left + count + cardinal right

      let rec nth_inc n = function
        | Empty -> raise Not_found
        | Node { left; data; count; right } ->
            if n < cardinal left then
              nth_inc n left
            else if n < cardinal left + count then
              data
            else
              nth_inc (n - cardinal left - count) right

      let rec nth_dec n = function
        | Empty -> raise Not_found
        | Node { left; data; count; right } ->
            if n < cardinal right then
              nth_dec n right
            else if n < cardinal right + count then
              data
            else
              nth_dec (n - cardinal right - count) left

      let rec elements_inc acc = function
        | Empty -> acc
        | Node { left; data; count; right } ->
            elements_inc
              (Array.fold_left (fun acc x -> x :: acc)
                (elements_inc acc right)
                (Array.make count data)) left

      let rec elements_dec acc = function
        | Empty -> acc
        | Node { left; data; count; right } ->
            elements_dec
              (Array.fold_left (fun acc x -> x :: acc)
                (elements_dec acc left)
                (Array.make count data)) right

      let rec take_inc n = function
        | Empty -> []
        | Node { left; data; count; right } ->
            if n < cardinal left then
              take_inc n left
            else if n < cardinal left + count then
              elements_inc (Array.to_list (Array.make (n - cardinal left) data)) left
            else
              elements_inc
                (Array.fold_left (fun acc x -> x :: acc)
                  (take_inc (n - cardinal left - count) right)
                  (Array.make count data)) left

      let rec take_dec n = function
        | Empty -> []
        | Node { left; data; count; right } ->
            if n < cardinal right then
              take_dec n right
            else if n < cardinal right + count then
              elements_dec (Array.to_list (Array.make (n - cardinal right) data)) right
            else
              elements_dec
                (Array.fold_left (fun acc x -> x :: acc)
                  (take_dec (n - cardinal right - count) left)
                  (Array.make count data)) right

      let elements_inc = elements_inc []
      let elements_dec = elements_dec []

      let rec fold_inc f acc = function
        | Empty -> acc
        | Node { left; data; count; right } ->
            fold_inc f
              (Array.fold_left f
                (fold_inc f acc left)
                (Array.make count data)) right

      let rec fold_dec f acc = function
        | Empty -> acc
        | Node { left; data; count; right } ->
            fold_dec f
              (Array.fold_right f
                (Array.make count data)
                (fold_dec f acc right)) left
      let fold_dec f t acc = fold_dec f acc t

      let rec min_elt t = fst (count_min_elt t)

      let rec max_elt = function
        | Empty -> raise Not_found
        | Node { data; right = Empty } -> data
        | Node { right } -> max_elt right
    end
end

module IntMultiSet = MultiSet.Make (struct
  type t = int
  let compare = compare
end)

let _ =
  Array.fold_left (fun (acc, q) -> function
    | None ->
        let n = IntMultiSet.cardinal q in
        Printf.printf "%d %d\n"
          (IntMultiSet.nth_inc ((n - 1) / 2) q)
          (acc +
            if n mod 2 = 1
            then 0
            else IntMultiSet.nth_inc (n / 2) q - IntMultiSet.nth_inc ((n - 1) / 2) q);
        (acc, q)
    | Some (a, b) ->
        (acc + b, IntMultiSet.add a 1 q)) (0, IntMultiSet.empty) @@
  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)


let n, k, s = Scanf.scanf " %d %d %s" @@ fun a b c -> a, b - 1, c
let _ = print_endline @@ String.mapi (fun i c -> if i = k then Char.lowercase c else c) 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


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

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.


let () =
  print_endline @@
  Scanf.scanf "%2d %2d" @@ fun a b ->
  if a <= 12 && b <= 12 then "AMBIGUOUS"
  else if a <= 12 then "MMYY"
  else if b <= 12 then "YYMM"
  else "NA"


open Batteries
let n, k = Scanf.sscanf (read_line()) "%d %d" (fun n k ->n, k)
let rec how_many n target =
  if n >= target then 0 else 1 + how_many (n*2) target

let rec n_loop i =
  if i > n then 0. else(
    ((1. /. 2.) ** (float_of_int @@ how_many i k)) *. (1. /. (float_of_int n)) +. (n_loop @@ i + 1))

let () = Printf.printf "%.10f\n" @@ n_loop 1

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 n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let p = 1. /. float n
let log2 n = log n /. log 2.
let ans = ref 0.
let _ =
  for i = 1 to n do
    let j = max 0. @@ ceil @@ log2 @@ float k /. float i in
    ans := !ans +. p *. 0.5 ** j done;
  Printf.printf "%.12f\n" !ans


let log2 b = (log10 b) /. (log10 2.)

let () =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let sum = ref 0. in
  for i = 1 to n do
    let n, k = float_of_int n, float_of_int k in
    let i' = float_of_int i in
    let cnt = let v = log2 (k /. i') in if v < 0. then 0. else v in
    let cnt = ceil cnt in
    let p = (0.5 ** cnt) /. n in
    sum := !sum +. p
  done;
  !sum |> print_float


let tap f x = f x; x

let n = Scanf.sscanf (read_line ()) "%d" @@ fun n  -> n
let e = Array.init (n - 1) @@ fun _ -> Scanf.sscanf (read_line ()) "%d %d %d" @@ fun u v w -> (u, v, w)

let e = tap
  (fun tbl -> Array.iter (fun (u, v, w) -> Hashtbl.add tbl (u - 1) ((v - 1), w); Hashtbl.add tbl (v - 1) ((u - 1), w)) e)
  (Hashtbl.create n)

let f d =
  let que = Queue.create () in
  Queue.add (0, 0) que;
  while not (Queue.is_empty que) do
    let (i, w) = Queue.pop que in
    d.(i) <- w;
    List.iter (fun (a, b) -> if d.(a) = -1 then Queue.add (a, w + b) que) @@ Hashtbl.find_all e i
  done

let () =
  let d = Array.make n (-1) in
  f d;
  d |> Array.map (fun i -> string_of_int (i mod 2)) |> Array.iter print_endline

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


(* 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) :: g.(u);
      g.(v) <- (u, w mod 2) :: 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 @@ c lxor w in List.iter f g.(v) in
  dfs 0 (-1) 0;
  cs |> Array.iter @@ Printf.printf "%d\n"


let () = Scanf.scanf "%d\n" @@ fun n ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d %d\n" @@ fun u v w ->
      es.(u - 1) <- (v - 1, w) :: es.(u - 1);
      es.(v - 1) <- (u - 1, w) :: es.(v - 1)
  done;
  let colours = Array.make n None in
  let rec visit c v =
    match colours.(v) with
    | Some _ -> ()
    | None ->
        colours.(v) <- Some c;
        List.iter (fun (u, w) -> visit (c lxor (w land 1)) u) es.(v) in
  visit 0 0;
  Array.iter (function
    | None -> ()
    | Some c -> Printf.printf "%d\n" c) colours


(* https://atcoder.jp/contests/atc001/tasks/unionfind_a *)
open Printf
open Scanf

class unionfind size =
  object(self)
    val mutable forest = [|(0,0)|]
    initializer begin
      forest <- Array.init size (fun x -> (x,1))
    end
    method forest () = begin
      forest
    end
    method print_forest () = begin
      let _ = Array.iter (fun x -> Printf.printf "(%d,%d);" (fst x) (snd x)) forest in
      print_newline()
    end
    method group_count () = begin
      let count = ref 0 in
      let _ = Array.iteri (fun i x -> if i = fst x then count := !count + 1) forest in
      !count
    end
    method find i = begin
      let (index, size) = forest.(i) in
      if (i = index) then (i, size)
      else
        let (nxt_index, nxt_size) = self#find index in
        forest.(i) <- (nxt_index, nxt_size);
        (nxt_index, nxt_size)
    end

    method union i j = begin
      let (x, x_size) = self#find i in
      let (y, y_size) = self#find j in

      if (x = y) then ()
      else
        let () = forest.(x) <- (y, x_size + y_size) in
        forest.(y) <- (y, x_size + y_size)
    end
  end

(*
let t = new unionfind 5;;
t#union 0 1;;
t#union 3 4;;
t#forest();;
t#find 0;;
*)

let (n,m) = sscanf (read_line ()) "%d %d" (fun a b -> (a,b))
let query = Array.make m (0,0,0);;
let () =
for i = 0 to m-1 do
  query.(i) <- sscanf (read_line ()) "%d %d %d" (fun x y z-> (x-1,y-1,z))
done;;

let forest = new unionfind n;;
let () = Array.iter (fun t -> let (x,y,z) = t in forest#union x y) query;;
let () = print_int (forest#group_count ()) in print_newline();;

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


let () =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let cnt = ref 0 in
  for i = 0 to n - 1 - (k - 1) do
    cnt := !cnt + 1
  done;
  print_int !cnt

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.scanf " %d %d %d %d" @@ fun a b c d -> a, b, c, d
let ans = ref 0
let _ =
  for i = 0 to n do
    for j = 0 to n do
      let rest = n - i * r - j * g in
      if rest >= 0 && rest mod b = 0 then incr ans 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