(* O(n) *)
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let p = ref @@ -1
let xys = ref []
let _ =
  Array.sort (-) a_s;
  let i = ref 0 in while !p < 0 && !i < n do if a_s.(!i) >= 0 then p := !i; incr i done;
  if !p = -1 then p := n - 1
  else if !p = 0 then p := 1;
  for i = !p to n - 2 do
    xys := (a_s.(0), a_s.(i)) :: !xys;
    a_s.(0) <- a_s.(0) - a_s.(i)
  done;
  for i = 0 to !p - 1 do
    xys := (a_s.(n - 1), a_s.(i)) :: !xys;
    a_s.(n - 1) <- a_s.(n - 1) - a_s.(i)
  done;
  Printf.printf "%d\n" a_s.(n - 1);
  List.rev !xys |> List.iter @@ fun (x, y) -> Printf.printf "%d %d\n" x y

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 () =
    let main () =
        let p, q, r = Scanf.sscanf (read_line ()) "%d %d %d" (fun a b c -> a, b, c) in
        Printf.printf "%d\n" (min (min (p+q) (q+r)) (r+p))
    in
    main ()

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

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

Submitted source-code file size, in bytes.

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

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


let () =
    let main () =
        let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun n m -> n, m) in
        let a = Array.init m (fun _ -> int_of_string (read_line ())) in
        let f = Array.make (n + 1) true in
        let () = Array.iter (fun v -> f.(v) <- false) a in
        let c = Array.make (n + 1) 0 in
        let () = c.(0) <- 1 in
        let mm = 1_000_000_007 in
        for i = 0 to n - 1 do
            if               f.(i + 1) then c.(i + 1) <- (c.(i + 1) + c.(i)) mod mm;
            if i + 2 <= n && f.(i + 2) then c.(i + 2) <- (c.(i + 2) + c.(i)) mod mm
        done;
        Printf.printf "%d\n" c.(n)
    in
    main ()

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 rec pow ( * ) z a n =
  if n = 0 then z
  else if n mod 2 = 1 then a * (pow ( * ) z a (n-1))
  else let h = pow ( * ) z a (n/2) in h * h

let rec intpow = pow ( * ) 1

let i3 = [| [|1; 0; 0|]; [|0; 1; 0|]; [|0; 0; 1|] |]

let () =
  Scanf.scanf "%d %d %d %d" @@ fun l a b modulo ->

  let (+@) a b = (a + b + modulo) mod modulo in
  let modmul a b = (a * b) mod modulo in
  let modpow = pow modmul 1 in

  let matmul a b =
    let m = Array.length b in
    Array.init (Array.length a) (fun i ->
    Array.init (Array.length b.(0)) (fun j ->
      fold_for 0 m 0 (fun k s -> s +@ modmul a.(i).(k) b.(k).(j))))
  in

  let rec loop d z =
    if d > 18 then z else
    let i = (intpow 10 (d-1) - a + b - 1) / b |> max 0 in
    let j = (intpow 10 d - a + b - 1) / b |> min l in
    let r = [| [| z; a +@ modmul b i; 1 |] |] in
    let m = [| [| modpow 10 d; 0; 0 |]; [| 1; 1; 0 |]; [| 0; b mod modulo; 1 |]; |] in
    let mc = pow matmul i3 m (j-i) in
    let r' = matmul r mc in
    loop (d+1) r'.(0).(0)
  in
  loop 1 0 |> Printf.printf "%d\n"

Score : 600 points

Problem Statement

There is an arithmetic progression with L terms: s_0, s_1, s_2, ... , s_{L-1}.

The initial term is A, and the common difference is B. That is, s_i = A + B \times i holds.

Consider the integer obtained by concatenating the terms written in base ten without leading zeros. For example, the sequence 3, 7, 11, 15, 19 would be concatenated into 37111519. What is the remainder when that integer is divided by M?

Constraints

All values in input are integers.

1 \leq L, A, B < 10^{18}

2 \leq M \leq 10^9

All terms in the arithmetic progression are less than 10^{18}.

Input

Input is given from Standard Input in the following format:

L A B M

Output

Print the remainder when the integer obtained by concatenating the terms is divided by M.

Sample Input 1

5 3 4 10007

Sample Output 1

5563

Our arithmetic progression is 3, 7, 11, 15, 19, so the answer is 37111519 mod 10007, that is, 5563.

Sample Input 2

4 8 1 1000000

Sample Output 2

891011

Sample Input 3

107 10000000000007 1000000000000007 998244353

Sample Output 3

39122908


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

let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let ab = Array.init (n - 1) @@ fun _ -> Scanf.sscanf (read_line ()) "%d %d" @@ fun a b -> (a - 1, b - 1)
let c = List.sort (fun a b -> b - a) @@ List.map int_of_string @@ split_string @@ read_line ()

let rec sum = function | ([] | _ :: []) -> 0 | x :: xs -> x + sum xs
let sum = sum c

let rec find_index i arr f =
  if Array.length arr = i then -1
  else if f arr.(i) then i
  else find_index (i + 1) arr f
let find_index = find_index 0 ab

let s = Array.make n false
let ans = Array.make n 0

let rec loop = function
  | [] -> ()
  | x :: xs ->
    let idx = find_index (fun (a, b) -> a + b > 0 && (s.(a) || s.(b))) in
    let (a, b) = ab.(idx) in
    ab.(idx) <- (-1, -1);
    if s.(a) then begin
      s.(b) <- true; ans.(b) <- x
    end
    else begin
      s.(a) <- true; ans.(a) <- x
    end;
    loop xs

let () =
  match c with
    | x :: [] -> print_endline "0"
    | x :: y :: xs ->
      let (a, b) = ab.(0) in
      Printf.printf "%d %d\n" a b;
      ab.(0) <- (-1, -1);
      ans.(a) <- x; s.(a) <- true;
      ans.(b) <- y; s.(b) <- true;
      loop xs;
      print_endline @@ String.concat " " @@ Array.to_list @@ Array.map string_of_int ans;
    | _ -> failwith ""

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


let applepie a p = (a * 3 + p) / 2

let a, p = Scanf.sscanf (read_line ()) "%d %d" (fun a p -> (a, p))
let () = Printf.printf "%d\n" (applepie a p)

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58


open Printf
open Scanf

let solve a p = (3 * a + p) / 2

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


let () = Scanf.scanf "%d %d" @@ fun a p ->
  Printf.printf "%d\n" @@ (3 * a + p) / 2


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) 0 false (cur :: acc)
                | false, ' ' -> loop (i + 1) 0 false acc
                | true,  v   -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc
                | false, v   -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc
            )
        in
        List.rev (loop 0 0 false [])
    in
    let main () =
        let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun n m -> n, m) in
        let arr = Array.init m (fun _ -> List.tl (split (read_line ()))) in
        let p = Array.of_list (split (read_line ())) in
        let sw = Array.make m 0 in
        for i = 0 to m - 1 do
            sw.(i) <- List.fold_left (fun acc v -> acc lor (1 lsl (v - 1))) 0 arr.(i)
        done;
        let count bits =
            let rec loop i acc =
                if i = 0 then acc else loop (i / 2) (acc + i land 1)
            in
            loop bits 0
        in
        let forall bits switch p =
            let rec loop i =
                if i < 0 then true else
                if count (switch.(i) land bits) mod 2 = p.(i) then loop (i - 1) else false
            in
            loop (m - 1)
        in
        let rec loop i acc =
            if i < 0 then acc else
                let acc = if forall i sw p then acc + 1 else acc in
                loop (i - 1) acc
        in
        let ans = loop ((1 lsl n) - 1) 0 in
        Printf.printf "%d\n" ans
    in
    main ()

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


let _ = Scanf.sscanf (read_line ()) "%d %d" (fun a b ->
  match a with
  | a when a >= 13 -> print_endline (string_of_int b)
  | a when a >= 6 -> print_endline (string_of_int (b/2))
  | a -> print_endline "0"
)

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 () =
    let main () =
        let a, b = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> a, b) in
        Printf.printf "%d\n" (if a >= 13 then b else if a >= 6 then b / 2 else 0)
    in
    main ()


Scanf.scanf "%d %d %d" @@ fun r d x2000 ->
  let ans = ref x2000 in
  for i = 1 to 10 do
    ans := !ans * r - d;
    Printf.printf "%d\n" !ans
  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 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


let make_gate_list l r =
  let rec hoge l r =
    if l > r then
      []
    else
      l :: hoge (l + 1) r
  in
    hoge l r

let hikaku_lst lst1 lst2 =
  let hikaku n =
    List.filter (fun m -> n = m) lst2
  in
    List.map hikaku lst1 |> List.concat

let () = Scanf.scanf "%d %d\n" (fun n m ->
    let card_lst = make_gate_list 1 n in
    let rec loop i lst =
      if i = m then (*iは回数制限（最初のnに達したら終了）*)
      card_lst else
        let i = i + 1 in
        Scanf.scanf "%d %d\n" (fun l r ->
          let gate_list = make_gate_list l r in
          let ok_list = hikaku_lst gate_list lst in
          hikaku_lst ok_list (loop i ok_list)
        )
      in
    let lst = loop 0 card_lst in
     Printf.printf "%d" (List.length lst)
)

Score : 300 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

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

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

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

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

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

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

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

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let count = Array.make (n + 1) 0 in
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d\n" @@ fun l r ->
      count.(l - 1) <- count.(l - 1) + 1;
      count.(r) <- count.(r) - 1;
  done;
  for i = 1 to n do
    count.(i) <- count.(i - 1) + count.(i)
  done;
  Printf.printf "%d\n" @@
  Array.fold_right (fun c -> ( + ) @@ if c < m then 0 else 1) count 0


(* O((n+m)log(n+m)) *)
open Array
let n, m = Scanf.scanf " %d %d" @@ fun a b -> a, b
let a_s = init n @@ fun _ -> Scanf.scanf " %d" @@ fun a -> a, 1
let cbs = init m @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> b, a
let cards = make (n + m) (0, 0)
let rec f acc i r =
  if r <= 0 then acc
  else
    let x, c = cards.(i) in
    f (acc + x * min c r) (i + 1) @@ r - min c r
let _ =
  iteri (fun i a -> cards.(i) <- a) a_s;
  iteri (fun i cb -> cards.(n + i) <- cb) cbs;
  sort (fun x y -> compare y x) cards;
  f 0 0 n |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

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


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 () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let bcs = Array.init m @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun b c -> b, c in
  Printf.printf "%d\n" @@
  List.fold_left ( + ) 0 @@
  IntMultiSet.take_dec n @@
  Array.fold_right (fun a -> IntMultiSet.add a 1) as_ @@
  Array.fold_left (fun s (b, c) -> IntMultiSet.add c b s) IntMultiSet.empty bcs


let is_month n = 0 < n && n <= 12;;

let () = Scanf.scanf "%2d%2d" (fun s t ->
  (if (is_month s) && (is_month t) then "AMBIGUOUS"
  else if (is_month s) && (not (is_month t)) then "MMYY"
  else if (not (is_month s)) && (is_month t) then "YYMM"
  else "NA") |> print_string
);;

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.


(* O(n * log(k)) *)
Scanf.scanf "%d %d" @@ fun n k ->
  let rec find acc x =
    if x >= k then acc
    else find (acc *. 0.5) (x * 2) in
  let sum = ref 0. in
  for i = 1 to n do
    let p = find 1. i in
    sum := !sum +. p /. float n
  done;
  Printf.printf "%.12f\n" !sum

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 () =
    let main () =
        let n, k = Scanf.sscanf (read_line ()) "%d %d" (fun n k -> n, k) in
        let log2 j k =
            let rec loop c i =
                if c >= k then i else loop (c * 2) (i + 1)
            in
            loop j 0
        in
        let rec loop i acc =
            if i = 0 then acc else loop (i - 1) (acc +. 0.5 ** float (log2 i k))
        in
        let ans = loop n 0.0 /. float n in
        Printf.printf "%.10f\n" ans
    in
    main ()


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

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

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

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

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 () = Scanf.scanf "%d %d" @@ fun n k ->
    Printf.printf "%d" @@ n - k + 1

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 acc_ab n s =
  snd @@ Array.fold_left (fun (c, n) c' ->
    (c', n + if c = 'A' && c' = 'B' then 1 else 0)) ('_', n) @@
  Array.init (String.length s) (String.get s)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let ss = Array.init n @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let (a, b, ba) =
    Array.fold_left (fun (a, b, ba) s ->
      if s.[0] = 'B' && s.[String.length s - 1] = 'A' then (a, b, ba + 1)
      else if s.[0] = 'B' then (a, b + 1, ba)
      else if s.[String.length s - 1] = 'A' then (a + 1, b, ba)
      else (a, b, ba)) (0, 0, 0) ss in
  let n = min a @@ min b ba in
  Printf.printf "%d\n" @@
  Array.fold_left acc_ab 0 ss +
  if a <= 0 && b <= 0 then max 0 (ba - 1) else ba + min a b

Score : 400 points

Problem Statement

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

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

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

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

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


open Printf open Scanf
open Array

let count_substr s t =
  let ln = String.length in
  init (ln s - ln t + 1) (fun i ->
    if init (ln t) (fun j -> s.[i+j] = t.[j])
    |> fold_left (&&) true then 1 else 0
  ) |> fold_left (+) 0

let () = scanf " %d" @@ fun n ->
  let arr = init n (fun _ -> scanf " %s" @@ fun s -> s)
  in
  let kba,kbx,kxa,kab = ref 0,ref 0,ref 0,ref 0 in
  iter (fun s ->
    let bx = s.[0] = 'B' in
    let xa = s.[String.length s-1] = 'A' in
    let ba = bx && xa in
    if ba then incr kba
    else if bx then incr kbx
    else if xa then incr kxa;
    kab := !kab + count_substr s "AB"
  ) arr;
  let kba,kbx,kxa,kab = !kba,!kbx,!kxa,!kab in
  print_int @@ kab +
    if kba >= 1 then (
      (* B-A^B-A^...^B-A *)
      let pair_ba = kba - 1 in
      (* B-A^B-A^...^B-A ^ B- *)
      let add,kbx =
        if kbx > 0 then 1,kbx-1 else 0,kbx in
      (* -A ^ B-A^B-A^...^B-A*)
      let add,kxa =
        if kxa > 0 then add+1,kxa-1 else add,kxa in
      pair_ba + add + min kbx kxa
    ) else
      (* -A^B- ... -A^B- *)
      min kbx kxa


open Printf open Scanf
open Array

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

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

let () = scanf " %d" @@ fun n ->
  let arr = init n (fun _ -> scanf " %s" @@ fun s -> s)
  in
  let kab,kbx,kxa,krest = fold_left (fun (kab,kbx,kxa,krest) s ->
    let bx = s.[0] = 'B' in
    let xa = s.[String.length s-1] = 'A' in
    let ab = bx && xa in
    let kab = if ab then kab + 1 else kab in
    let kbx = if not ab then (
      if bx then kbx+1 else kbx
    ) else kbx in
    let kxa = if not ab then (
      if xa then kxa+1 else kxa
    ) else kxa in
    let krest = krest + count_substring s "AB"
    in
    (kab,kbx,kxa,krest)
  ) (0,0,0,0) arr in
  (* printf "%d %d %d %d\n" kab kbx kxa krest; *)
  let pair_ab = min kxa kbx in
  let kxa,kbx = kxa - pair_ab, kbx - pair_ab in
  print_int @@ krest + pair_ab +
    if kxa > 0 || kbx > 0 then 1 + max (kab - 1) 0
    else max (kab - 1) 0


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

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

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

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


let n = read_int ()
let i, ans = ref 1, ref 0
let f m = if m > 0 && n / m = n mod m then ans := !ans + m
let _ =
  while !i * !i <= n do if n mod !i = 0 then (f @@ !i - 1; f @@ n / !i - 1); incr i done;
  Printf.printf "%d\n" !ans

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


open Scanf
open Printf

let (a, b, t) = sscanf (read_line ()) "%d %d %d" (fun x y z -> (x, y, z));;

printf "%d\n" (b * (t / a))

Score : 100 points

Problem Statement

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

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

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

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

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

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

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


let _ =
  let a, b, t = Scanf.scanf "%f %d %f\n" (fun a b t -> a, b, t) in
  ((t +. 0.5) /. a)
  |> int_of_float
  |> ( * ) b
  |> print_int


let () =
	Scanf.scanf "%d %d %d\n"
	(fun a b t ->
		let tt = (float_of_int t) +. 0.5 in
		let aa = (float_of_int a) in
		(int_of_float (tt /. aa)) * b) |> print_int


open Printf open Scanf
open Array

let () = scanf " %d" @@ fun n ->
  init n (fun _ -> scanf " %d" @@ fun v -> v)
  |> map (fun v -> scanf " %d" @@ fun c -> max (v-c) 0)
  |> fold_left (+) 0
  |> print_int

Score : 200 points

Problem Statement

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

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

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

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

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

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

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


let () =
	let n = Scanf.scanf "%d\n" (fun x -> x) in
	let v = Array.to_list (Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x))) in
	let  c = Array.to_list (Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x))) in
	let sabun = List.map2 (fun a b -> a -b) v c in
	List.fold_left (fun a b -> if b > 0 then a + b else a) 0 sabun
	|> print_int


let () =
  Scanf.scanf "%d" @@ fun n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  Array.sort (fun x y -> abs x - abs y) a;

  let s = Array.fold_left (fun x y -> x + abs y) 0 a in
  let c = Array.fold_left (fun x y -> if y < 0 then x+1 else x) 0 a in
  Printf.printf "%d\n" (if c mod 2 = 0 then s else s - 2 * abs a.(0))

Score : 400 points

Problem Statement

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

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

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

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

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

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

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

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

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

Sample Output 3

10000000000

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


let () =
	Scanf.scanf "%d %d %d\n"
	(fun a b c -> if a < c && c < b then "Yes " else "No ")
	|> print_string

Score : 100 points

Problem Statement

There are three houses on a number line: House 1, 2 and 3, with coordinates A, B and C, respectively.
Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Constraints

0\leq A,B,C\leq 100

A, B and C are distinct integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print Yes if we pass the coordinate of House 3 on the straight way from House 1 to House 2 without making a detour, and print No otherwise.

Sample Input 1

3 8 5

Sample Output 1

Yes

We pass the coordinate 5 on the straight way from the house at coordinate 3 to the house at coordinate 8.

Sample Input 2

7 3 1

Sample Output 2

No

Sample Input 3

10 2 4

Sample Output 3

Yes

Sample Input 4

31 41 59

Sample Output 4

No


let _ =
  let a, b, c = Scanf.scanf "%d %d %d\n" (fun a b c -> a, b, c) in
  print_string @@ if a <= c && c <= b then "Yes" else "No"


open Printf open Scanf
open Array

let print_array f a = Array.iter (fun v -> printf "%s " @@ f v) a; print_newline ()

let () = scanf " %d %s" @@ fun n s ->
  let a = init n (fun i -> s.[i]) in
  let res = ref 0 in
  let rec lp i black =
    let rec lp2 i =
      if i<n && a.(i) = '.' then lp2 (i+1)
      else i
    in
    if i=n then ()
    else if a.(i-1) = '#' && black > 0
      && a.(i) = '.' then (
      let j = lp2 @@ i+1 in
      let white = j - i in
      if black >= white then (
        res := !res + white;
        lp j (black + white);
      ) else (
        res := !res + black;
        lp j 0;
      );
    ) else lp (i+1) (black + if a.(i) = '#' then 1 else 0)
  in
  lp 1 (if a.(0) = '#' then 1 else 0);
  print_int !res;

Score : 300 points

Problem Statement

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

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

3
#.#

Sample Output 1

1

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

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


let button a b =
  if a = b then a + b else (max a b) * 2 - 1

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

Score : 100 points

Problem Statement

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

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

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

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

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

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


let () = Scanf.scanf "%d %d" (fun a b -> (
  (if a = b then a + b
  else if a > b then 2 * a - 1
  else 2 * b - 1)
  |> print_int;
));;


let _ = Scanf.sscanf (read_line ()) "%d %d" (fun a b ->
  match a with
  | a when a = b -> print_endline (string_of_int (a * 2))
  | a when a > b -> print_endline (string_of_int (a + (a-1)))
  | _ -> print_endline (string_of_int (b + (b-1)))
)


let solve = Array.fold_left (fun ((c, c'), n) d ->
  (c', c), n + if c = d then 1 else 0)

let () =
  let s = read_line () in
  let s = Array.init (String.length s) (String.get s) in
  Printf.printf "%d\n" @@ min
    (snd @@ solve (('0', '1'), 0) s)
    (snd @@ solve (('1', '0'), 0) s)

Score : 300 points

Problem Statement

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

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

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

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

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

000

Sample Output 1

1

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

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


open Scanf
open Printf

let (n,k) = sscanf (read_line ()) "%d %d" (fun x y -> (x,y));;
let str = sscanf (read_line ()) "%s" (fun x -> x);;

let string2cnt_array s =
  let len = String.length s in
  let array = Array.make len (0,'0') in
  let rec loop i c num cnt =
    if (i = len) then
      let () = array.(num) <- (cnt,c) in
      let ret = Array.make (num+1) (0,'0') in
      let () = Array.blit array 0 ret 0 (num+1) in
      ret
    else if (s.[i] = c) then
      loop (i+1) c num (cnt+1)
    else
      let () = array.(num) <- (cnt,c) in
      loop (i+1) (s.[i]) (num+1) 1
    in loop 0 s.[0] 0 0;;

let cnt_array = string2cnt_array str;;
let len = Array.length cnt_array;;
let ruiseki = Array.make len 0;;
let () = ruiseki.(0) <- fst cnt_array.(0) in
for i = 1 to len - 1 do
  ruiseki.(i) <- ruiseki.(i-1) + (fst cnt_array.(i))
done

let rec solve i ans =
  if i = len then ans
  else
    let num = if snd cnt_array.(i) = '0' then 0 else 1 in
    let target = 2 * k - (1 - num) + i in
    let si = min (len - 1) target in
    let ruiseki_minus = if i = 0 then 0 else ruiseki.(i-1) in
    let next_ans = max ans (ruiseki.(si) - ruiseki_minus) in
    solve (i+1) next_ans;;

printf ("%d\n") (solve 0 0);;

Score : 400 points

Problem Statement

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

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

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

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

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

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

Constraints

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

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

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

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

Sample Input 1

5 1
00010

Sample Output 1

4

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

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

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


let () = Scanf.scanf "%d\n%d\n%d\n%d\n%d\n%d" (fun a b c d e k -> (
  (if e > a + k then ":("
  else "Yay!") |> print_string
));;

Score: 100 points

Problem Statement

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

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

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

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

Constraints

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

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

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

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

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

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

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

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

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

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

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

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

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

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

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

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

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

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


let () =
  let ts = Array.init 5 @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let sum = Array.fold_left (fun acc elt -> acc + (elt + 9) / 10 * 10) 0 ts in
  let ans = ( - ) sum @@ Array.fold_left (fun acc elt -> max acc @@ ((elt + 9) / 10 * 10) - elt) 0 ts in
  Printf.printf "%d\n" ans

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

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

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

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

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

This restaurant has the following rules on orders:

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

Only one dish can be ordered at a time.

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

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

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

Sample Input 1

29
20
7
35
120

Sample Output 1

215

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

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

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

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

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

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

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

Sample Input 2

101
86
119
108
57

Sample Output 2

481

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

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

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

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

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

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

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

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


(* O(1) *)
let get_wait_time cook_time = let m = cook_time mod 10 in if m = 0 then 0 else 10 - m
let get_next_time cook_time = cook_time + get_wait_time cook_time

(* O(|dishes|) *)
let solve dishes =
  let max_wait = List.map get_wait_time dishes |> List.fold_left max 0 in
  let sum = List.map get_next_time dishes |> List.fold_left (+) 0 in
  sum - max_wait

let read_int_array n = Array.init n (fun _ -> read_int ())
let read_ints n = read_int_array n |> Array.to_list

let _ = read_ints 5 |> solve |> string_of_int |> print_endline


let () = Scanf.scanf "%d %d %d %d %d" @@ fun a b c d e ->
  Printf.printf "%d\n" @@
  List.fold_left (fun acc a -> acc + a + 9 - (a + 9) mod 10) 0 [a; b; c; d; e]
  - List.fold_left (fun acc a -> max acc (9 - (a + 9) mod 10)) 0 [a; b; c; d; e]


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

Score: 300 points

Problem Statement

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

There are five means of transport in this empire:

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

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

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

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

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

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

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

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

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

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

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

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

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

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

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

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

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

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

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

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

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


let kABCMax = 3000
let x, y, z, k = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> a, b, c, d
let a_s = Array.init x @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let bs = Array.init y @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let cs = Array.init z @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let ab_s = Array.make kABCMax 0
let ans = Array.make (kABCMax * z) 0
let _ =
  for i = 0 to x - 1 do
    for j = 0 to y - 1 do
      if i * y + j < kABCMax then
        ab_s.(i * y + j) <- a_s.(i) + bs.(j) done done;
  for i = 0 to kABCMax - 1 do
    for j = 0 to z - 1 do
      ans.(i * z + j) <- ab_s.(i) + cs.(j) done done;
  Array.sort (fun x y -> y - x) ans;
  for i = 0 to k - 1 do
    Printf.printf "%d\n" ans.(i) done

Score: 400 points

Problem Statement

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

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

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

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

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

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

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

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

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

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

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

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

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

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

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

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

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

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

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

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

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

Sample Input 2

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

Sample Output 2

400
310
310
301
301

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

Sample Input 3

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

Sample Output 3

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

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


open Batteries

let xyzk = List.map int_of_string (String.split_on_char ' ' (read_line()))
let (x, y, z, k) = match xyzk with
   [x; y; z; k] -> (x, y, z, k)
 | _ -> (1, 1, 1, 1)
let a = List.map int_of_string (String.split_on_char ' ' (read_line()))
let b = List.map int_of_string (String.split_on_char ' ' (read_line()))
let c = List.map int_of_string (String.split_on_char ' ' (read_line()))

let sumlist lst1 lst2 lst3 =
  let rec hojo p q r n =
  if n < 3000 then
    if p < x then
      if q < y then
        if r < z then
          let ap = List.nth lst1 p in
          let bq = List.nth lst2 q in
          let cr = List.nth lst3 r in
          let sumall = ap + bq + cr in
          sumall :: hojo p q (r+1) (n+1)
        else hojo p (q+1) 0 (n+1)
      else hojo (p+1) 0 0 (n+1)
    else []
  else [] in
  hojo 0 0 0 0

let rec ins_sort lst = match lst with
    [] -> []
  | first :: rest ->
     let rec insert n lst = match lst with
         [] -> [n]
       | first :: rest -> if n >= first then n :: insert first rest
                          else first :: insert n rest in
     insert first (ins_sort rest)

let last = ins_sort (sumlist a b c)
let rec answer i = if i < k then (print_int (List.nth last i);
                                  print_string "\n";
                                  answer (i+1))
                   else ()
let () = answer 0


open Batteries

let xyzk = List.map int_of_string (String.split_on_char ' ' (read_line()))
let (x, y, z, k) = match xyzk with
   [x; y; z; k] -> (x, y, z, k)
 | _ -> (1, 1, 1, 1)
let a = List.map int_of_string (String.split_on_char ' ' (read_line()))
let b = List.map int_of_string (String.split_on_char ' ' (read_line()))
let c = List.map int_of_string (String.split_on_char ' ' (read_line()))

let sumlist lst1 lst2 lst3 =
  let rec hojo p q r =
    if p < x then
      if q < y then
        if r < z then
          let ap = List.nth lst1 p in
          let bq = List.nth lst2 q in
          let cr = List.nth lst3 r in
          let sumall = ap + bq + cr in
          sumall :: hojo p q (r+1)
        else hojo p (q+1) 0
      else hojo (p+1) 0 0
    else [] in
  hojo 0 0 0

let rec ins_sort lst = match lst with
    [] -> []
  | first :: rest ->
     let rec insert n lst = match lst with
         [] -> [n]
       | first :: rest -> if n >= first then n :: insert first rest
                          else first :: insert n rest in
     insert first (ins_sort rest)

let last = ins_sort (sumlist a b c)
let rec answer i = if i < k then (print_int (List.nth last i);
                                  print_string "\n";
                                  answer (i+1))
                   else ()
let () = answer 0


let n = read_int ()
let s = read_line ()
let f x s = let n = ref 0 in String.iter (fun c -> if c = x then incr n) s; !n
let r = f 'R' s
let _ = print_endline @@ if r > n - r then "Yes" else "No"

Score : 200 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 100

|s| = N

s_i is R or B.

Input

Input is given from Standard Input in the following format:

N
s

Output

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

Sample Input 1

4
RRBR

Sample Output 1

Yes

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

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

Sample Input 2

4
BRBR

Sample Output 2

No

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

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


open Printf
open Scanf

let id x = x
let read_int _ = bscanf Scanning.stdin " %d " id
let read_str _ = bscanf Scanning.stdin " %s " id
let read_pair _ = bscanf Scanning.stdin " %c %c " (fun x y -> (x,y))

let check s m inst dir =
  let n = String.length s in
  let rec check' i = function
    | _ when i = -1 || i = n -> true
    | [] -> false
    | (t,d)::rest ->
      if t = s.[i]
      then check' (if d = dir then i-1 else i+1) rest
      else check' i rest
  in check' m inst

let rec binary_search s l r inst d = match r - l = 1 with
    | true -> l
    | false ->
      let m = (l + r) / 2 in
      let (l',r') = if check s m inst d then (m, r) else (l, m) in
      binary_search s l' r' inst d

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

let () =
  let n = read_int () in
  let q = read_int () in
  let s = read_str () in
  let inst = Array.(init q read_pair |> to_list) in
  let l = binary_search s (-1) n inst 'L' + 1 in
  let r = binary_search (rev_str s) (-1) n inst 'R' + 1 in
  printf "%d\n" (max 0 (n - r - l))

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

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

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


open Batteries

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

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

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

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

let dbg x = Printf.printf "%s\n" @@ dump x; x

let s = scan "%s" identity

let () =
  let n = String.length s in
  Enum.Labels.map (0 --^ n)
    ~f:(fun i ->
        Enum.Labels.map (1 -- n) ~f:(fun j ->
            if i < j then
              let sub = String.slice ~first:i ~last:j s  in
              if Enum.for_all (String.contains "AGTC") @@ String.enum sub then
                j - i
              else 0
            else
              0))
  |> Enum.concat
  |> Enum.reduce max
  |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

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

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

Notes

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

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

Constraints

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

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

ATCODER

Sample Output 1

3

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

Sample Input 2

HATAGAYA

Sample Output 2

5

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

Sample Input 3

SHINJUKU

Sample Output 3

0

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


let s = read_line ()
let rec f i m c = String.(if i >= length s then max m c else if contains "ACGT" s.[i] then f (i + 1) m (c + 1) else f (i + 1) (max m c) 0)
let _ = f 0 0 0 |> Printf.printf "%d\n"


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

module StringMap = Map.Make (String)

let () = Scanf.scanf "%d" @@ fun n ->
  let dp = Array.make (n + 1) StringMap.empty in
  dp.(3) <-
    List.fold_left (List.fold_left (List.fold_left (List.fold_left (fun m s -> StringMap.add s 1 m)))) StringMap.empty @@
    List.map (fun c1 ->
      List.map (fun c2 ->
        List.map (fun c3 ->
          if
            c1 = 'A' && c2 = 'G' && c3 = 'C' ||
            c1 = 'A' && c3 = 'G' && c2 = 'C' ||
            c2 = 'A' && c1 = 'G' && c3 = 'C'
          then []
          else [String.init 3 (function 0 -> c1 | 1 -> c2 | 2 -> c3)])
      ['A'; 'C'; 'G'; 'T']) ['A'; 'C'; 'G'; 'T']) ['A'; 'C'; 'G'; 'T'];
  for i = 4 to n do
    dp.(i) <- StringMap.fold (fun s n ->
      List.fold_right (fun c m ->
        if
          s.[1] = 'A' && s.[2] = 'G' && c = 'C' ||
          s.[0] = 'A' && s.[2] = 'G' && c = 'C' ||
          s.[2] = 'A' && s.[1] = 'G' && c = 'C' ||
          s.[0] = 'A' && s.[1] = 'G' && c = 'C' ||
          s.[1] = 'A' && c = 'G' && s.[2] = 'C'
        then m
        else
          let s' = String.sub s 1 2 ^ String.make 1 c in
          StringMap.add s' (n +^ try StringMap.find s' m with Not_found -> 0) m) ['A'; 'C'; 'G'; 'T']) dp.(i - 1) StringMap.empty
  done;
  Printf.printf "%d\n" @@ StringMap.fold (fun _ -> ( +^ )) dp.(n) 0

Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

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

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

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

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


let (>>=) x f = match x with None -> None | Some x -> f x

let rec rm_rightest temp i = function
  | [] -> None
  | b::bs ->
     if i = b then Some (b, List.fold_left (fun acc b -> b::acc) bs temp)
     else rm_rightest (b::temp) (i - 1) bs

let solve bs n =
  let rec inner ans n = function
    | [] -> Some ans
    | bs ->
(*       print_string "n: "; print_endline @@ string_of_int n;
       print_string "bs: "; List.iter (fun n -> print_int n; print_string "; ") bs;
       print_endline ""; *)
       rm_rightest [] n bs >>= fun (b, bs) ->
(*       print_string "b, bs: "; print_int b; print_string " | ";
       List.iter(fun n -> print_int n; print_string "; ") bs;
       print_endline "";*)
       inner (b::ans) (n - 1) bs
  in inner [] n bs

let print_result = function
  | None -> print_int (-1)
  | Some ans -> List.iter (fun n -> print_int n; print_endline "") ans

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let bs = ref [] in
  for i = 0 to n - 1 do
    Scanf.scanf (if i <> n - 1 then "%d " else "%d\n") (fun b -> bs := b::!bs)
  done;
  solve !bs n
  |> print_result

Score : 400 points

Problem Statement

Snuke has an empty sequence a.

He will perform N operations on this sequence.

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

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

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq b_i \leq N

Input

Input is given from Standard Input in the following format:

N
b_1 \dots b_N

Output

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

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

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

After the first operation: (1)

After the second operation: (1,1)

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

Sample Input 2

2
2 2

Sample Output 2

-1

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

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1


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

Score : 700 points

Problem Statement

You are given an integer N.
Build an undirected graph with N vertices with indices 1 to N that satisfies the following two conditions:

The graph is simple and connected.

There exists an integer S such that, for every vertex, the sum of the indices of the vertices adjacent to that vertex is S.

It can be proved that at least one such graph exists under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

In the first line, print the number of edges, M, in the graph you made. In the i-th of the following M lines, print two integers a_i and b_i, representing the endpoints of the i-th edge.

The output will be judged correct if the graph satisfies the conditions.

Sample Input 1

3

Sample Output 1

2
1 3
2 3

For every vertex, the sum of the indices of the vertices adjacent to that vertex is 3.


let () = Scanf.scanf "%d" @@ fun s ->
  if s mod 2 = 0 then begin
    Printf.printf "%d\n" (s * (s - 2) / 2);
    for i = 1 to s do
      for j = i + 1 to s do
        if i + j <> s + 1 then
          Printf.printf "%d %d\n" i j
      done
    done
  end else begin
    Printf.printf "%d\n" (s * (s - 1) / 2 - s / 2);
    for i = 1 to s do
      for j = i + 1 to s do
        if i + j <> s then
          Printf.printf "%d %d\n" i j
      done
    done
  end


let popcnt x =
  let x = (x land 0x5555555555555555) + ((x lsr 1) land 0x5555555555555555) in
  let x = (x land 0x3333333333333333) + ((x lsr 2) land 0x3333333333333333) in
  let x = (x land 0x0f0f0f0f0f0f0f0f) + ((x lsr 4) land 0x0f0f0f0f0f0f0f0f) in
  let x = (x land 0x00ff00ff00ff00ff) + ((x lsr 8) land 0x00ff00ff00ff00ff) in
  let x = (x land 0x0000ffff0000ffff) + ((x lsr 16) land 0x0000ffff0000ffff) in
  (x land 0x00000000ffffffff) + ((x lsr 32) land 0x00000000ffffffff)

let rec gray_of_binary g = g lxor (g lsr 1)

let rec binary_of_gray b = function
  | 0 -> b
  | g -> binary_of_gray (b lxor g) (g lsr 1)
let binary_of_gray = binary_of_gray 0

let () = Scanf.scanf "%d %d %d" @@ fun n a b ->
  let a' = binary_of_gray a in
  let b' = binary_of_gray b in
  let n' = 1 lsl n in
  if popcnt (a lxor b) <> 1
  then print_endline "NO"
  else begin
    print_endline "YES";
    for i = 0 to n' - 1 do
      Printf.printf "%d " @@
      if (a' < b') = (abs (a' - b') = 1)
      then gray_of_binary ((a' + n' - i) mod n')
      else gray_of_binary ((a' + i) mod n')
    done;
    print_newline ()
  end

Score : 800 points

Problem Statement

You are given integers N,\ A and B.
Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.

P_0=A

P_{2^N-1}=B

For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} differ by exactly one bit.

Constraints

1 \leq N \leq 17

0 \leq A \leq 2^N-1

0 \leq B \leq 2^N-1

A \neq B

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B

Output

If there is no permutation that satisfies the conditions, print NO.

If there is such a permutation, print YES in the first line.
Then, print (P_0,\ P_1,\ ...\ P_{2^N-1}) in the second line, with spaces in between.
If there are multiple solutions, any of them is accepted.

Sample Input 1

2 1 3

Sample Output 1

YES
1 0 2 3

The binary representation of P=(1,0,2,3) is (01,00,10,11), where any two adjacent elements differ by exactly one bit.

Sample Input 2

3 2 1

Sample Output 2

NO


let rec gray_of_binary g = g lxor (g lsr 1)
let rec binary_of_gray b = function
  | 0 -> b
  | g -> binary_of_gray (b lxor g) (g lsr 1)
let binary_of_gray = binary_of_gray 0

let () = Scanf.scanf "%d %d %d" @@ fun n a b ->
  let a' = binary_of_gray a in
  let b' = binary_of_gray b in
  let n' = 1 lsl n in
  if abs (a' - b') <> 1 && abs (a' - b') <> n' - 1
  then print_endline "NO"
  else begin
    print_endline "YES";
    (* for i = 0 to n' - 1 do
      Printf.printf "%d " @@
      if (a' < b') = (abs (a' - b') = 1)
      then gray_of_binary ((a' + n' - i) mod n')
      else gray_of_binary ((a' + i) mod n')
    done;
    print_newline () *)
  end


let _ = Scanf.sscanf (read_line ()) "%d %d" (fun h w ->
    Scanf.sscanf (read_line ()) "%d %d" (fun h_ w_ ->
      print_endline (string_of_int ((h - h_) * (w - w_)))
    )
)

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


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

let n, m, c = Scanf.sscanf (read_line ()) "%d %d %d" (
        fun n m c ->
                n, m, c
)
let blst =
        Str.split (Str.regexp " ") (read_line ())
        |> List.map int_of_string
let alst =
        List.init n (
                fun _ ->
                        Str.split (Str.regexp " ") (read_line ())
                        |> List.map int_of_string
        )

let dot_product = List.fold_left2 (fun a b c -> a + b * c) 0
let rec f lst =
        match lst with
                [] -> 0
                | first :: rest ->
                        let fdot = c + dot_product first blst in
                                if fdot > 0 then
                                        1 + (f rest)
                                else
                                        f rest

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

Score : 200 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

1

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

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

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

Sample Input 2

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

Sample Output 2

2

Sample Input 3

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

Sample Output 3

0

All of them are Wrong Answer. Except yours.


let calc a b c = List.fold_left2 (fun x y z -> x + y * z) c a b
let () =
  try
    let (n, m, c) = Scanf.scanf "%d %d %d\n" (fun a b c -> (a, b, c)) in
    let b = Array.to_list
        (Array.init m (fun _ -> Scanf.scanf "%d " (fun x -> x))) in
    let a = Array.to_list
        (Array.init (n) (fun _ -> Array.to_list (Array.init m (fun _ -> Scanf.scanf "%d " (fun x -> x))))) in
    List.length (List.filter (fun lst -> calc lst b c > 0) a) |> print_int
  with
    End_of_file -> ()


let calc a b c = List.fold_left2 (fun x y z -> x + y * z) c a b
let () =
  try
    let (n, m, c) = Scanf.scanf "%d %d %d\n" (fun a b c -> (a, b, c)) in
    let b = Array.to_list
        (Array.init m (fun _ -> Scanf.scanf "%d " (fun x -> x))) in
    let a = Array.to_list
        (Array.init (n-1) (fun _ -> Array.to_list (Array.init m (fun _ -> Scanf.scanf "%d " (fun x -> x))))) in
    List.length (List.filter (fun lst -> calc lst b c > 0) a) |> print_int
  with
    End_of_file -> ()


(* 本当に辛い *)
let array_map2 f a b =
    let l = Array.length a in
    if l = 0 then [||] else begin
        let r = Array.make l (f (Array.unsafe_get a 0) (Array.unsafe_get b 0)) in
        for i = 0 to l - 1 do
            Array.unsafe_set r i (f (Array.unsafe_get a i) (Array.unsafe_get b i))
        done;
        r
    end

let () = Scanf.scanf "%d %d %d\n" @@ fun n m c ->
    let b = Array.init m (fun _ ->
        Scanf.scanf " %d" (fun b -> b)) in
    Array.init n (fun _ ->
        Scanf.scanf "\n" (fun _ -> ()) 0;
        let a = Array.init m (fun _ ->
            Scanf.scanf " %d" (fun a -> a)) in
        let t = array_map2 (fun a b -> a * b) a b
        |> Array.fold_left (+) 0 in
        if t + c > 0
        then 1
        else 0)
    |> Array.fold_left (+) 0
    |> Printf.printf "%d"


Scanf.scanf "%d %d" (fun n m ->
    let ab = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun a b -> a, b)) in
    Array.sort compare ab;

    let rec loop i acc hon =
        let a, b = ab.(i) in
        let d = min b (m - hon) in
        let acc = acc + a * d in
        let hon = hon + d in
        if hon < m then loop (i + 1) acc hon
            else acc
    in
    loop 0 0 0 |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

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

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

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

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

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


type drink = {price: int; stock: int};;
let compare_drink d1 d2 = d1.price - d2.price;;

let input_drink_array n = Array.init n @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> {price = a; stock = b};;

let () = Scanf.scanf "%d %d" @@ fun n m ->
  let drinks = input_drink_array n in (
    Array.fast_sort compare_drink drinks;
    let ans = ref 0 in
    let cnt = ref 0 in (
      for i = 0 to n - 1 do
        if drinks.(i).stock + !cnt < m then (
          ans := !ans + drinks.(i).price * drinks.(i).stock;
          cnt := !cnt + drinks.(i).stock
        ) else if !cnt < m then (
          let rest = m - !cnt in (
            ans := !ans + drinks.(i).price * rest;
            cnt := m;
          )
        )
      done;
      Printf.printf "%d\n" !ans
    )
  )
;;


let input () =
let (n,m) = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> (a,b)) in
let rec loop count list =
  match count with
    0 -> list
  | x -> let (a,b) = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> (a,b)) in
          loop (count - 1) ((a,b)::list)
in (m,loop n []);;

let solve () =
  let (m, list) = input() in
  let sort_list = List.sort (fun (a,_) (b,_) -> if a > b then 1 else -1) list in
  let rec loop ans m l =
    let (a,b) = List.hd l in
    if m > b then
      loop (ans + (a*b)) (m-b) (List.tl l)
    else print_int (ans + m*a)
  in loop 0 m sort_list;;

solve();;


let rec qsort compare ls =
  if ls = [] then []
  else
    let p, tl = (List.hd ls), (List.tl ls) in
    let left = List.filter (compare p) tl in
    let right = List.filter (fun x -> not @@ compare p x) tl in
    (qsort compare left) @ p::(qsort compare right)

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

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


let a, b, k = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let c = ref 1
let _ = for i = min a b downto 1 do if a mod i = 0 && b mod i = 0 then (if !c >= k then (Printf.printf "%d\n" i; exit 0); incr c) done

Score : 200 points

Problem Statement

You are given positive integers A and B.

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

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

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

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

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

Sample Input 1

8 12 2

Sample Output 1

2

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

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


let calc a b =
  let rec iter i =
    if i == 0 then
      []
    else if a mod i == 0 && b mod i == 0 then
      i :: iter (i - 1)
    else iter (i - 1)
  in iter 100
let () =
  let (a, b, k) = Scanf.scanf "%d %d %d" (fun a b k -> (a, b, k)) in
  let l = calc a b in
  (*List.iter (fun e -> e |> string_of_int |> print_endline) l*)
  List.nth l (k - 1) |> string_of_int |> print_endline


let a=ref 0 in let b=ref 0 in Scanf.scanf"%s"@@fun s->String.iter(fun c->if c='0'then a:=!a+2 else b:=!b+2)s;min !a!b|>print_int

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


let m = Scanf.scanf "2019/%d" @@ fun a -> a
let _ = print_endline @@ if m >= 5 then "TBD" else "Heisei"

Score : 100 points

Problem Statement

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD