Scanf.scanf "%d %d" (fun n k ->
    let x = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x)) in

    let rec loop p acc =
        if p = n then acc else
            let s1 = x.(p - k + 1) in
            let s2 = x.(p) in
            let v1 = if s1 < 0 && s2 <= 0 then abs s1 else
                     if s1 >= 0 && s2 > 0 then s2 else
                         min (abs s1 * 2 + s2) (abs s1 + s2 * 2)
            in
            let acc = min acc v1 in
            loop (p + 1) acc
    in
    loop (k - 1) max_int |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

There are N candles placed on a number line.
The i-th candle from the left is placed on coordinate x_i.
Here, x_1 < x_2 < ... < x_N holds.

Initially, no candles are burning.
Snuke decides to light K of the N candles.

Now, he is at coordinate 0.
He can move left and right along the line with speed 1.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

8 5
-9 -7 -4 -3 1 2 3 4

Sample Output 4

10


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

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

Score: 100 points

Problem Statement

There is a farm whose length and width are A yard and B yard, respectively. A farmer, John, made a vertical road and a horizontal road inside the farm from one border to another, as shown below: (The gray part represents the roads.)

What is the area of this yard excluding the roads? Find it.

Note

It can be proved that the positions of the roads do not affect the area.

Constraints

A is an integer between 2 and 100 (inclusive).

B is an integer between 2 and 100 (inclusive).

Input

Input is given from Standard Input in the following format:

A B

Output

Print the area of this yard excluding the roads (in square yards).

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.

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 () =
  Scanf.scanf "%d %d\n"
    (fun a b -> (a-1) * (b-1)) |> print_int


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


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

let n = scan "%d" id

let factors n =
  let rec aux n i =
    if n = 1 then 0
    else if n mod i = 0 then 1 + aux (n/i) i
    else aux n (succ i)
  in aux n 2

let () =
  ListL.map (1++n) ~f:(fun i ->
      if i mod 2 = 1 && factors i = 8 then 1 else 0
    )
  |> List.sum
  |> Printf.printf "%d\n"

Score: 200 points

Problem Statement

The number 105 is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?

Constraints

N is an integer between 1 and 200 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between 1 and 105, the only number that is odd and has exactly eight divisors is 105.

Sample Input 2

7

Sample Output 2

0

1 has one divisor. 3, 5 and 7 are all prime and have two divisors. Thus, there is no number that satisfies the condition.


let () = Scanf.scanf "%d" @@ fun n ->
  Printf.printf "%d\n" @@ List.length @@
    List.filter (fun x -> ( = ) 8 @@
      List.length @@
        List.filter (fun i -> x mod i = 0) @@
          Array.to_list @@ Array.init x (( + ) 1)) @@
      List.filter (fun x -> x mod 2 = 1) @@
        Array.to_list @@ Array.init n (( + ) 1)


let solve s i =
  let rec find_aux s i cur = match String.get s (cur-1) with
    | '1' when i > cur -> find_aux s i (cur+1)
    | '1' when i = cur -> '1'
    | x -> x
  in
  find_aux s i 1

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

Score: 300 points

Problem Statement

Mr. Infinity has a string S consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in S is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if S is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after 5 \times 10^{15} days. What is the K-th character from the left in the string after 5 \times 10^{15} days?

Constraints

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

K is an integer between 1 and 10^{18} (inclusive).

The length of the string after 5 \times 10^{15} days is at least K.

Input

Input is given from Standard Input in the following format:

S
K

Output

Print the K-th character from the left in Mr. Infinity's string after 5 \times 10^{15} days.

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after 5 \times 10^{15} days is 12222. As K=4, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after 5 \times 10^{15} days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


let arr_of_str s = Array.init (String.length s) (fun i -> s.[i])
let () =
  Scanf.scanf "%s %d" @@ fun s k ->
  let s = arr_of_str s in
  if k = 1 then Printf.printf "%c\n" s.(0)
  else
    Array.fold_left (fun z c ->
      if z <> '1' then z else if c <> '1' then c else '1') '1' s
    |> Printf.printf "%c\n"


let _ = Scanf.sscanf (read_line ()) "%d %d" (fun n k ->
  if n mod k = 0 then 0 else 1
) |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

Takahashi has decided to distribute N AtCoder Crackers to K users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is 1.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


let make_no =
  let rec one n f =
    let i = (4 * n) + 1 in
    if i < 21 then i :: one (n + 1) f else f
  in
  let rec two n f =
    let i = (4 * n) + 2 in
    if i < 14 then i :: two (n + 1) f else f
  in
  let rec three n f =
    let i = (4 * n) + 3 in
    if i < 7 then i :: three (n + 1) f else f
  in
  one 0 (two 0 (three 0 []))

let () =
  let n = read_int () in
  let l = make_no in
  (match List.mem n l with true -> "No" | false -> "Yes") |> print_endline

Score : 200 points

Problem Statement

La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each.
Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

If there is a way to buy some cakes and some doughnuts for exactly N dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be 4 + 7 = 11 dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be 4 \times 10 = 40 dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (4 dollars) and doughnuts (7 dollars) are both higher than 3 dollars, so there is no such way.


let () = Scanf.scanf "%d" @@ fun n ->
  print_endline @@
    (function true -> "Yes" | false -> "No") @@
      Array.fold_left (Array.fold_left ( || )) false @@
        Array.init (n + 1) @@ fun i ->
          Array.init (n + 1) @@ fun j -> 4 * i + 7 * j = n


open Batteries
open Printf
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in

  let rec aux i =
    if i*7 > n then "No" else
      (
        if (n - i*7) mod 4 = 0 then "Yes" else
          aux (i+1)
      )
  in
  Printf.printf "%s\n" @@
  aux 0


let f a = if a < 1200 then "ABC" else (if a < 2800 then "ARC" else "AGC");;
let () = Scanf.scanf "%d" f
|> Printf.printf "%s\n"

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is R. What is the next contest rated for him?

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

1199 is less than 1200, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

1200 is not less than 1200 and ABC will be unrated, but it is less than 2800 and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC


let ratingChangedContest rating =
  if rating < 1200 then
    "ABC"
  else if rating < 2800 then
    "ARC"
  else
    "AGC";;

read_int() |> ratingChangedContest |> print_endline


let () =
  print_endline @@ Scanf.scanf "%d" @@ fun r ->
    if r < 1200 then "ABC" else if r < 2800 then "ARC" else "AGC"


let s = read_line ()
let n = String.length s
let cs = Array.init n @@ fun i -> if Char.uppercase s.[i] = s.[i] then 1 else 0
let _ = print_endline @@ if s.[0] = 'A' && String.contains (String.sub s 2 (n - 3)) 'C' && Array.fold_left (+) 0 cs = 2 then "AC" else "WA"

Score : 200 points

Problem Statement

You are given a string S. Each character of S is uppercase or lowercase English letter.
Determine if S satisfies all of the following conditions:

The initial character of S is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

4 ≤ |S| ≤ 10 (|S| is the length of the string S.)

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

If S satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


type at = A | C | N | E;;

let is_lowercase = function
  | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h'
  | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p'
  | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x'
  | 'y' | 'z' -> true
  | _ -> false;;

let on string index =
  if String.length string == index + 1 then E
  else if index == 0 then A
  else if index >= 2 && ((String.length string) - index) >= 2 then C
  else N

let valid string =
  let rec validate string index c_state =
    match (on string index, string.[index], c_state) with
    | (E, _, true) -> "AC"
    | (A, 'A', _) -> validate string (index + 1) c_state
    | (C, 'C', false) -> validate string (index + 1) true
    | (C, c, true) when c != 'C' -> validate string (index + 1) true
    | (N, 'C', _) -> "WA"
    | (N, c, _) when is_lowercase c -> validate string (index + 1) c_state
    | (_, _, _) -> "WA"
  in validate string 0 false;;

read_line() |> valid |> print_endline


Scanf.scanf "%d %d" (fun d g ->
    let pc = Array.init d (fun _ -> Scanf.scanf " %d %d" (fun p c -> p, c)) in

    let rec loop bits mi =
        let rec loop2 j bits score count =
            if bits = 0 then score, count else
                let p,c = pc.(j) in
                if bits land 1 = 1 then loop2 (j + 1) (bits lsr 1) (score + 100 * (j + 1) * p + c) (count + p)
                                   else loop2 (j + 1) (bits lsr 1) score count
        in
        let rec find_bits i =
            if i < 0 then i else
                if (1 lsl i) land bits = 0 then i else find_bits (i - 1)
        in
        if bits < 0 then mi else
            let score, count = loop2 0 bits 0 0 in
            let mi = if score >= g then min mi count else
                let k = find_bits (d - 1) in
                if k < 0 then mi else
                    let p, _ = pc.(k) in
                    let kk = (k + 1) * 100 in
                    let q = (g - score + kk - 1) / kk in
                    if q < p then min mi (count + q) else mi
            in
            loop (bits - 1) mi
    in
    loop ((1 lsl d) - 1) max_int |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer i between 1 and D (inclusive), there are p_i problems with a score of 100i points.
These p_1 + … + p_D problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of 100i points, he/she earns the perfect bonus of c_i points, aside from the base score (1 ≤ i ≤ D).

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of G or more points.
At least how many problems does he need to solve for this objective?

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

It is possible to have a total score of G or more points.

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

Print the minimum number of problems that needs to be solved in order to have a total score of G or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with 100 points and five problems each with 200 points. The perfect bonus for solving all the 100-point problems is 500 points, and the perfect bonus for solving all the 200-point problems is 800 points. Takahashi's objective is to have a total score of 700 points or more.

One way to achieve this objective is to solve four 200-point problems and earn a base score of 800 points. However, if we solve three 100-point problems, we can earn the perfect bonus of 500 points in addition to the base score of 300 points, for a total score of 800 points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is 2000 points or more. In this case, we inevitably need to solve all five 200-point problems, and by solving two 100-point problems additionally we have the total score of 2000 points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is 400 points or more. In this case, we only need to solve two 200-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one 500-point problem, but the perfect bonus can be earned even in such a case.


open Printf
open Scanf

let (d,g) = sscanf (read_line ()) "%d %d" (fun d g -> (d,g));;
let rec input_list num l =
if num = 0 then l
else
    let (p,c) = sscanf (read_line ()) "%d %d" (fun d g -> (d,g)) in
    input_list (num-1) ((100 * (d-num+1), p, c) :: l);;

let list = input_list d [];;
let inf = 10000000000;;

let solve list g =
    let rec loop l q_num sum tl =
    match l with
    | [] ->
        (match tl with
        | [] ->  if sum >= g then q_num else inf
        | x::rest ->
            let diff = g - sum in
            if diff <= 0 then q_num
            else
                let (i1,p1,c1) = List.hd (List.sort (fun (a,_,_) (b,_,_) -> -compare a b) tl) in
                if i1*(p1-1)+sum < g then inf
                else q_num (*+ truncate ((float_of_int diff) /. (float_of_int i1))*)
        )
    | (i1,p1,c1)::rest ->
        let used_value = loop rest (q_num + p1) (sum + p1*i1 + c1) tl in
        let non_used_value = loop rest q_num sum ((i1,p1,c1) :: tl) in
        min used_value non_used_value
    in loop list 0 0 [];;

let ans = solve list g;;

let _ = printf "%d\n" ans;;


(* O(2^d d) *)
Scanf.scanf " %d %d" @@ fun d g ->
  let pcs = Array.init d @@ fun _ -> Scanf.scanf " %d %d" @@ fun p c -> p, c in
  let ans = ref max_int in
  let rec find acc rest i bits =
    if rest <= 0 then acc
    else if i < 0 then max_int
    else if bits lsr i land 1 = 1 then find acc rest (i - 1) bits
    else
      let p, _ = pcs.(i) in
      let m = (i + 1) * 100 in
      let n = min (p - 1) @@ (rest + m - 1) / m in
      find (acc + n) (rest - n * m) (i - 1) bits in
  let points = Array.init d @@ fun i -> let p, c = pcs.(i) in i, p, p * (i + 1) * 100 + c in
  let f bits =
    let g (c, sum) (i, p, s) = if bits lsr i land 1 = 1 then c + p, sum + s else c, sum in
    Array.fold_left g (0, 0) points in
  for i = 0 to 1 lsl d - 1 do
    let c, s = f i in
    ans := min !ans @@ find c (g - s) (d - 1) i
  done;
  Printf.printf "%d\n" !ans


Scanf.scanf "%d %d %d" @@ fun a b c -> Printf.printf "%d\n" @@ max a (max b c) - min a (min b c)

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

Here, |x| denotes the absolute value of x.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


let a_s = Array.init 3 @@ fun _ -> Scanf.scanf " %d" (+) 0
let ans = ref 500
let f i j k = ans := min !ans @@ abs (a_s.(i) - a_s.(j)) + abs (a_s.(j) - a_s.(k))
let _ =
  f 0 1 2; f 0 2 1; f 1 0 2; f 1 2 0; f 2 0 1; f 2 1 0;
  Printf.printf "%d\n" !ans


let f a b c = let aab = abs (a-b) in let abc = abs (b-c) in let aca = abs (c-a) in
aab + abc + aca - max aab (max abc aca);;
let () = Scanf.scanf "%d %d %d" f
|> Printf.printf "%d\n"


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


let () = Scanf.scanf "%d %d %d" (fun x y z -> [x;y;z])
    |> (fun l -> (List.fold_left max 0 l) - (List.fold_left min 101 l))
    |> Printf.printf "%d"


let () = Scanf.scanf "%d %d %d" @@ fun a1 a2 a3 ->
  let [a1'; a2'; a3'] = List.sort compare [a1; a2; a3] in
  Printf.printf "%d\n" @@ a3' - a1'


open Scanf
open Printf

let rotates s = let rec f n = if n = String.length s
                 then []
                 else (String.sub s n (String.length s - n) ^ String.sub s 0 n) :: f (n+1)
  in s :: (f 1)

let f s t = List.fold_left ( || ) false (List.map (fun u -> u = t) @@ rotates s)

let () = if scanf "%s\n%s\n" f
    then printf "Yes\n"
    else printf "No\n"

Score : 200 points

Problem Statement

You are given string S and T consisting of lowercase English letters.

Determine if S equals T after rotation.

That is, determine if S equals T after the following operation is performed some number of times:

Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}.

Here, |X| denotes the length of the string X.

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S equals T after rotation, print Yes; if it does not, print No.

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ ->
    Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 @@ Array.map (fun a -> a - 1) as_

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


open Scanf
open Printf

let rec scan_list = function
  | 1 -> scanf "%d" (fun k -> [k])
  | n -> scanf "%d " (fun k -> k :: scan_list (n-1))

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

let lcm a b = a * (b / (gcd a b))

let f a m = List.fold_left ( + ) 0 (List.map (fun x -> m mod x) a)

let rec search lst m = function
  | 0 -> m
  | n -> search lst (max m (f lst n)) (n-1)

let () = let lst = scanf "%d\n" scan_list in
  printf "%d\n" (search lst 0 (List.fold_left lcm 1 lst))


open Scanf
open Printf

let rec scan_list = function
  | 1 -> scanf "%d" (fun k -> [k])
  | n -> scanf "%d " (fun k -> k :: scan_list (n-1))

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

let lcm a b = a * (b / (gcd a b))

let rec seq = function
  | 0 -> []
  | n -> n :: seq (n-1)

let f a m = List.fold_left ( + ) 0 (List.map (fun x -> m mod x) a)

let () = let lst = scanf "%d\n" scan_list in
  printf "%d\n" (List.fold_left max 0 (List.map (f lst) (seq @@ List.fold_left lcm 1 lst)))


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

let lcm n m = n / gcd n m * m

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ ->
    Scanf.scanf "%d " @@ fun a -> a in
  let lcm = Array.fold_left lcm 1 as_ in
  Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 @@ Array.map (fun a -> (lcm - 1) mod a) as_


open Scanf
open Printf

let consume c b x = if x <= c
  then x - b
  else if (x - c) mod b = 0
  then c
  else c + (x - c) mod b - b

let f a b c d = let arr = Array.make (c+1) false in
  let rec g n x = if x < 0
    then printf "No\n"
    else if n < 0 || arr.(x)
    then printf "Yes\n"
    else (arr.(x) <- true; g (n-1) (consume c b (x+d)))
  in g c (consume c b a)

let () = scanf "%d\n" (fun c ->
  for i = 1 to c do
    scanf "%d %d %d %d\n" f
  done)

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning.
Snuke buys B cans of juice here every day in the daytime.
Then, the manager checks the number of cans of juice remaining in stock every night.
If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them.
Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

1 \leq T \leq 300

1 \leq A, B, C, D \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain Yes if Snuke can buy apple juice indefinitely in the i-th query; No otherwise.

Sample Input 1

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Sample Output 1

No
Yes
No
Yes
Yes
No
No
Yes
No
Yes
Yes
No
No
Yes

In the first query, the number of cans of juice in stock changes as follows: (D represents daytime and N represents night.)

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 6
→D x

In the second query, the number of cans of juice in stock changes as follows:

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 15
→D 8
→N 8
→D 1
→N 10
→D 3
→N 12
→D 5
→N 14
→D 7
→N 7
→D 0
→N 9
→D 2
→N 11
→D …

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

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

Sample Output 2

No
No
No
No
No
No
Yes
Yes
No
No
No
No
Yes
Yes
Yes
No
No
No
Yes
Yes
Yes
No
No
No


module Int64Set = Set.Make (Int64)

let rec solve aset a b c d =
  let ( + ) = Int64.add in
  let ( - ) = Int64.sub in
  let ( mod ) = Int64.rem in
  if a < b then "No"
  else if Int64Set.mem a aset then "Yes"
  else if a - b <= c then
    if d = b then "Yes"
    else if d < b then "No"
    else solve (Int64Set.add a aset) (d + c - (c + b - a) mod (d - b)) b c d
  else
    solve (Int64Set.add a aset) (c + if (a - c) mod b = 0L then b else (a - c) mod b) b c d
let solve = solve Int64Set.empty

let () = Scanf.scanf "%d\n" @@ fun t ->
  for i = 0 to t - 1 do
    Scanf.scanf "%d %d %d %d\n" @@ fun a b c d ->
      print_endline @@
      solve (Int64.of_int a) (Int64.of_int b) (Int64.of_int c) (Int64.of_int d)
  done


module Memo = Map.Make(struct
  type t = string * string
  let compare = compare
end)
let str_of_list xs = List.fold_left (fun s c -> s ^ String.make 1 c) "" xs
let pow_str s f =
  let len = String.length s in
  let rec loop idx a b =
    if idx >= len then [(str_of_list (f a), str_of_list (f b))]
    else loop (idx+1) (s.[idx]::a) b @ loop (idx+1) a (s.[idx]::b)
  in loop 0 [] []
let () =
  Scanf.scanf "%d %s" @@ fun n s ->
  let s0, s1 = String.(sub s 0 n, sub s n n) in
  let memo = pow_str s0 (fun x -> x) |> List.fold_left (fun m p ->
    try let v = Memo.find p m in Memo.add p (v+1) m
    with Not_found -> Memo.add p 1 m) Memo.empty
  in
  pow_str s1 List.rev |> List.fold_left (fun s p ->
    try let v = Memo.find p memo in s + v
    with Not_found -> s) 0
  |> Printf.printf "%d\n"

Score : 600 points

Problem Statement

You are given a string S of length 2N consisting of lowercase English letters.

There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition?

The string obtained by reading the characters painted red from left to right is equal to the string obtained by reading the characters painted blue from right to left.

Constraints

1 \leq N \leq 18

The length of S is 2N.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of ways to paint the string that satisfy the condition.

Sample Input 1

4
cabaacba

Sample Output 1

4

There are four ways to paint the string, as follows:

cabaacba

cabaacba

cabaacba

cabaacba

Sample Input 2

11
mippiisssisssiipsspiim

Sample Output 2

504

Sample Input 3

4
abcdefgh

Sample Output 3

0

Sample Input 4

18
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Sample Output 4

9075135300

The answer may not be representable as a 32-bit integer.


let s = read_line ()
let w = read_int ()
let _ = String.iteri (fun i c -> if i mod w = 0 then print_char c) s; print_newline ()

Score : 200 points

Problem Statement

You are given a string S consisting of lowercase English letters.
We will write down this string, starting a new line after every w letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.

Constraints

1 \leq w \leq |S| \leq 1000

S consists of lowercase English letters.

w is an integer.

Input

Input is given from Standard Input in the following format:

S
w

Output

Print the desired string in one line.

Sample Input 1

abcdefgh
3

Sample Output 1

adg

When we write down abcdefgh, starting a new line after every three letters, we get the following:

abc

def

gh

Concatenating the letters at the beginnings of these lines, we obtain adg.

Sample Input 2

lllll
1

Sample Output 2

lllll

Sample Input 3

souuundhound
2

Sample Output 3

suudon


let () = Scanf.scanf "%d %d %d" @@ fun n m d ->
  if n - d < 1 then
    print_endline "0.0"
  else if d = 0 then
    Printf.printf "%.10f\n" @@ float_of_int (n - d) /. float_of_int (n * n) *. float_of_int (m - 1)
  else
    Printf.printf "%.10f\n" @@ 2. *. float_of_int (n - d) /. float_of_int (n * n) *. float_of_int (m - 1)

Score : 300 points

Problem Statement

Let us define the beauty of a sequence (a_1,... ,a_n) as the number of pairs of two adjacent elements in it whose absolute differences are d.
For example, when d=1, the beauty of the sequence (3, 2, 3, 10, 9) is 3.

There are a total of n^m sequences of length m where each element is an integer between 1 and n (inclusive).
Find the beauty of each of these n^m sequences, and print the average of those values.

Constraints

0 \leq d < n \leq 10^9

2 \leq m \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m d

Output

Print the average of the beauties of the sequences of length m where each element is an integer between 1 and n.
The output will be judged correct if the absolute or relative error is at most 10^{-6}.

Sample Input 1

2 3 1

Sample Output 1

1.0000000000

The beauty of (1,1,1) is 0.

The beauty of (1,1,2) is 1.

The beauty of (1,2,1) is 2.

The beauty of (1,2,2) is 1.

The beauty of (2,1,1) is 1.

The beauty of (2,1,2) is 2.

The beauty of (2,2,1) is 1.

The beauty of (2,2,2) is 0.

The answer is the average of these values: (0+1+2+1+1+2+1+0)/8=1.

Sample Input 2

1000000000 180707 0

Sample Output 2

0.0001807060


type t = FIN | ANS of int | ILL;;

Scanf.scanf "%d %d" (fun n m ->
    let nei = Array.make n [] in
    for i = 1 to m do
        Scanf.scanf " %d %d %d" (fun u v s ->
            let u = u - 1 in
            let v = v - 1 in
            nei.(u) <- (v, s) :: nei.(u);
            nei.(v) <- (u, s) :: nei.(v);
        )
    done;

    let dist = Array.make n (0, 0) in

    let rec loop cur =
        let (c, v) = dist.(cur) in
        let rec loop2 = function
            | [] -> FIN
            | (nn, nc) :: tl ->
                let mc, mv = nc - c, -v in
                if dist.(nn) = (0, 0) then (
                    dist.(nn) <- mc, mv;
                    let ret = loop nn in
                    if ret = FIN then loop2 tl else ret)
                else (
                    if dist.(nn) = (mc, mv) then loop2 tl else (
                        let qc, qv = dist.(nn) in
                        if mv = qv then ILL else
                        if (qc - mc) mod (mv - qv) = 0 &&
                            (qc - mc) / (mv - qv) > 0 then (
                                ANS ((qc - mc) / (mv - qv))
                            ) else ILL
                    )
                )
        in
        loop2 nei.(cur)
    in

    let single k =
        let dist2 = Array.make n 0 in
        let rec loop cur =
            let c = dist2.(cur) in
            let rec loop2 = function
                | [] -> 1
                | (nn, nc) :: tl ->
                        let mc = nc - c in
                        if mc <= 0 then 0 else (
                            if dist2.(nn) = 0 then (
                                dist2.(nn) <- mc;
                                if loop nn = 1 then loop2 tl else 0
                            ) else (
                                if dist2.(nn) = mc then loop2 tl else 0
                            )
                        )
            in
            loop2 nei.(cur)
        in
        dist2.(0) <- k;
        loop 0
    in
    let check dist =
        let rec loop i l r =
            if i = n then max 0 (r - l + 1) else
                let (c, v) = dist.(i) in
                if v = 1 then loop (i + 1) (max l (-c)) r
                         else loop (i + 1) l (min r (c - 1))
        in
        loop 0 1 max_int
    in

    dist.(0) <- 0, 1;
    match loop 0 with
    | FIN   -> Printf.printf "%d\n" @@ check dist
    | ANS k -> Printf.printf "%d\n" @@ single k
    | ILL   -> Printf.printf "0\n"
)

Score : 600 points

Problem Statement

Kenkoooo found a simple connected graph.
The vertices are numbered 1 through n.
The i-th edge connects Vertex u_i and v_i, and has a fixed integer s_i.

Kenkoooo is trying to write a positive integer in each vertex so that the following condition is satisfied:

For every edge i, the sum of the positive integers written in Vertex u_i and v_i is equal to s_i.

Find the number of such ways to write positive integers in the vertices.

Constraints

2 \leq n \leq 10^5

1 \leq m \leq 10^5

1 \leq u_i < v_i \leq n

2 \leq s_i \leq 10^9

If i\neq j, then u_i \neq u_j or v_i \neq v_j.

The graph is connected.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m
u_1 v_1 s_1
:
u_m v_m s_m

Output

Print the number of ways to write positive integers in the vertices so that the condition is satisfied.

Sample Input 1

3 3
1 2 3
2 3 5
1 3 4

Sample Output 1

1

The condition will be satisfied if we write 1,2 and 3 in vertices 1,2 and 3, respectively.
There is no other way to satisfy the condition, so the answer is 1.

Sample Input 2

4 3
1 2 6
2 3 7
3 4 5

Sample Output 2

3

Let a,b,c and d be the numbers to write in vertices 1,2,3 and 4, respectively.
There are three quadruples (a,b,c,d) that satisfy the condition:

(a,b,c,d)=(1,5,2,3)

(a,b,c,d)=(2,4,3,2)

(a,b,c,d)=(3,3,4,1)

Sample Input 3

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

Sample Output 3

0


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

let test a b =
	Array.fold_left (fun (u,i) v ->
		Printf.printf "  %d::abs(%d-(%d+%d))=%d\n"
			i v b i (abs (v-(b+i)))
		;
		(u + (abs (v - (b+i)))), i+1) (0,1) a
	|> fst
let min_listi ls =
	let rec f0 i l v vi = match l with
	| [] -> (v,i) | h::t -> if (h < v) then f0 (i+1) t h i else f0 (i+1) t v vi
	in f0 0 ls max_int (-1)

let () =
	let n = get_int ()
	in let a = input_int_array n
	in let a_cal b = Array.init n (fun i -> a.(i)-b-i-1)
	in let (m,mi) = min_listi (a|>Array.to_list)
	in
	let f = ref true
	in let b = ref m
	in let la = ref max_int
	in let a_res = a_cal !b
	in
	while !f do
		let r = Array.fold_left (fun u v -> u + abs v) 0 a_res
		in
		(* Printf.printf "%d::%d\n" !b r; *)
		if r < !la then (
			la := r; b := !b - 1;
			for i=0 to Array.length a - 1 do
				a_res.(i) <- a_res.(i) + 1
			done
		) else (
			f := false
		)
	done;
	!la |> string_of_int |> print_endline

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

He will freely choose an integer b.
Here, he will get sad if A_i and b+i are far from each other.
More specifically, the sadness of Snuke is calculated as follows:

abs(A_1 - (b+1)) + abs(A_2 - (b+2)) + ... + abs(A_N - (b+N))

Here, abs(x) is a function that returns the absolute value of x.

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

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 minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

If we choose b=0, the sadness of Snuke would be abs(2-(0+1))+abs(2-(0+2))+abs(3-(0+3))+abs(5-(0+4))+abs(5-(0+5))=2.
Any choice of b does not make the sadness of Snuke less than 2, so the answer is 2.

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


open Printf
open Scanf

let solve s =
  let f i = if s.[i] = '+' then 1 else -1 in
  List.fold_left (+) 0 @@ List.map f [0;1;2;3]

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

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = Printf.printf "%d\n" @@ (n - 2) / (k - 1) + 1

Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


let () =
  let n, k = Scanf.scanf "%d %d" (fun n k -> n, k) in
  let a =
    Array.init n (fun _ ->
        Scanf.scanf " %d" (fun x -> x)) in
  let (_, i1) = Array.fold_left (fun (i, res) x ->
               if x = 1 then
                 (i+1, i)
               else
                 (i+1, res)
             ) (0, 0) a in
  Printf.printf "%d\n"
    (if i1 = 0 then
       (n) / (k-1)
     else if i1 < k then
      1 + (n-i1) / (k-1)
    else
      1 + (i1) / (k-1) + (n-i1+1)/(k-1))


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

let () = Printf.printf "%d\n" @@ (n + k - 1)/ k


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@ (n + k - 3) / (k - 1)


Scanf.scanf "%d" (fun k ->
    let l = [ 1,  9; 1,  9;  1,  19;  2,  29;  3,  39;  4,  49;  5, 59;
              6, 69; 7, 79;  8,  89;  9,  99; 10, 109; 11, 109; 11, 99 ]
    in

    let proc ten s t acc =
        let rec loop i acc =
            if i > t then acc else
                loop (i + 1) ((i * ten + ten - 1) :: acc)
        in
        loop s acc
    in

    let rec loop ten acc = function
        | [] -> acc
        | (s, t) :: tl ->
                loop (ten * 10) (proc ten s t acc) tl
    in
    let r = Array.of_list (loop 1 [] l) in
    Array.sort compare r;
    for i = 0 to k - 1 do
        Printf.printf "%d\n" r.(i)
    done
)

Score : 500 points

Problem Statement

Let S(n) denote the sum of the digits in the decimal notation of n.
For example, S(123) = 1 + 2 + 3 = 6.

We will call an integer n a Snuke number when, for all positive integers m such that m > n, \frac{n}{S(n)} \leq \frac{m}{S(m)} holds.

Given an integer K, list the K smallest Snuke numbers.

Constraints

1 \leq K

The K-th smallest Snuke number is not greater than 10^{15}.

Input

Input is given from Standard Input in the following format:

K

Output

Print K lines. The i-th line should contain the i-th smallest Snuke number.

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19


let rec s = function
  | 0 -> 0
  | n -> n mod 10 + s (n / 10)

let p x y = x * s y <= y * s x

let bases = Array.to_list @@ Array.init 16 (fun d -> int_of_float (10. ** float_of_int d))

let solutions =
  Array.init 1000 (fun i ->
    List.filter (fun r ->
      p ((i + 1) * r - 1) ((i - i mod 10 + 10) * r - 1) &&
      p ((i + 1) * r - 1) ((i - i mod 100 + 100) * r - 1) &&
      p ((i + 1) * r - 1) ((i - i mod 1000 + 1000) * r - 1)) bases
    |> List.map (fun r -> (i + 1) * r - 1))
  |> Array.to_list
  |> List.concat
  |> List.sort_uniq compare
  |> Array.of_list

let () = Scanf.scanf "%d" @@ fun k ->
  for i = 1 to k do
    Printf.printf "%d\n" solutions.(i - 1)
  done


let () = Scanf.scanf "%d %d" (fun x y -> if x > 8 || y > 8 then Printf.printf ":(\n" else Printf.printf "Yay!\n")

Score: 100 points

Problem Statement

E869120's and square1001's 16-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into 16 equal fan-shaped pieces.

E869120 and square1001 were just about to eat A and B of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

A and B are integers between 1 and 16 (inclusive).

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.


let change a =
	let rec change a n =
    	if a land 1 == 0 then change (a lsr 1) (n + 1) else n
    in change a 0
let calc n =
	let rec calc n ans =
    	if n = 0 then print_int ans
        else calc (n - 1) (ans + Scanf.scanf " %d" change)
    in calc n 0
let main = Scanf.scanf "%d" calc

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

N is an integer between 1 and 10 \ 000 (inclusive).

a_i is an integer between 1 and 1 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


let n = read_int () in

print_endline(if n < 1000 then "ABC" else "ABD")

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

The contests are labeled as ABC001, ABC002, ... from the first round, but after the 999-th round ABC999, a problem occurred: how the future rounds should be labeled?

In the end, the labels for the rounds from the 1000-th to the 1998-th are decided: ABD001, ABD002, ..., ABD999.

You are given an integer N between 1 and 1998 (inclusive). Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the first three characters of the label of the N-th round of AtCoder Beginner Contest.

Sample Input 1

999

Sample Output 1

ABC

The 999-th round of AtCoder Beginner Contest is labeled as ABC999.

Sample Input 2

1000

Sample Output 2

ABD

The 1000-th round of AtCoder Beginner Contest is labeled as ABD001.

Sample Input 3

1481

Sample Output 3

ABD

The 1481-th round of AtCoder Beginner Contest is labeled as ABD482.


let n = read_int()
let a = Array.make (n + 1) 0

let rec f i =
  if i = n + 1 then a.(n)
  else
    let rec g i j k =
      if j < k then j - k / i
      else g i j (k * i) in
    a.(i) <- 1 + min a.(g 6 i 1) a.(g 9 i 1);
    f (i + 1)

let () = Printf.printf "%d\n" (f 1)

Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


let rec seq a b = if a >= b then [] else a :: seq (a+1) b
let (>>=) x f = List.map f x |> List.concat
let () =
  Scanf.scanf "%d %d" @@ fun n c ->
  let d =
    Array.init c (fun i ->
      Array.init c (fun j -> Scanf.scanf " %d" ((+) 0)))
  in
  let b =
    Array.init n (fun i ->
      Array.init n (fun j -> Scanf.scanf " %d" ((+) 0)))
  in

  let sc = Array.init 3 (fun _ -> Array.make c 0) in
  let _ =
    seq 0 n >>= fun x ->
    seq 0 n >>= fun y ->
      let i = (x + y) mod 3 in
      seq 0 c |> List.iter (fun j -> sc.(i).(j) <- sc.(i).(j) + d.(b.(x).(y)-1).(j));
      []
  in

  (seq 0 c >>= fun i ->
   seq 0 c >>= fun j ->
   seq 0 c >>= fun k ->
     if i = j || j = k || k = i then []
     else [ sc.(0).(i) + sc.(1).(j) + sc.(2).(k) ])
  |> List.fold_left min 10101010101010
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

There is a grid with N rows and N columns of squares. Let (i,j) be the square at the i-th row from the top and the j-th column from the left.

These squares have to be painted in one of the C colors from Color 1 to Color C. Initially, (i,j) is painted in Color c_{i,j}.

We say the grid is a good grid when the following condition is met for all i,j,x,y satisfying 1 \leq i,j,x,y \leq N:

If (i+j) \% 3=(x+y) \% 3, the color of (i,j) and the color of (x,y) are the same.

If (i+j) \% 3 \neq (x+y) \% 3, the color of (i,j) and the color of (x,y) are different.

Here, X \% Y represents X modulo Y.

We will repaint zero or more squares so that the grid will be a good grid.

For a square, the wrongness when the color of the square is X before repainting and Y after repainting, is D_{X,Y}.

Find the minimum possible sum of the wrongness of all the squares.

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)

1 \leq c_{i,j} \leq C

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N C
D_{1,1} ... D_{1,C}
:
D_{C,1} ... D_{C,C}
c_{1,1} ... c_{1,N}
:
c_{N,1} ... c_{N,N}

Output

If the minimum possible sum of the wrongness of all the squares is x, print x.

Sample Input 1

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

Sample Output 1

3

Repaint (1,1) to Color 2. The wrongness of (1,1) becomes D_{1,2}=1.

Repaint (1,2) to Color 3. The wrongness of (1,2) becomes D_{2,3}=1.

Repaint (2,2) to Color 1. The wrongness of (2,2) becomes D_{3,1}=1.

In this case, the sum of the wrongness of all the squares is 3.

Note that D_{i,j} \neq D_{j,i} is possible.

Sample Input 2

4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2

Sample Output 2

428


let rec fact n =
  if n = 0 then 1 else n * fact (n - 1)
;;
let bi_c  n k =
  fact n / ((fact k) * (fact (n - k)))
;;

let rec rgb a b n k x sum  =
  if x <= 0 then sum
  else
    let y = (k - a * x) / b in
    if a * x + b * y = k && 0 <= y && y <= n then
      rgb a b n k (x - 1) (sum +  (bi_c n x) * (bi_c n y))
    else
      rgb a b n k (x - 1) (sum)

let () =
  let n, a, b, k = Scanf.scanf "%d %d %d %d"
                     (fun n a b k -> n, a, b, k) in
  (rgb a b n k n 0) mod 998244353
|> print_int

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

It is known that A plus B equals N.
Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".

Sample Input 1

15

Sample Output 1

6

When A=2 and B=13, the sums of their digits are 2 and 4, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10


(* nCr = {(n-r+1)/r}nCr-1 *)
let const = 998244353
let ( *$ ) x y = x * y mod const
let ( +$ ) x y = x + y mod const
let rec power x n =
  if n <= 0 then 1
  else if n mod 2 = 0 then
    power (x *$ x) (n/2)
  else
    x *$ power x (n - 1)
let mod_inv x =
  power x (const - 2)

let () =
  let n, a, b, k = Scanf.scanf "%d %d %d %d"
                     (fun n a b k -> n, a, b, k) in
  let binomial = Array.make (n + 1) 1 in
  for i = 1 to n do
    binomial.(i) <- binomial.(i-1)  *$ (n+1-i) *$ mod_inv i
  done;
  Array.init (n+1) (fun x ->
      let y = (k - a * x) / b in
      if a * x + b * y = k && 0 <= y && y <= n then
        binomial.(x) *$ binomial.(y)
      else
        0)
  |> Array.fold_left (fun x y -> x +$ y) 0
  |> Printf.printf "%d\n"

Score : 700 points

Problem Statement

Takahashi has a tower which is divided into N layers.
Initially, all the layers are uncolored. Takahashi is going to paint some of the layers in red, green or blue to make a beautiful tower.
He defines the beauty of the tower as follows:

The beauty of the tower is the sum of the scores of the N layers, where the score of a layer is A if the layer is painted red, A+B if the layer is painted green, B if the layer is painted blue, and 0 if the layer is uncolored.

Here, A and B are positive integer constants given beforehand. Also note that a layer may not be painted in two or more colors.

Takahashi is planning to paint the tower so that the beauty of the tower becomes exactly K.
How many such ways are there to paint the tower? Find the count modulo 998244353.
Two ways to paint the tower are considered different when there exists a layer that is painted in different colors, or a layer that is painted in some color in one of the ways and not in the other.

Constraints

1 ≤ N ≤ 3×10^5

1 ≤ A,B ≤ 3×10^5

0 ≤ K ≤ 18×10^{10}

All values in the input are integers.

Input

Input is given from Standard Input in the following format:

N A B K

Output

Print the number of the ways to paint tiles, modulo 998244353.

Sample Input 1

4 1 2 5

Sample Output 1

40

In this case, a red layer worth 1 points, a green layer worth 3 points and the blue layer worth 2 points. The beauty of the tower is 5 when we have one of the following sets of painted layers:

1 green, 1 blue

1 red, 2 blues

2 reds, 1 green

3 reds, 1 blue

The total number of the ways to produce them is 40.

Sample Input 2

2 5 6 0

Sample Output 2

1

The beauty of the tower is 0 only when all the layers are uncolored. Thus, the answer is 1.

Sample Input 3

90081 33447 90629 6391049189

Sample Output 3

577742975


let result = ref 0;;
let rec fact n = if n = 0 then 1 else n * fact (n - 1);;

let () =
  let n, a, b, k = Scanf.scanf "%d %d %d %d"
                     (fun n a b k -> n, a, b, k) in
  let rgb_color () =
    for i = 0 to n do
      let n1 = n - i in
      for j = 0 to n1 do
        let n2 = n1 - j in
        for s = 0 to n2 do
          let n3 = n2 - s in
          for t = 0 to n3 do
            if (i * a + j * (a+b) + s * b)  = k && i+j+s+t = n then
              let r = if i = 0 || i = 1 then 0 else fact i in
              let g = if  j = 0 || j = 1 then 0 else fact j in
              let b = if  s = 0 || s = 1 then 0 else fact s in
              let c = if  t = 0 || t = 1 then 0 else fact t in
            result :=
              (!result) +  (fact n / (r + g + b + c))
          else
            ()
          done
        done
      done
    done
  in
  let _ = rgb_color () in
  let x = (!result) mod  998244353 in
  print_endline (string_of_int x)


let f a b = max (a+b) (max (a-b) (a*b));;
let () = Scanf.scanf "%d %d" f
|> Printf.printf "%d\n"

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest value among A+B, A-B and A \times B.

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


let n = read_int ()
let s = read_line ()
let ans = ref 0
let _ = for i = 0 to n - 1 do let c = ref 0 in
  for j = Char.code 'a' to Char.code 'z' do if String.(contains (sub s 0 i) @@ Char.chr j && contains (sub s i @@ n - i) @@ Char.chr j) then incr c done;
  ans := max !ans !c done; Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.
We will cut this string at one position into two strings X and Y.
Here, we would like to maximize the number of different letters contained in both X and Y.
Find the largest possible number of different letters contained in both X and Y when we cut the string at the optimal position.

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the largest possible number of different letters contained in both X and Y.

Sample Input 1

6
aabbca

Sample Output 1

2

If we cut the string between the third and fourth letters into X = aab and Y = bca, the letters contained in both X and Y are a and b.
There will never be three or more different letters contained in both X and Y, so the answer is 2.

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

However we divide S, only a will be contained in both X and Y.

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


(* O(n^3) *)
let n = read_int ()
let s = read_line ()
let ans = ref 0
let _ =
  for i = 1 to n - 1 do
    let x = String.sub s 0 i in
    let y = String.sub s i @@ n - i in
    let flags = Array.make 128 false in
    let count = ref 0 in
    let f c =
      if not flags.(int_of_char c) then
        (flags.(int_of_char c) <- true;
        try (String.index y c |> ignore; incr count) with
        | _ -> ()) in
    String.iter f x;
    ans := max !ans !count
  done;
  Printf.printf "%d\n" !ans


let rec iter a b f = if a >= b then () else (f a; iter (a+1) b f)
let () =
  Scanf.scanf "%d %s" @@ fun n s ->
  let w = Array.init n (fun i -> if s.[i] = 'W' then 1 else 0) in
  let e = Array.init n (fun i -> if s.[i] = 'E' then 1 else 0) in
  iter 1 n (fun i -> w.(i) <- w.(i) + w.(i-1));
  iter 1 n (fun i -> e.(n-1-i) <- e.(n-1-i) + e.(n-i));
  Array.init n (fun i ->
    (if i > 0 then w.(i-1) else 0) + (if i+1 < n then e.(i+1) else 0))
  |> Array.fold_left min n |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


let _ = Scanf.scanf "%d\n" @@ fun n ->
  let ps = Array.init n @@ fun _ ->
    Scanf.scanf "%d\n" @@ fun p -> p in
  (* ps.(inv_ps.(i)) = i かつ inv_ps.(ps.(i)) = i なのを作る *)
  let inv_ps = Array.make (n + 1) 0 in
  Array.iteri (fun i p ->
    (* p = ps.(i) *)
    inv_ps.(p) <- i) ps;
  Array.init n (( + ) 1)
  |> Array.fold_left (fun (acc, s) p ->
      s :: acc,
      if inv_ps.(p - 1) <= inv_ps.(p)
      then s + 1
      else 1) ([], 0)
  |> (fun (acc, s) -> List.fold_left max s acc)
  |> (( - ) n)
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N.
You would like to sort this sequence in ascending order by repeating the following operation:

Choose an element in the sequence and move it to the beginning or the end of the sequence.

Find the minimum number of operations required.
It can be proved that it is actually possible to sort the sequence using this operation.

Constraints

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

(P_1,P_2,...,P_N) is a permutation of (1,2,...,N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1
:
P_N

Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4

Sample Output 1

2

For example, the sequence can be sorted in ascending order as follows:

Move 2 to the beginning. The sequence is now (2,1,3,4).

Move 1 to the beginning. The sequence is now (1,2,3,4).

Sample Input 2

6
3
2
5
1
4
6

Sample Output 2

4

Sample Input 3

8
6
3
1
2
7
4
8
5

Sample Output 3

5


let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let a = Array.to_list @@ Array.init n @@ fun _ -> int_of_string @@ read_line ()

let () =
  if List.hd a != 0 then print_endline "-1"
  else
    let (sum, _) = List.fold_left (fun (sum, before) i ->
      (sum + (if i > before then i - before else i), i)
    ) (0, 0) @@ List.tl a in
    Printf.printf "%d\n" sum

Score : 700 points

Problem Statement

There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X.

You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required.

Choose an integer i such that 1\leq i\leq N-1. Replace the value of X_{i+1} with the value of X_i plus 1.

Constraints

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

0 \leq A_i \leq 10^9(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

If we can make X equal to A by repeating the operation, print the minimum number of operations required. If we cannot, print -1.

Sample Input 1

4
0
1
1
2

Sample Output 1

3

We can make X equal to A as follows:

Choose i=2. X becomes (0,0,1,0).

Choose i=1. X becomes (0,1,1,0).

Choose i=3. X becomes (0,1,1,2).

Sample Input 2

3
1
2
1

Sample Output 2

-1

Sample Input 3

9
0
1
1
0
1
2
2
1
2

Sample Output 3

8


let f a b c d = [abs (a-b) <= d; abs (b-c) <= d; abs (c-a)<= d];;
let f2 [b1;b2;b3] = if b3 then "Yes" else (if b2 && b1 then "Yes" else "No");;
let () = Scanf.scanf "%d %d %d %d" f
|> f2 |> Printf.printf "%s\n"

Score : 100 points

Problem Statement

Three people, A, B and C, are trying to communicate using transceivers.
They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively.
Two people can directly communicate when the distance between them is at most d meters.
Determine if A and C can communicate, either directly or indirectly.
Here, A and C can indirectly communicate when A and B can directly communicate and also B and C can directly communicate.

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

If A and C can communicate, print Yes; if they cannot, print No.

Sample Input 1

4 7 9 3

Sample Output 1

Yes

A and B can directly communicate, and also B and C can directly communicate, so we should print Yes.

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


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

let () = main ()


let () =
  let s = Scanf.scanf "%s " (fun a -> a) in
  let k = Scanf.scanf "%d " (fun a -> a) in

  let length = String.length s in

  let rec f str fst fnl res =
    if fst = length then res else (
      let res = (String.sub str fst fnl) :: res in
      if (fst + fnl = length || fnl - fst = k) then
        f str (fst+1) 1 res
      else
        f str fst (fnl+1) res
    )

  in
  let lst = f s 0 1 [] in
  let lst = List.sort_uniq compare lst in

  print_endline (List.nth lst (k-1))

Score : 300 points

Problem Statement

You are given a string s.
Among the different substrings of s, print the K-th lexicographically smallest one.

A substring of s is a string obtained by taking out a non-empty contiguous part in s.
For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

Let X = x_{1}x_{2}...x_{n} and Y = y_{1}y_{2}...y_{m} be two distinct strings. X is lexicographically larger than Y if and only if Y is a prefix of X or x_{j} > y_{j} where j is the smallest integer such that x_{j} \neq y_{j}.

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

200 points will be awarded as a partial score for passing the test set satisfying |s| ≤ 50.

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

s has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


let () =
  let s = Scanf.scanf "%s " (fun a -> a) in
  let k = Scanf.scanf "%d " (fun a -> a) in

  let srd l =
    let sl = List.sort compare l in
    let rec go l acc = match l with
      | [] -> List.rev acc
      | [x] -> List.rev (x::acc)
      | (x1::x2::xs) ->
        if x1 = x2
        then go (x2::xs) acc
        else go (x2::xs) (x1::acc)
    in go sl []
  in

  let length = String.length s in

  let rec f str fst fnl res =
    if fst = length then res else (
      let res = (String.sub str fst fnl) :: res in
      if (fst + fnl = length || fnl - fst = k) then
        f str (fst+1) 1 res
      else
        f str fst (fnl+1) res
    )

  in
  let lst = f s 0 1 [] in
  let lst = srd lst in

  List.iter print_endline lst;
  print_endline (List.nth lst (k-1))


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

let s_len = String.length s

let () =
  let acc =
    List.init s_len (fun i -> List.init (min 5 (s_len - i)) (fun j -> String.sub s i (j + 1)))
    |> List.flatten
    |> List.sort_uniq compare in
  print_endline @@ List.nth acc (k - 1)


let rec solve trace (acc, cas) (c, a) =
  match cas with
  | [] -> (acc, List.rev_append trace [(c, a)])
  | (c', a') :: cas' ->
      if c = c' && a <= a' then
        (acc + List.length cas, List.rev_append trace ((c, a) :: cas))
      else
        solve ((c', a') :: trace) (acc, cas') (c, a)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let cas = Array.init (2 * n) @@ fun _ -> Scanf.scanf "%c %d\n" @@ fun c a -> c, a in
  Printf.printf "%d\n" @@ fst @@ Array.fold_left (solve []) (0, []) cas

Score : 600 points

Problem Statement

There are 2N balls, N white and N black, arranged in a row. The integers from 1 through N are written on the white balls, one on each ball, and they are also written on the black balls, one on each ball.
The integer written on the i-th ball from the left (1 ≤ i ≤ 2N) is a_i, and the color of this ball is represented by a letter c_i.
c_i = W represents the ball is white; c_i = B represents the ball is black.

Takahashi the human wants to achieve the following objective:

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the white ball with i written on it is to the left of the white ball with j written on it.

For every pair of integers (i,j) such that 1 ≤ i < j ≤ N, the black ball with i written on it is to the left of the black ball with j written on it.

In order to achieve this, he can perform the following operation:

Swap two adjacent balls.

Find the minimum number of operations required to achieve the objective.

Constraints

1 ≤ N ≤ 2000

1 ≤ a_i ≤ N

c_i = W or c_i = B.

If i ≠ j, (a_i,c_i) ≠ (a_j,c_j).

Input

Input is given from Standard Input in the following format:

N
c_1 a_1
c_2 a_2
:
c_{2N} a_{2N}

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3
B 1
W 2
B 3
W 1
W 3
B 2

Sample Output 1

4

The objective can be achieved in four operations, for example, as follows:

Swap the black 3 and white 1.

Swap the white 1 and white 2.

Swap the black 3 and white 3.

Swap the black 3 and black 2.

Sample Input 2

4
B 4
W 4
B 3
W 3
B 2
W 2
B 1
W 1

Sample Output 2

18

Sample Input 3

9
W 3
B 1
B 4
W 1
B 5
W 9
W 2
B 6
W 5
B 3
W 8
B 9
W 7
B 2
B 8
W 4
W 6
B 7

Sample Output 3

41


Scanf.scanf "%d %d" @@ fun a b -> Printf.printf "%d\n" @@ if a <= b then a else a - 1

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


let f a b = if a <= b then a else a-1;;
let () = Scanf.scanf "%d %d" f
|> Printf.printf "%d\n"


(* エラトステネスのふるい *)
let sieve :
  (* 素数かどうかを判定する自然数の上界 *)
  int ->
  (* 素数ならtrueを返す関数 *)
  (int -> bool)
  = fun n ->
    let a = Array.make n true in
    a.(0) <- false;
    a.(1) <- false;
    for p = 2 to int_of_float @@ ceil @@ sqrt @@ float_of_int n do
      if a.(p) then
        for i = p to (n - 1) / p do
          a.(p * i) <- false
        done
    done;
    Array.get a

let rec take n = function
  | [] -> []
  | x :: xs ->
      if n = 0 then []
      else x :: take (n - 1) xs

let () = Scanf.scanf "%d\n" @@ fun n ->
  let p = sieve 55555 in
  Array.init 55555 (fun i -> i)
  |> Array.to_list
  (*
   * (5i + 1) + (5j + 1) + (5k + 1) + (5l + 1) + (5m + 1)
   * = 5 (i + j + k + l + m + 1)
   *)
  |> List.filter (fun n -> n mod 5 = 1 && p n)
  |> take n
  |> List.iter (Printf.printf "%d ")


let main () =
  let a, b, c = Scanf.scanf "%d %d %d\n" (fun a b c -> a, b, c) in
  let k = Scanf.scanf "%d\n" (fun a -> a) in
  let rec pow i j = if j = 1 then i else pow (i * i) (j - 1) in
  let ans1 = a * (pow 2 k) + b + c in
  let ans2 = a + b * (pow 2 k) + c in
  let ans3 = a + b + c * (pow 2 k) in
  Printf.printf "%d\n" (max (max ans1 ans2) ans3);;

let _ = main ()


(* O(n) *)
open Array
open Hashtbl
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let sums = make (n + 1) 0
let h = create @@ n + 1
let f s = try let c = find h s in replace h s @@ c + 1 with _ -> add h s 1
let _ =
  iteri (fun i a -> sums.(i + 1) <- sums.(i) + a) a_s;
  Array.iter f sums;
  fold (fun s c acc -> acc + if c > 1 then c * (c - 1) / 2 else 0) h 0 |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

We have an integer sequence A, whose length is N.

Find the number of the non-empty contiguous subsequences of A whose sums are 0.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

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

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

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

Find the number of the non-empty contiguous subsequences of A whose sum is 0.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are 0: (1,3,-4), (-4,2,2) and (2,-2).

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of (1, -1) are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


open Batteries

module Int64map = Map.Make(Int64)

let () =
  let a = Scanf.scanf "%d\n" (fun a -> a) in

  let arr = Array.make a 0L in
  for i = 0 to a-1-1 do
    let c = Scanf.scanf "%Ld " (fun c -> c) in
    Array.set arr i c
  done;
  let c = Scanf.scanf "%Ld\n" (fun c -> c) in
  Array.set arr (a-1) c;

  let arr2 = Array.make a 0L in
  for i=0 to a-1 do
    arr2.(i) <- (Int64.add arr.(i) (if i<>0 then arr2.(i-1) else 0L));
  done;

  let arr2 = Array.append arr2 [|0L|] in

  let nc2 n =
    if n < 2L then 0L else Int64.div (Int64.mul n (Int64.sub n 1L)) 2L
  in

  let m = ref Int64map.empty in

  Array.iter (fun x ->
      if Int64map.mem x !m then (
        m := Int64map.add x (Int64.add (Int64map.find x !m) 1L) !m;
      ) else (
        m := Int64map.add x 1L !m;
      );
    ) arr2;

  let mm = Int64map.map (nc2) !m in
  let cnt = Int64map.fold (fun k v1 v2 -> Int64.add v1 v2) mm 0L in

  print_endline (Int64.to_string cnt)


let rec for_fold a b v f = if a >= b then v else for_fold (a+1) b (f v a) f
let () =
  Scanf.scanf "%d" @@ fun n ->
  let s = Array.init n (fun _ -> Scanf.scanf " %s" (fun x -> x)) in
  let s = Array.init (2*n-1) (fun i ->
    Array.init n (fun j -> s.(i mod n).[j mod n])) in
  for_fold 0 n 0 (fun c i ->
    let sym =
      for_fold 0 (n*n) true (fun b j ->
        b && s.(i + j/n).(j mod n) = s.(i + j mod n).(j/n))
    in c + if sym then n else 0)
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.


let () = Scanf.scanf "%d\n" @@ fun n ->
  let ss = Array.init n @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  Printf.printf "%d\n" @@
    Array.fold_left (List.fold_left (fun acc (a, b, w) ->
      if
        List.for_all (fun i ->
          List.for_all (fun j ->
            ss.((i + a) mod n).[(j + b) mod n] = ss.((j + a) mod n).[(i + b) mod n]) @@
            Array.to_list @@
              Array.init i @@ fun j -> j) @@
            Array.to_list @@
              Array.init (n - 1) @@ fun i -> i + 1
      then acc + w
      else acc)) 0 @@
    Array.init n @@ function
      | 0 -> [(0, 0, n)]
      | i -> [(i, 0, n - i); (0, i, n - i)]


let () = Scanf.scanf "%d\n" @@ fun n ->
  let ss = Array.init n @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  Printf.printf "%d\n" @@
    Array.fold_left (Array.fold_left (fun acc (a, b) ->
      if
        List.for_all (fun i ->
          List.for_all (fun j ->
            ss.((i + a) mod n).[(j + b) mod n] = ss.((j + a) mod n).[(i + b) mod n]) @@
            Array.to_list @@
              Array.init i @@ fun j -> j) @@
            Array.to_list @@
              Array.init (n - 1) @@ fun i -> i + 1
      then acc + 1
      else acc)) 0 @@
      Array.init n @@ fun a ->
        Array.init n @@ fun b -> (a, b)


open Batteries

let () =
  let n = Scanf.scanf "%d\n" (fun a -> a) in

  let arr = Array.make_matrix n n '-' in
  for i = 0 to n-1 do
    for j = 0 to n-1-1 do
      let c = Scanf.scanf "%c " (fun c -> c) in
      Array.set (Array.get arr i) j c
    done;
    let c = Scanf.scanf "%c\n" (fun c -> c) in
    Array.set (Array.get arr i) (n-1) c
  done;

  let cnt = ref 0 in
  let cur_char = ref '-' in

  for j = 0 to n-1 do
    for i = 0 to n-1 do
      let j = j - i in
      let j = if j < 0 then j + n else j in
      let c = (Array.get (Array.get arr i) j) in
      if (i = 0) then (
        cur_char := c;
      ) else (
        if !cur_char <> c then (
          cur_char := '-';
        )
      );
    done;
    if !cur_char <> '-' then (
      cnt := !cnt + n
    )
  done;

  print_endline (string_of_int !cnt)


let f a b c = 700 + (if a='o' then 100 else 0) + (if b='o' then 100 else 0) + (if c='o' then 100 else 0);;
let () = Scanf.scanf "%c %c %c" f
|> Printf.printf "%d\n"

Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


let () =
let lst = Scanf.scanf "%1s%1s%1s\n" (fun a b c -> [a; b; c]) in
Printf.printf "%d\n" (List.fold_left (fun ans x -> if x = "o" then ans+100 else ans) 700 lst)


let list_init n f =
  let rec aux n f l = if n >= 0 then aux (n - 1) f (f n :: l) else l in
  aux (n - 1) f []

let () =
  let n, x = Scanf.scanf "%d %d" (fun n x -> (n, x)) in
  let ms = list_init n (fun _ -> Scanf.scanf " %d" (fun m -> m)) in
  let min_m = List.fold_left min (List.hd ms) ms in
  let sum_m = List.fold_left ( + ) 0 ms in
  let x = x - sum_m in
  let n = n + (x / min_m) in
  Printf.printf "%d\n" n

Score : 200 points

Problem Statement

Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams of Moto. She cannot make a non-integer number of doughnuts, such as 0.5 doughnuts.

Now, she has X grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:

For each of the N kinds of doughnuts, make at least one doughnut of that kind.

At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition.

Constraints

2 ≤ N ≤ 100

1 ≤ m_i ≤ 1000

m_1 + m_2 + ... + m_N ≤ X ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
m_1
m_2
:
m_N

Output

Print the maximum number of doughnuts that can be made under the condition.

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

She has 1000 grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes 120 + 100 + 140 = 360 grams of Moto. From the 640 grams of Moto that remains here, she can make additional six Doughnuts 2. This is how she can made a total of nine doughnuts, which is the maximum.

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

Making one doughnut for each of the four kinds consumes all of her Moto.

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26


let () =
  let a, b = Scanf.scanf "%d %d\n" (fun a b -> a, b) in

  let arr = Array.make a 0 in
  for i = 1 to a do
    let c = Scanf.scanf "%d\n" (fun c -> c) in
    Array.set arr (i-1) c
  done;

  let lst = Array.to_list arr in
  let sum = List.fold_left (+) 0 lst in
  let cheapest = List.hd (List.sort compare lst) in

  let x = (b - sum) / cheapest in

  print_endline (string_of_int (a + x))


open Scanf
open Printf

let ($) f x = f x
let scanIntlist n = let list = ref [] in
  for i = 1 to n do
    list := (scanf (if i < n then "%d " else "%d") (fun x -> x))::!list
  done; List.rev !list

let string2charlist s = let rec proc i res =
                          try proc (i+1) $ s.[i]::res
                          with Invalid_argument _ -> res
  in List.rev $ proc 0 []

let minInt l = let rec proc l res = match l with
      [] -> res
    | x::xs -> if x < res then proc xs x else proc xs res
  in if l == [] then raise $ Failure "null list" else proc l max_int

let maxInt l = let rec proc l res = match l with
      [] -> res
    | x::xs -> if x > res then proc xs x else proc xs res
  in if l == [] then raise $ Failure "null list" else proc l min_int

let rec listSum = function
    [] -> 0
  | x::xs -> x+listSum xs;;

let rec quick_sort = function
    ([] | [_]) as l -> l
  | pivot :: rest ->
     let rec partition left right = function
	 [] -> (quick_sort left) @ (pivot :: quick_sort right)
       | y :: ys -> if pivot < y then partition left (y :: right) ys
                    else partition (y :: left) right ys
     in partition [] [] rest

let calc a b c x y = let p1 = a*x + b*y in
  let p2 = if x < y then c*2*x + b*(y-x) else c*2*y + a*(x-y) in
  let p3 = if x < y then c*2*y else c*2*x in
  minInt [p1;p2;p3];;

scanf "%d %d %d %d %d" $ fun a b c x y -> print_int $ calc a b c x y;;

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


let () =
  let open Int64 in
  let len, b = Scanf.scanf "%d %Ld\n" (fun a b -> a, b) in

  let arr = Array.make len (0L,0L) in
  for i = 0 to (len-1) do
    let c = Scanf.scanf "%Ld %Ld\n" (fun a b -> a, b) in
    Array.set arr i c
  done;

  let arr_l = Array.make len (0L,0L) in
  let arr_r = Array.make len (0L,0L) in
  let arr_l2 = Array.make len (0L,0L) in
  let arr_r2 = Array.make len (0L,0L) in

  let t = ref (0L,0L) in
  for i = 0 to (len-1) do
    let distance = fst (Array.get arr i) in

    let cal = Int64.add (snd (Array.get arr i))
        ( if (i=0) then 0L else (snd (Array.get arr_l (i-1)))) in

    let d_sub = if (i=0) then 0L else (fst (Array.get arr_l (i-1))) in
    let d_sub = Int64.sub distance d_sub in
    let cal = Int64.sub cal d_sub in

    let tt = (distance, cal) in
    if (cal > (snd !t))
    then (
      t := tt
    )
    else ();
    Array.set arr_l i tt;
    Array.set arr_l2 i !t;
  done;

  let t = ref (0L,0L) in
  for i = 0 to (len-1) do
    let i = len-1-i in
    let distance = Int64.sub b (fst (Array.get arr i)) in
    let cal = Int64.add (snd (Array.get arr i))
        (if (i=len-1) then 0L else (snd (Array.get arr_r (i+1))) ) in

    let d_sub = if (i=len-1) then 0L else (fst (Array.get arr_r (i+1))) in
    let d_sub = Int64.sub distance d_sub in
    let cal = Int64.sub cal d_sub in

    let tt = (distance, cal) in
    if (cal > (snd !t))
    then (
      t := tt
    )
    else ();
    Array.set arr_r i tt;
    Array.set arr_r2 i !t;
  done;

  let t = ref (0L,0L) in
  for i = 0 to (len-1) do
    let j = if (i=len-1) then 0 else i+1 in

    let d_l = fst (Array.get arr_l2 i) in
    let d_r =
      if (j = 0) then
        0L
      else
        fst (Array.get arr_r2 j) in
    let d_sub = if d_l > d_r then d_r else d_l in

    let cal_l = snd (Array.get arr_l2 i) in
    let cal_r =
      if (j = 0) then
        0L
      else
        snd (Array.get arr_r2 j) in
    let cal = Int64.sub (Int64.add cal_l cal_r) d_sub in

    if (cal > (snd !t))
    then (
      let tt = (0L, cal) in
      t := tt
    )
    else ();
  done;

  Printf.printf "%Ld" (snd !t);

Score : 500 points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is C meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are N pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the i-th sushi is placed, is x_i meters. Also, the i-th sushi has a nutritive value of v_i kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes 1 kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

1 ≤ N ≤ 10^5

2 ≤ C ≤ 10^{14}

1 ≤ x_1 < x_2 < ... < x_N < C

1 ≤ v_i ≤ 10^9

All values in input are integers.

Subscores

300 points will be awarded for passing the test set satisfying N ≤ 100.

Input

Input is given from Standard Input in the following format:

N C
x_1 v_1
x_2 v_2
:
x_N v_N

Output

If Nakahashi can take in at most c kilocalories on balance before he leaves the restaurant, print c.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of 20 meters. If he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks seven more meters clockwise, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 9 kilocalories, thus he can take in 191 kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of 80 kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of 120 kilocalories. If he leaves now, the total nutrition taken in is 200 kilocalories, and the total energy consumed is 8 kilocalories, thus he can take in 192 kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a 32-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.


open Scanf
open Printf

let cats_and_dogs a b x =
  if a > x then "NO"
  else if a + b < x then "NO"
  else "YES"

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

Score : 100 points

Problem Statement

There are a total of A + B cats and dogs.
Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs.

Determine if it is possible that there are exactly X cats among these A + B animals.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

1 \leq X \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B X

Output

If it is possible that there are exactly X cats, print YES; if it is impossible, print NO.

Sample Input 1

3 5 4

Sample Output 1

YES

If there are one cat and four dogs among the B = 5 animals, there are X = 4 cats in total.

Sample Input 2

2 2 6

Sample Output 2

NO

Even if all of the B = 2 animals are cats, there are less than X = 6 cats in total.

Sample Input 3

5 3 2

Sample Output 3

NO

Even if all of the B = 3 animals are dogs, there are more than X = 2 cats in total.


open Printf
open Scanf

let solve a b x =
  if a <= x && x <= a + b then "YES" else "NO"

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


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


Scanf.(Array.(scanf" %d %d %d"@@fun n m x->
	let l,r = init m (fun _->scanf" %d"@@fun v->v)
	|> fold_left(fun (l,r) v->if v<x then (l+1,r) else (l,r+1))(0,0)
	in print_int @@ min l r));;

Score : 200 points

Problem Statement

There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right.

Initially, you are in Square X.
You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N.
However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1.
It is guaranteed that there is no toll gate in Square 0, Square X and Square N.

Find the minimum cost incurred before reaching the goal.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

1 \leq X \leq N - 1

1 \leq A_1 < A_2 < ... < A_M \leq N

A_i \neq X

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M X
A_1 A_2 ... A_M

Output

Print the minimum cost incurred before reaching the goal.

Sample Input 1

5 3 3
1 2 4

Sample Output 1

1

The optimal solution is as follows:

First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.

Then, travel from Square 4 to Square 5. This time, no cost is incurred.

Now, we are in Square 5 and we have reached the goal.

In this case, the total cost incurred is 1.

Sample Input 2

7 3 2
4 5 6

Sample Output 2

0

We may be able to reach the goal at no cost.

Sample Input 3

10 7 5
1 2 3 4 6 8 9

Sample Output 3

3