module WeightedDirectedGraph
  (Vertex : sig
    type t
    val compare : t -> t -> int
  end)
  (Weight : sig
    type t
    val zero : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  val dijkstra :
    (* 隣接リスト *)
    (Vertex.t -> (Vertex.t * Weight.t) list) ->
    (* 始点 *)
    Vertex.t ->
    (* 始点から辿り着けなければNoneを返す *)
    (Vertex.t -> Weight.t option)
end =
struct
  module WMap = Map.Make (Weight)
  module VMap = Map.Make (Vertex)

  (* ダイクストラ法のメインループ *)
  (* d に入っていない頂点への距離は無限大とみなす *)
  let rec dijkstra_aux e (d, q) =
    match WMap.min_binding q with
    | exception Not_found -> d
    | (w, us) ->
        dijkstra_aux e @@ List.fold_left (fun (d, q) u ->
          if Weight.compare (VMap.find u d) w < 0
          (* 既に頂点uを訪れていた *)
          then (d, q)
          (* w = d.(u) *)
          else List.fold_left (fun (d, q) (v, c) ->
            let open Weight in
            if
              (* d.(v) <= d.(u) + c *)
              try Weight.compare (VMap.find v d) (w + c) <= 0
              with Not_found -> false (* d.(v) は無限大 *)
            then (d, q)
            else
              VMap.add v (w + c) d,
              WMap.add (w + c) (v :: try WMap.find (w + c) q with Not_found -> []) q)
          (d, q) (e u)) (d, WMap.remove w q) us

  let dijkstra e s =
    let d =
      dijkstra_aux e
        (VMap.singleton s Weight.zero, WMap.singleton Weight.zero [s]) in
    fun t -> try Some (VMap.find t d) with Not_found -> None
end

module G = WeightedDirectedGraph
  (struct
    type t = int * int
    let compare = compare
  end)
  (struct
    type t = int
    let zero = 0
    let ( + ) = ( + )
    let compare = compare
  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 %d\n" @@ fun p q c ->
      es.(p - 1) <- (q - 1, c) :: es.(p - 1);
      es.(q - 1) <- (p - 1, c) :: es.(q - 1)
  done;
  match
    G.dijkstra (function
      | (v, 0) -> List.map (fun (_, c) -> ((v, c), 1)) es.(v)
      | (v, c) -> ((v, 0), 0) :: List.concat (List.map (fun (v, c') -> if c = c' then [((v, c), 0)] else []) es.(v))) (0, 0) (n - 1, 0)
  with
  | None -> print_endline "-1"
  | Some d -> Printf.printf "%d\n" d

Score : 600 points

Problem Statement

Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.

The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This line is operated by company c_i.

You can change trains at a station where multiple lines are available.

The fare system used in this subway system is a bit strange. When a passenger only uses lines that are operated by the same company, the fare is 1 yen (the currency of Japan). Whenever a passenger changes to a line that is operated by a different company from the current line, the passenger is charged an additional fare of 1 yen. In a case where a passenger who changed from some company A's line to another company's line changes to company A's line again, the additional fare is incurred again.

Snuke is now at station 1 and wants to travel to station N by subway. Find the minimum required fare.

Constraints

2 \leq N \leq 10^5

0 \leq M \leq 2×10^5

1 \leq p_i \leq N (1 \leq i \leq M)

1 \leq q_i \leq N (1 \leq i \leq M)

1 \leq c_i \leq 10^6 (1 \leq i \leq M)

p_i \neq q_i (1 \leq i \leq M)

Input

The input is given from Standard Input in the following format:

N M
p_1 q_1 c_1
:
p_M q_M c_M

Output

Print the minimum required fare. If it is impossible to get to station N by subway, print -1 instead.

Sample Input 1

3 3
1 2 1
2 3 1
3 1 2

Sample Output 1

1

Use company 1's lines: 1 → 2 → 3. The fare is 1 yen.

Sample Input 2

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

Sample Output 2

2

First, use company 1's lines: 1 → 3 → 2 → 5 → 6. Then, use company 5's lines: 6 → 7 → 8. The fare is 2 yen.

Sample Input 3

2 0

Sample Output 3

-1


exception Found of int

module IntSet = Set.Make (struct
  type t = int
  let compare = compare
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 %d\n" @@ fun p q c ->
      es.(p - 1) <- (c, q - 1) :: es.(p - 1);
      es.(q - 1) <- (c, p - 1) :: es.(q - 1)
  done;
  let visited = Array.make n IntSet.empty in
  let rec bfs01 d t = function
    | [] -> ()
    | cvs ->
        List.map (fun (c, v) -> dfs t c d [] v) cvs
        |> List.concat
        |> bfs01 (1 + d) t
  and dfs t c d acc v =
    if IntSet.mem c visited.(v) then acc
    else begin
      (if v = t then raise (Found d));
      visited.(v) <- IntSet.add c visited.(v);
      List.fold_left (fun acc (c', u) ->
        if c = c' then dfs t c d acc u
        else (c', u) :: acc) acc es.(v)
    end in
  try
    bfs01 1 (n - 1) es.(0);
    print_endline "-1"
  with Found d -> Printf.printf "%d\n" d

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

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


module IntSet = Set.Make (struct
  type t = int
  let compare = compare
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 %d\n" @@ fun p q c ->
      es.(p - 1) <- (c, q - 1) :: es.(p - 1);
      es.(q - 1) <- (c, p - 1) :: es.(q - 1)
  done;
  let visited = Array.make n IntSet.empty in
  let dist = Array.make n None in
  let rec bfs01 d = function
    | [] -> ()
    | cvs ->
        List.map (fun (c, v) -> dfs c d [] v) cvs
        |> List.concat
        |> bfs01 (1 + d)
  and dfs c d acc v =
    if IntSet.mem c visited.(v) then acc
    else begin
      visited.(v) <- IntSet.add c visited.(v);
      (if dist.(v) = None then dist.(v) <- Some d);
      List.fold_left (fun acc (c', u) ->
        if c = c' then dfs c d acc u
        else (c', u) :: acc) acc es.(v)
    end in
  dist.(0) <- Some 0;
  bfs01 1 es.(0);
  match dist.(n - 1) with
  | None -> print_endline "-1"
  | Some d -> Printf.printf "%d\n" d


Scanf.scanf "%d %d %d" (fun a b c ->
    let ( *@) = min in
    let check a b c =
        let q = a / 2 in
        b * c * (a - 2 * q)
    in
    Printf.printf "%d\n" @@ check a b c *@ check b c a *@ check c a b
)

Score : 200 points

Problem Statement

We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that:

There is at least one red block and at least one blue block.

The union of all red blocks forms a rectangular parallelepiped.

The union of all blue blocks forms a rectangular parallelepiped.

Snuke wants to minimize the difference between the number of red blocks and the number of blue blocks. Find the minimum possible difference.

Constraints

2≤A,B,C≤10^9

Input

The input is given from Standard Input in the following format:

A B C

Output

Print the minimum possible difference between the number of red blocks and the number of blue blocks.

Sample Input 1

3 3 3

Sample Output 1

9

For example, Snuke can paint the blocks as shown in the diagram below.
There are 9 red blocks and 18 blue blocks, thus the difference is 9.

Sample Input 2

2 2 4

Sample Output 2

0

For example, Snuke can paint the blocks as shown in the diagram below.
There are 8 red blocks and 8 blue blocks, thus the difference is 0.

Sample Input 3

5 3 5

Sample Output 3

15

For example, Snuke can paint the blocks as shown in the diagram below.
There are 45 red blocks and 30 blue blocks, thus the difference is 9.


let a, b, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let m, p = if a > b then if a > c then a, b * c else c, a * b else if b > c then b, a * c else c, a * b
let _ = Printf.printf "%d\n" @@ if a mod 2 = 0 || b mod 2 = 0 || c mod 2 = 0 then 0 else (m - m / 2 * 2) * p


let f x y z = (x - x/2*2) * y * z
let _ = Printf.printf "%d\n" @@ Scanf.scanf "%d %d %d" @@ fun a b c ->
  min (f a b c) (min (f b c a) (f c a b))


let () =
	let n, k, x, y = Scanf.scanf "%d\n%d\n%d\n%d\n" (fun a b c d -> a,b,c,d) in
    Printf.printf "%d\n" ((if n<=k then 0 else (k-n)*y) + n*x)

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

The input is given from Standard Input in the following format:

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


let n = read_int ()
let k = read_int ()
let x = read_int ()
let y = read_int ()

let () =
  if n > k then
    begin print_int @@ k * x + (n - k) * y; print_newline () end
  else
    begin print_int @@ n * x; print_newline () end


(* O(n) *)
let w = read_line ()
let n = String.length w
let _ =
  for i = Char.code 'a' to Char.code 'z' do
    let c = ref 0 in
    String.iter (fun x -> if x = Char.chr i then incr c) w;
    if !c mod 2 <> 0 then (print_endline "No"; exit 0)
  done;
  print_endline "Yes"

Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

The input is given from Standard Input in the following format:

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


let arr_of_str s = Array.init (String.length s) (fun i -> s.[i])
let f b c = b lxor (1 lsl (int_of_char c - 97))
let () =
  let st = Scanf.scanf "%s" arr_of_str |> Array.fold_left f 0 in
  print_endline (if st = 0 then "Yes" else "No")


open Printf
let input_int_array n =
	Array.init n (fun _ -> Scanf.scanf " %d" (fun v -> v))

let get_int () = Scanf.scanf " %d" (fun v -> v)
let get_2_ints () = Scanf.scanf " %d %d" (fun u v -> u,v)
let get_3_ints () = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w)
let get_4_ints () = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x)
let get_5_ints () = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)

module Int64 = struct
	include Int64
	let (+|) p q = Int64.add p q
	let (-|) p q = Int64.sub p q
	let ( *|) p q = Int64.mul p q
	let (/|) p q = Int64.div p q
	let (<|) p q =
		if Int64.compare p q < 0 then true
		else false
	let (>|) p q =
		if Int64.compare p q > 0 then true
		else false
	let (>=|) p q = not (p < q)
	let (<=|) p q = not (p > q)
	let labs p = if p <| 0L then -1L*|p else p
	let (~|) p = Int64.of_int p
end

let dump_2darr f a =
	Array.fold_left (fun u v ->
		u ^ Array.fold_left (fun u v -> u ^ (f v) ^ ",") "" v ^ ";\n"
	) "" a |> print_endline

let () =
	let n,a = get_2_ints ()
	in let ar = input_int_array n
	in let mx = (Array.fold_left max 0 ar)*n
	in let open Bigarray in let open Int64
	in
	let dp = Bigarray.Array3.create int64 c_layout (n+5) (n+5) (mx+1)
	in dp.{0,0,0} <- 1L;
	for i=0 to n-1 do
		for j=0 to n do
			for k=0 to mx do
				dp.{i+1,j,k} <- dp.{i,j,k} +| (
					let v = k-ar.(i) in
					if j>=1 && v>=0 then dp.{i,j-1,v} else 0L
				)
			done
		done
	done;
	let s = ref 0L in
	for k=1 to n do
		if a*k <= mx then
		s := !s +| dp.{n,k,a*k}
	done;
	!s |> printf "%Ld\n"

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

The input is given from Standard Input in the following format:

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


let s = read_line ()
let f = String.contains s
let _ = print_endline @@ if f 'N' = f 'S' && f 'E' = f 'W' then "Yes" else "No"

Score : 200 points

Problem Statement

Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip.
At the beginning of Day 1, he is at home. His plan is described in a string S of length N.
On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:

North if the i-th letter of S is N

West if the i-th letter of S is W

South if the i-th letter of S is S

East if the i-th letter of S is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N.

Constraints

1 ≦ | S | ≦ 1000

S consists of the letters N, W, S, E.

Input

The input is given from Standard Input in the following format:

S

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of 1 on each day, he will be back at home at the end of day 4.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No


let arr_of_str s = Array.init (String.length s) (fun i -> s.[i])
let _ = print_endline @@ Scanf.scanf "%s" @@ fun d ->
  let n,w,s,e =
    arr_of_str d |> Array.fold_left (fun (n,w,s,e) c ->
    (n||c='N', w||c='W', s||c='S', e||c='E')) (0=1,0=1,0=1,0=1)
  in if n = s && w = e then "Yes" else "No"


Scanf.scanf "%d" @@ fun n ->
  Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0))
  |> Array.fold_left (fun (s, l) x ->
      let c = if x = 0 then 0 else l + x mod 2 in
      s + x/2 + c/2, c mod 2) (0, 0)
  |> fst |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it.
He has A_i cards with an integer i.

Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1.

Snuke wants to create the maximum number of pairs from his cards, on the condition that no card should be used in multiple pairs. Find the maximum number of pairs that he can create.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

All input values are integers.

Input

The input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the maximum number of pairs that Snuke can create.

Sample Input 1

4
4
0
3
2

Sample Output 1

4

For example, Snuke can create the following four pairs: (1,1),(1,1),(3,4),(3,4).

Sample Input 2

8
2
0
1
6
0
8
2
1

Sample Output 2

9


open Bytes
let s = read_line ()
let b = of_string s
let i = ref 0
let _ = String.iter (function 'B' -> i := max 0 @@ !i - 1 | c -> set b !i c; incr i) s; print_endline @@ sub_string b 0 !i

Score : 200 points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string s, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

1 ≦ |s| ≦ 10 (|s| denotes the length of s)

s consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

The input is given from Standard Input in the following format:

s

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.


let step out key =
    match key with
    | "B" ->
        begin match out with
        | [] -> []
        | _ :: xs -> xs
        end
    | _ ->
        key :: out

let () =
    read_line ()
    |> Str.split (Str.regexp "")
    |> List.fold_left step []
    |> List.rev
    |> String.concat ""
    |> print_endline


let rec upper_bound l r p =
  if r <= 1 + l
  then l
  else let m = (l + r) / 2 in
       if p m
       then upper_bound m r p
       else upper_bound l m p

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ ->
    Scanf.scanf "%d " @@ fun a -> a in
  let cost x =
    Array.fold_left ( + ) 0 @@
    Array.map (fun y -> (x - y) * (x - y)) as_ in
  Printf.printf "%d\n" @@ cost @@ upper_bound (-10000) 10000 @@ fun i ->
    cost i - cost (i - 1) <= 0

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


let a, b = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = print_endline @@ if a * b <= 0 then "Zero" else if a > 0 || (b - a) mod 2 = 1 then "Positive" else "Negative"

Problem Statement

You are given two integers a and b (a≤b). Determine if the product of the integers a, a+1, …, b is positive, negative or zero.

Constraints

a and b are integers.

-10^9≤a≤b≤10^9

Partial Score

In test cases worth 100 points, -10≤a≤b≤10.

Input

The input is given from Standard Input in the following format:

a b

Output

If the product is positive, print Positive. If it is negative, print Negative. If it is zero, print Zero.

Sample Input 1

1 3

Sample Output 1

Positive

1×2×3=6 is positive.

Sample Input 2

-3 -1

Sample Output 2

Negative

(-3)×(-2)×(-1)=-6 is negative.

Sample Input 3

-1 1

Sample Output 3

Zero

(-1)×0×1=0.


let rs, cs, xys = Scanf.(Array.(scanf "%d %d" @@ fun n m -> make n 0, make n 1, init m @@ fun _ -> scanf " %d %d" @@ fun a b -> a - 1, b - 1))
let _ = rs.(0) <- 1; Array.(iter (fun (x, y) -> rs.(y) <- max rs.(y) rs.(x); cs.(y) <- cs.(y) + 1; cs.(x) <- cs.(x) - 1; rs.(x) <- min rs.(x) cs.(x)) xys; fold_left (+) 0 rs) |> Printf.printf "%d\n"

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

The input is given from Standard Input in the following format:

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


let rec power ( * ) one m = function
  | 0 -> one
  | n when n mod 2 = 0 ->
      power ( * ) one (m * m) (n / 2)
  | n ->
      m * power ( * ) one m (n - 1)

let memoize n f =
  let dp = Hashtbl.create n in
  let rec get x k =
    try k @@ Hashtbl.find dp x with
    | Not_found ->
        f get x @@ fun y ->
          Hashtbl.add dp x y; k y in get

let m = 1000000007
let ( +^ ) x y = (x + y) mod m
let ( *^ ) x y = (x * y) mod m
let inv n = power ( *^ ) 1 n (m - 2)

let () = Scanf.scanf "%d %d %d %d" @@ fun h w a b ->
  let fact = memoize (h + w) @@ fun fact n k ->
    if n <= 1 then k 1
    else fact (n - 1) @@ fun x -> k @@ n *^ x in
  let fact n = fact n @@ fun x -> x in
  let inv_fact = memoize (h + w) @@ fun inv_fact n k ->
    if n <= 1 then k 1
    else inv_fact (n - 1) @@ fun x -> k @@ inv n *^ x in
  let inv_fact n = inv_fact n @@ fun x -> x in
  Printf.printf "%d\n" @@ Array.fold_left ( +^ ) 0 @@ Array.init (h - a) @@ fun i ->
    fact(i + b - 1) *^ fact(h + w - 2 - i - b) *^ inv_fact(i) *^ inv_fact(b - 1) *^ inv_fact(h - i - 1) *^ inv_fact(w - b - 1)

Score : 400 points

Problem Statement

We have a large square grid with H rows and W columns.
Iroha is now standing in the top-left cell.
She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.

However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.

Find the number of ways she can travel to the bottom-right cell.

Since this number can be extremely large, print the number modulo 10^9+7.

Constraints

1 ≦ H, W ≦ 100,000

1 ≦ A < H

1 ≦ B < W

Input

The input is given from Standard Input in the following format:

H W A B

Output

Print the number of ways she can travel to the bottom-right cell, modulo 10^9+7.

Sample Input 1

2 3 1 1

Sample Output 1

2

We have a 2×3 grid, but entering the bottom-left cell is forbidden. The number of ways to travel is two: "Right, Right, Down" and "Right, Down, Right".

Sample Input 2

10 7 3 4

Sample Output 2

3570

There are 12 forbidden cells.

Sample Input 3

100000 100000 99999 99999

Sample Output 3

1

Sample Input 4

100000 100000 44444 55555

Sample Output 4

738162020


let () = Scanf.scanf "%d %d %d" (fun a b c -> if a+b+c=17 && a*b*c=175 then "YES" else "NO")
|> print_endline

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

The input is given from Standard Input in the following format:

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


let make_list f t step =
  let rec make_list_inner c t lst =
    if c >= t then lst else make_list_inner (c+step) t (c::lst)
  in
  List.rev (make_list_inner f t [])

let print_list str list = Printf.printf "%s: [ " str; List.iter (fun (q,r) -> Printf.printf "(%d, %d); " q r) list; Printf.printf "]\n"

let solve a b c = match (a,b,c) with
    (5,7,5) -> "YES"
  | (7,5,5) -> "YES"
  | (5,5,7) -> "YES"
  | _ -> "NO"

let () =
  let rec read () =
    try let ans = (Scanf.scanf "%d %d %d\n" solve ) in
        Printf.printf "%s\n" ans
    with End_of_file -> ()
  in
  read ()
;;


let js = Array.make 10 true
let rec f n = if n <= 9 then js.(n) else js.(n mod 10) && f (n / 10)
let _ = Scanf.scanf " %d %d" @@ fun n k -> for _ = 1 to k do js.(Scanf.scanf " %d" (+) 0) <- false done; for i = n to 100000 do if f i then (Printf.printf "%d\n" i; exit 0) done

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

The input is given from Standard Input in the following format:

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


let n, k = Scanf.scanf "%d %d\n" (fun a b -> a, b)
let ds =
  Array.init k (fun _ -> Scanf.scanf "%c " (fun x -> x))
  |> Array.to_list

let rec solve p =
  let s = string_of_int p in
  if List.exists (fun c -> String.contains s c) ds then solve (p + 1)
  else p

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


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

let rec tabulate n f =
  let rec loop acc m =
    if m < n then loop (f m :: acc) (m + 1)
    else List.rev acc in
  loop [] 0

let rec solve ds = function
  | 0 -> (0, false)
  | n ->
      let m, n = n mod 10, n / 10 in
      tabulate 10 (fun n -> n)
      |> List.filter (fun n -> IntSet.mem n ds && m <= n)
      |> (function
          | [] -> (10 * fst (solve ds (n + 1)) + IntSet.min_elt ds, true)
          | m :: _ ->
              match solve ds n with
              | (n, false) -> (10 * n + m, false)
              | (n, true) -> (10 * n + IntSet.min_elt ds, true))

let () =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let ds =
    IntSet.diff
      (IntSet.of_list (tabulate 10 (fun k -> k)))
      (IntSet.of_list (tabulate k (fun _ -> Scanf.scanf "%d " (fun d -> d)))) in
  Printf.printf "%d\n" (fst (solve ds n))


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

let rec tabulate n f =
  let rec loop acc m =
    if m < n then loop (f m :: acc) (m + 1)
    else List.rev acc in
  loop [] 0

let rec solve ds = function
  | 0 -> 0
  | n ->
      let m, n = n mod 10, n / 10 in
      tabulate 10 (fun n -> n)
      |> List.filter (fun n -> IntSet.mem n ds && m <= n)
      |> (function
          | [] -> 10 * solve ds (n + 1) + IntSet.min_elt ds
          | m :: _ -> 10 * solve ds n + m)

let () =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let ds =
    IntSet.diff
      (IntSet.of_list (tabulate 10 (fun k -> k)))
      (IntSet.of_list (tabulate k (fun _ -> Scanf.scanf "%d " (fun d -> d)))) in
  Printf.printf "%d\n" (solve ds n)


let modulo = 1000000007
let (+@) a b = (a + b) mod modulo
let ( *@ ) a b = (a * b) mod modulo

let rec mod_pow a n =
  if n <= 0 then 1
  else if n mod 2 = 1 then a *@ mod_pow a (n-1)
  else let h = mod_pow a (n/2) in h *@ h
let mod_inv a = mod_pow a (modulo-2)

let lim = 200010

let fact =
  let res = Array.make lim 1 in
  for i = 1 to lim-1 do res.(i) <- i *@ res.(i-1) done;
  res

let inv_fact = Array.map mod_inv fact

let comb n k =
  if n < k then 0 else fact.(n) *@ inv_fact.(k) *@ inv_fact.(n-k)

let r h w = comb (h+w) h

let () =
  Scanf.scanf "%d %d %d %d" @@ fun h w a b ->
  Array.init (h-a) (fun i -> r i (b-1) *@ r (h-1-i) (w-b-1))
  |> Array.fold_left (+@) 0
  |> Printf.printf "%d\n"


open Batteries
open Printf
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let l_lst = Array.to_list @@ Array.init (n*2) (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  let len = List.length l_lst in
  List.sort compare l_lst |>
  List.filteri (fun i x -> i mod 2 = 0 && i <> len-1) |>
  List.fold_left (+) 0 |>
  Printf.printf "%d\n"

Score : 200 points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make N servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.

What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

1≦N≦100

1≦L_i≦100

For each i, L_i is an integer.

Input

The input is given from Standard Input in the following format:

N
L_1 L_2 ... L_{2N}

Output

Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135


let id x = x

let read_ints =
  let rec aux acc = function
    | 0 -> acc
    | n -> aux ((Scanf.scanf "%d " id) :: acc) (n-1) in
  aux []

let odd_sum =
  let rec aux acc = function
    | [] -> acc
    | hd1 :: hd2 :: tl -> aux (hd1 + acc) tl in
  aux 0

let () =
  let n = Scanf.scanf "%d\n" id in
  let l = read_ints (2*n) in
  print_int (odd_sum (List.sort compare l))


let main =
    Scanf.sscanf (read_line()) "%d %d" (
        fun n x ->
            let rec gcd a b =
                if a < b
                then gcd b a
                else if b = 0
                then a
                else gcd b (a mod b)
            in
            print_int (3 * (n - gcd n x));
            print_string "\n"
    )

Score : 500 points

Problem Statement

Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.

Three mirrors of length N are set so that they form an equilateral triangle.
Let the vertices of the triangle be a, b and c.

Inside the triangle, the rifle is placed at the point p on segment ab such that ap = X.
(The size of the rifle is negligible.)
Now, the rifle is about to fire a ray of Mysterious Light in the direction of bc.

The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light.
There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror!
When the ray comes back to the rifle, the ray will be absorbed.

The following image shows the ray's trajectory where N = 5 and X = 2.

It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of N and X.
Find the total length of the ray's trajectory.

Constraints

2≦N≦10^{12}

1≦X≦N-1

N and X are integers.

Partial Points

300 points will be awarded for passing the test set satisfying N≦1000.

Another 200 points will be awarded for passing the test set without additional constraints.

Input

The input is given from Standard Input in the following format:

N X

Output

Print the total length of the ray's trajectory.

Sample Input 1

5 2

Sample Output 1

12

Refer to the image in the Problem Statement section.
The total length of the trajectory is 2+3+2+2+1+1+1 = 12.


let solve n x =
  let rec aux acc n x =
    if n = x then acc + x
    else if n > x then aux (2*x + acc) (n-x) x
    else aux (2*n + acc) (x-n) n in
  aux n (n-x) x

let () = print_int (Scanf.scanf "%d %d" solve)