(* unihernandez22
 * https://atcoder.jp/contests/abc054/tasks/abc054_b
 * implementation
 * *)

Scanf.scanf "%d %d\n" @@ fun n m ->
    let a = Array.init n @@ fun _ -> String.trim @@ read_line() in
    let b = Array.init m @@ fun _ -> String.trim @@ read_line() in

    let valid = ref true in
    let ans = ref "No\n" in
    for i = 0 to n-m do
        for j = 0 to n-m do
            valid := true;
            for y = 0 to m-1 do
                if not (String.sub a.(i+y) j m = b.(y)) then
                    valid := false;
            done;
            if !valid then
                ans := "Yes\n";
        done;
    done;
    print_string !ans;;

Score : 200 points

Problem Statement

You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size 1×1.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image A is given as N strings A_1,...,A_N.

The j-th character in the string A_i corresponds to the pixel at the i-th row and j-th column of the image A (1≦i,j≦N).

Similarly, the template image B is given as M strings B_1,...,B_M.

The j-th character in the string B_i corresponds to the pixel at the i-th row and j-th column of the template image B (1≦i,j≦M).

Determine whether the template image B is contained in the image A when only parallel shifts can be applied to the images.

Constraints

1≦M≦N≦50

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

B_i is a string of length M consisting of # and ..

Input

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

N M
A_1
A_2
:
A_N
B_1
B_2
:
B_M

Output

Print Yes if the template image B is contained in the image A. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image B is identical to the upper-left 2 × 2 subimage and the lower-right 2 × 2 subimage of A. Thus, the output should be Yes.

Sample Input 2

4 1
....
....
....
....
#

Sample Output 2

No

The template image B, composed of a black pixel, is not contained in the image A composed of white pixels.


let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m)
let a = Array.init n (fun i -> read_line ())
let b = Array.init m (fun i -> read_line ())

let c = n - m + 1

let rec ans i j k l =
  if i = c then "No"
  else if j = c then ans (i + 1) 0 0 0
  else if k = m then "Yes"
  else if l = m then ans i j (k + 1) 0
  else if a.(i + k).[j + l] <> b.(k).[l] then ans i (j + 1) 0 0
  else ans i j k (l + 1)

let () = print_endline (ans 0 0 0 0)

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

Submitted source-code file size, in bytes.

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

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


let scan_words () = Scanf.scanf "%d %d\n" (fun a b -> (a, b))
module Is = Set.Make (struct type t = int let compare = compare end)
let h = Hashtbl.create 8
let n, m = scan_words ()

let rec solve now set =
  if Is.mem now set then 0
  else if Is.cardinal set = (n - 1) then 1
  else match Hashtbl.find_all h now with
    | [] -> 0
    | ls ->
      List.fold_left (fun acc pos -> acc + solve pos (Is.add now set)) 0 ls

let () =
  for i = 1 to m do
    let a, b = scan_words () in
    Hashtbl.add h a b ; Hashtbl.add h b a
  done ;
  Printf.printf "%d\n" (solve 1 Is.empty)

Score : 300 points

Problem Statement

You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

How many different paths start from vertex 1 and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex 1.

Figure 4: another example of a path that does not satisfy the condition

Constraints

2≦N≦8

0≦M≦N(N-1)/2

1≦a_i<b_i≦N

The given graph contains neither self-loops nor double edges.

Input

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

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

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

Sample Output 2

1

This test case is the same as the one described in the problem statement.


Scanf.scanf "%d %d %d" (fun n ma mb ->
    let module M = Map.Make (struct type t = int * int let compare = compare end) in
    let map =
        let rec loop i map =
            if i = n then map else
                let map =
                    Scanf.scanf " %d %d %d" (fun a b c ->
                        M.fold (fun (ka, kb) v next ->
                            let key = (ka + a, kb + b) in
                            M.add key (min (v + c) (try M.find key next with _ -> max_int)) next
                        ) map map
                    )
                in
                loop (i + 1) map
        in
        loop 0 (M.add (0, 0) 0 M.empty)
    in
    let rec loop i mi =
        if i = 500 then (if mi = max_int then -1 else mi) else
            let key = (ma * i, mb * i) in
            let mi = min mi (try M.find key map with _ -> max_int) in
            loop (i + 1) mi
    in
    loop 1 max_int |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

Dolphin is planning to generate a small amount of a certain chemical substance C.

In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b.

He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmacy.

The pharmacy sells N kinds of chemicals. For each kind of chemical, there is exactly one package of that chemical in stock.

The package of chemical i contains a_i grams of the substance A and b_i grams of the substance B, and is sold for c_i yen (the currency of Japan).

Dolphin will purchase some of these packages. For some reason, he must use all contents of the purchased packages to generate the substance C.

Find the minimum amount of money required to generate the substance C.

If it is not possible to generate the substance C by purchasing any combination of packages at the pharmacy, report that fact.

Constraints

1≦N≦40

1≦a_i,b_i≦10

1≦c_i≦100

1≦M_a,M_b≦10

gcd(M_a,M_b)=1

a_i, b_i, c_i, M_a and M_b are integers.

Input

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

N M_a M_b
a_1 b_1 c_1
a_2 b_2 c_2
:
a_N b_N c_N

Output

Print the minimum amount of money required to generate the substance C. If it is not possible to generate the substance C, print -1 instead.

Sample Input 1

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

Sample Output 1

3

The amount of money spent will be minimized by purchasing the packages of chemicals 1 and 2.

In this case, the mixture of the purchased chemicals will contain 3 grams of the substance A and 3 grams of the substance B, which are in the desired ratio: 3:3=1:1.

The total price of these packages is 3 yen.

Sample Input 2

1 1 10
10 10 10

Sample Output 2

-1

The ratio 1:10 of the two substances A and B cannot be satisfied by purchasing any combination of the packages. Thus, the output should be -1.


Scanf.scanf "%d %d %d" (fun n ma mb ->
    let module M = Map.Make (struct type t = int * int let compare = compare end) in
    let map =
        let rec loop i map =
            if i = n then map else
                let map =
                    Scanf.scanf " %d %d %d" (fun a b c ->
                        M.fold (fun (ka, kb) v next ->
                            let key = (ka + a, kb + b) in
                            M.add key (min (v + c) (try M.find key next with _ -> max_int)) next
                        ) map map
                    )
                in
                loop (i + 1) map
        in
        loop 0 (M.add (0, 0) 0 M.empty)
    in
    let rec loop i =
        if i = 500 then (-1) else
            let key = (ma * i, mb * i) in
            if M.mem key map then M.find key map else loop (i + 1)
    in
    loop 1 |> Printf.printf "%d\n"
)


let inf = 1 lsl 40
let n, ma, mb = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let abcs = Array.init n @@ fun _ -> Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let dp = Array.(init (n + 1) @@ fun _ -> make_matrix 411 411 inf)
let a, b, c = abcs.(0)
let ans = ref inf
let _ = dp.(0).(0).(0) <- 0; for i = 0 to n - 1 do let a, b, c = abcs.(i) in for j = 0 to 400 do for k = 0 to 400 do dp.(i + 1).(j).(k) <- min dp.(i + 1).(j).(k) dp.(i).(j).(k); dp.(i + 1).(j + a).(k + b) <- min dp.(i + 1).(j + a).(k + b) (dp.(i).(j).(k) + c) done done done; Array.(iter (iteri (fun i -> (iter (fun j -> if i > 0 && j > 0 && i * mb = j * ma then ans := min !ans dp.(n).(i).(j))))) dp); Printf.printf "%d\n" @@ if !ans = inf then -1 else !ans


(* O(n) *)
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let _ = print_endline @@ if Array.fold_left (fun acc a -> (acc + a) mod 2) 0 a_s = 0 then "YES" else "NO"

Score : 300 points

Problem Statement

There are N integers written on a blackboard. The i-th integer is A_i.

Takahashi will repeatedly perform the following operation on these numbers:

Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.

Then, write a new integer on the blackboard that is equal to the sum of those integers, A_i+A_j.

Determine whether it is possible to have only one integer on the blackboard.

Constraints

2 ≦ N ≦ 10^5

1 ≦ A_i ≦ 10^9

A_i is an integer.

Input

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

N
A_1 A_2 … A_N

Output

If it is possible to have only one integer on the blackboard, print YES. Otherwise, print NO.

Sample Input 1

3
1 2 3

Sample Output 1

YES

It is possible to have only one integer on the blackboard, as follows:

Erase 1 and 3 from the blackboard, then write 4. Now, there are two integers on the blackboard: 2 and 4.

Erase 2 and 4 from the blackboard, then write 6. Now, there is only one integer on the blackboard: 6.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

NO


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

let () =
  let n = get_int ()
  in let ls = input_int_array n |> Array.to_list
  in
  List.filter (fun v -> v mod 2 = 1) ls
  |> List.length
  |> (fun v -> if v mod 2 = 0 then "YES" else "NO")
  |> print_endline


print_endline @@ if read_int () < 1200 then "ABC" else "ARC"

Score : 100 points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than 1200, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, x. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

1 ≦ x ≦ 3{,}000

x is an integer.

Input

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

x

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than 1200, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than 1200, thus the output should be ARC.


print_endline (if read_int () < 1200 then "ABC" else "ARC")


let k = List.(Array.(init (read_int ()) (fun _ -> Scanf.scanf " %d" (+) 0) |> to_list) |> sort_uniq (-) |> length)
let _ = Printf.printf "%d\n" @@ k - (k + 1) mod 2

Score : 400 points

Problem Statement

Snuke has decided to play a game using cards.
He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written.

He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of remaining cards. Here, N is odd, which guarantees that at least one card can be kept.

Operation: Take out three arbitrary cards from the deck. Among those three cards, eat two: one with the largest value, and another with the smallest value. Then, return the remaining one card to the deck.

Constraints

3 ≦ N ≦ 10^{5}

N is odd.

1 ≦ A_i ≦ 10^{5}

A_i is an integer.

Input

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

N
A_1 A_2 A_3 ... A_{N}

Output

Print the answer.

Sample Input 1

5
1 2 1 3 7

Sample Output 1

3

One optimal solution is to perform the operation once, taking out two cards with 1 and one card with 2. One card with 1 and another with 2 will be eaten, and the remaining card with 1 will be returned to deck. Then, the values written on the remaining cards in the deck will be pairwise distinct: 1, 3 and 7.

Sample Input 2

15
1 3 5 2 1 3 2 8 8 6 2 6 11 1 1

Sample Output 2

7


let cs, a_s = Array.(make 100001 0, init (read_int ()) @@ fun _ -> Scanf.scanf " %d" (+) 0)
let _ = Array.(iter (fun a -> cs.(a) <- cs.(a) + 1) a_s; List.(length @@ sort_uniq (-) @@ to_list a_s) - if (fold_left (fun s c -> if c > 0 && c mod 2 = 0 then s + 1 else s) 0 cs) mod 2 = 1 then 1 else 0) |> Printf.printf "%d\n"


let n = read_int () in
let c = (n / 11) * 2 in
let n = n mod 11 in
Printf.printf "%d\n" @@
    if n = 0 then c else if n <= 6 then c + 1 else c + 2

Score : 300 points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die 90° toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain y points where y is the number written in the side facing upward.

For example, let us consider the situation where the side showing 1 faces upward, the near side shows 5 and the right side shows 4, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing 3 will face upward.
Besides, the side showing 4 will face upward if the die is rotated toward the left, the side showing 2 will face upward if the die is rotated toward the front, and the side showing 5 will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least x points in total.

Constraints

1 ≦ x ≦ 10^{15}

x is an integer.

Input

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

x

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801


let () = Scanf.scanf "%d" (fun x ->
  Printf.printf "%d\n" @@ (x + 4) / 11 * 2 + min 1 ((x + 4) mod 11))


let solve n = max ((n / 11) * 2 + (if n mod 11 = 0 then 0 else 1)) 2

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


let n = Scanf.scanf " %d" (+) 0
let ab_s = Array.to_list @@ Array.init n @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let f a b = if a mod b = 0 then 0 else (a + b - 1) / b * b - a
let _ = List.fold_left (fun c (a, b) -> c + f (a + c) b) 0 @@ List.rev ab_s |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

There are an integer sequence A_1,...,A_N consisting of N terms, and N buttons.
When the i-th (1 ≦ i ≦ N) button is pressed, the values of the i terms from the first through the i-th are all incremented by 1.

There is also another integer sequence B_1,...,B_N. Takahashi will push the buttons some number of times so that for every i, A_i will be a multiple of B_i.

Find the minimum number of times Takahashi will press the buttons.

Constraints

All input values are integers.

1 ≦ N ≦ 10^5

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

1 ≦ B_i ≦ 10^9(1 ≦ i ≦ N)

Input

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

N
A_1 B_1
:
A_N B_N

Output

Print an integer representing the minimum number of times Takahashi will press the buttons.

Sample Input 1

3
3 5
2 7
9 4

Sample Output 1

7

Press the first button twice, the second button twice and the third button three times.

Sample Input 2

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

Sample Output 2

22


let n = Scanf.scanf " %d" (+) 0
let ab_s = Array.init n @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let f a b = if a < b then b - a else if a mod b = 0 then 0 else (a + b - 1) / b * b - a
let ans = ref 0
let _ = for i = n - 1 downto 0 do ans := !ans + f (fst ab_s.(i) + !ans) (snd ab_s.(i)) done; Printf.printf "%d\n" !ans


Scanf.scanf "%d" @@ fun n ->
  let ab = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x,y)) in
  let ab = Array.init n (fun i -> ab.(n-1-i)) in
  Array.fold_left (fun (s,d) (x,y) ->
    let p = ((x+d+y-1)/y*y - (x+d)) mod y in (s+p, d+p)) (0,0) ab
  |> fst |> Printf.printf "%d\n"


let rec make_tournament losers winner =
  List.map (make_tournament losers) (losers winner)
    |> List.sort compare
    |> List.fold_left (fun d d' -> 1 + max d d') 0

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init (n - 1) (fun _ -> Scanf.scanf "%d\n" (fun a -> a)) in
  let losers = Array.make n [] in
  Array.iteri (fun i a ->
    losers.(a - 1) <- i + 1 :: losers.(a - 1)) as_;
  Printf.printf "%d\n" (make_tournament (fun i -> losers.(i)) 0)

Score : 800 points

Problem Statement

N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament.
For some reasons, the tournament may not be "fair" for all the contestants.
That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The structure of the tournament is formally described at the end of this statement.

After each match, there were always one winner and one loser. The last contestant standing was declared the champion.

Figure: an example of a tournament

For convenience, the contestants were numbered 1 through N. The contestant numbered 1 was the champion, and the contestant numbered i(2 ≦ i ≦ N) was defeated in a match against the contestant numbered a_i.

We will define the depth of the tournament as the maximum number of the matches that must be played in order to win the championship over all the contestants.

Find the minimum possible depth of the tournament.

The formal description of the structure of the tournament is as follows. In the i-th match, one of the following played against each other:

Two predetermined contestants

One predetermined contestant and the winner of the j-th match, where j(j<i) was predetermined

The winner of the j-th match and the winner of the k-th match, where j and k (j,k<i, j ≠ k) were predetermined

Such structure is valid structure of the tournament, if and only if no contestant who has already been defeated in a match will never play in a match, regardless of the outcome of the matches.

Constraints

2 ≦ N ≦ 10^5

1 ≦ a_i ≦ N(2 ≦ i ≦ N)

It is guaranteed that the input is consistent (that is, there exists at least one tournament that matches the given information).

Input

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

N
a_2
:
a_N

Output

Print the minimum possible depth of the tournament.

Sample Input 1

5
1
1
2
4

Sample Output 1

3

The following tournament and the result of the matches are consistent with the given information:

In the first match, contestants 4 and 5 played against each other, and contestant 4 won.

In the second match, contestants 2 and 4 played against each other, and contestant 2 won.

In the third match, contestants 1 and 3 played against each other, and contestant 1 won.

In the fourth match, contestants 1 and 2 played against each other, and contestant 1 won.

The depth of this tournament is 3, since contestant 5 must play three matches in order to win the championship.
There is no tournament with depth 2 or less that is consistent with the given information, thus the output should be 3.

Sample Input 2

7
1
2
1
3
1
4

Sample Output 2

3

Sample Input 3

4
4
4
1

Sample Output 3

3


Scanf.scanf "%d %d %d %d" (fun a b c d -> print_int (max (a * b) (c * d)))

Score : 100 points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B.
The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

1≤A≤10^4

1≤B≤10^4

1≤C≤10^4

1≤D≤10^4

Input

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

A B C D

Output

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of 3×5=15, and the second rectangle has an area of 2×7=14.
Thus, the output should be 15, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000


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


let (a,b,c,d) = Scanf.scanf "%d %d %d %d\n" (fun a b c d -> (a,b,c,d))
let str = if a*b = c*d then a*b else if a*b > c*d then a*b else c*d
let () = Printf.printf "%d\n" str


let n, s = Scanf.scanf " %d %s" @@ fun a b -> a, b
let ans, acc = ref 0, ref 0
let _ =
  String.iter (fun c -> if c = 'I' then incr acc else decr acc; ans := max !ans !acc) s;
  Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

You have an integer variable x.
Initially, x=0.

Some person gave you a string S of length N, and using the string you performed the following operation N times.
In the i-th operation, you incremented the value of x by 1 if S_i=I, and decremented the value of x by 1 if S_i=D.

Find the maximum value taken by x during the operations (including before the first operation, and after the last operation).

Constraints

1≤N≤100

|S|=N

No characters except I and D occur in S.

Input

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

N
S

Output

Print the maximum value taken by x during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of x becomes 1, 2, 1, 2 and 1, respectively. Thus, the output should be 2, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value x=0 is the maximum value taken by x, thus the output should be 0.


(* O(n^2) *)
let n = read_int ()
let is_prime n =
  if n <= 1 then false
  else
    let rec loop i =
      if i * i > n then true
      else if n mod i = 0 then false
      else loop @@ i + 1 in
    loop 2
let rec div_count n i = if n mod i <> 0 then 0 else 1 + div_count (n / i) i
let ans = ref 1
let _ =
  for i = 2 to n do
    if is_prime i then
      let c = ref 0 in
      for j = 2 to n do c := !c + div_count j i done;
      ans := !ans * (!c + 1) mod 1_000_000_007 done;
  Printf.printf "%d\n" @@ !ans

Score : 300 points

Problem Statement

You are given an integer N.
Find the number of the positive divisors of N!, modulo 10^9+7.

Constraints

1≤N≤10^3

Input

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

N

Output

Print the number of the positive divisors of N!, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

4

There are four divisors of 3! =6: 1, 2, 3 and 6. Thus, the output should be 4.

Sample Input 2

6

Sample Output 2

30

Sample Input 3

1000

Sample Output 3

972926972


let s = read_line ()
let f = String.sub s
let _ = Printf.printf "%s %s %s\n" (f 0 5) (f 6 7) (f 14 5)

Score : 100 points

Problem Statement

As a New Year's gift, Dolphin received a string s of length 19.

The string s has the following format: [five lowercase English letters],[seven lowercase English letters],[five lowercase English letters].

Dolphin wants to convert the comma-separated string s into a space-separated string.

Write a program to perform the conversion for him.

Constraints

The length of s is 19.

The sixth and fourteenth characters in s are ,.

The other characters in s are lowercase English letters.

Input

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

s

Output

Print the string after the conversion.

Sample Input 1

happy,newyear,enjoy

Sample Output 1

happy newyear enjoy

Replace all the commas in happy,newyear,enjoy with spaces to obtain happy newyear enjoy.

Sample Input 2

haiku,atcoder,tasks

Sample Output 2

haiku atcoder tasks

Sample Input 3

abcde,fghihgf,edcba

Sample Output 3

abcde fghihgf edcba


let (sx,sy,tx,ty) = Scanf.scanf "%d %d %d %d" (fun a b c d -> (a,b,c,d) )

let rec firstx x y tx ty list =
  if (x < tx) then firstx (x+1) y tx ty ('R'::list) else
    if (x > tx) then firstx (x-1) y tx ty ('L'::list) else list

let rec firsty x y tx ty list =
  if (y < ty) then firsty x (y+1) tx ty ('U'::list) else
    if (y > ty) then firsty x (y-1) tx ty ('D'::list) else list

let rec secondx x y tx ty list =
  if (x < (tx+1)) then firstx (x+1) y tx ty ('R'::list) else
    if (x > (tx+1)) then firstx (x-1) y tx ty ('L'::list) else list

let rec secondy x y tx ty list =
  if (y < ty) then firsty x (y+1) tx ty ('U'::list) else
    if (y > ty) then firsty x (y-1) tx ty ('D'::list) else list

let rec listinv = function
  | [] -> []
  | a :: rest ->
     match a with
     | 'R' -> 'L' :: listinv rest
     | 'L' -> 'R' :: listinv rest
     | 'U' -> 'D' :: listinv rest
     | 'D' -> 'U' :: listinv rest

let list1 = firstx sx sy tx ty []
let list2 = firsty sx sy tx ty []
let list12 = list1 @ list2
let list12' = listinv list12
let list3 = 'D' :: (firstx sx sy tx ty []) @ ['R']
let list4 = 'U' :: (firsty sx sy tx ty []) @ ['L']
let list34 = list3 @ list4
let list34' = listinv list34
let anslist = list12 @ list12' @ list34 @ list34'

let rec list_to_string : char list -> string = fun cl ->
   String.concat "" @@ List.map (String.make 1) cl

let ans = list_to_string anslist

let () = Printf.printf "%s\n" ans


Scanf.scanf "%d %d" (fun n m ->
    let module S = Set.Make (struct type t = int let compare = compare end) in
    let mat = Array.make_matrix n n (max_int / 1000, S.empty) in
    for i = 0 to n - 1 do mat.(i).(i) <- 0,S.empty done;
    for i = 0 to m - 1 do
        Scanf.scanf " %d %d %d" (fun a b c ->
            let a = a - 1 in let b = b - 1 in
            mat.(a).(b) <- c, S.singleton i;
            mat.(b).(a) <- c, S.singleton i;
        )
    done;
    for k = 0 to n - 1 do
        for i = 0 to n - 1 do
            for j = 0 to n - 1 do
                let d1, s1 = mat.(i).(j) in
                let d2, s2 = mat.(i).(k) in
                let d3, s3 = mat.(k).(j) in
                if d1 > d2 + d3 then mat.(i).(j) <- d2 + d3, S.union s2 s3
            done
        done
    done;
    let edge = Array.make m false in
    for i = 0 to n - 1 do
        for j = 0 to n - 1 do
            let _, s = mat.(i).(j) in
            S.iter (fun v -> edge.(v) <- true) s
        done
    done;
    Array.fold_left (fun acc v -> if v then acc else acc + 1) 0 edge |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

You are given an undirected connected weighted graph with N vertices and M edges that contains neither self-loops nor double edges.

The i-th (1≤i≤M) edge connects vertex a_i and vertex b_i with a distance of c_i.

Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M).

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

2≤N≤100

N-1≤M≤min(N(N-1)/2,1000)

1≤a_i,b_i≤N

1≤c_i≤1000

c_i is an integer.

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

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

N M
a_1 b_1 c_1
a_2 b_2 c_2
:
a_M b_M c_M

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex 1 to vertex 2 is: vertex 1 → vertex 2, with the length of 1.

The shortest path from vertex 1 to vertex 3 is: vertex 1 → vertex 3, with the length of 1.

The shortest path from vertex 2 to vertex 1 is: vertex 2 → vertex 1, with the length of 1.

The shortest path from vertex 2 to vertex 3 is: vertex 2 → vertex 1 → vertex 3, with the length of 2.

The shortest path from vertex 3 to vertex 1 is: vertex 3 → vertex 1, with the length of 1.

The shortest path from vertex 3 to vertex 2 is: vertex 3 → vertex 1 → vertex 2, with the length of 2.

Thus, the only edge that is not contained in any shortest path, is the edge of length 3 connecting vertex 2 and vertex 3, hence the output should be 1.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.


(* 座標圧縮 *)
module CoordComp
  (* 座標の型 *)
  (Coord : sig
    type t
    val compare : t -> t -> int
  end) :
sig
  val compress :
    (* 座標のリスト *)
    Coord.t list ->
    (* 座標の数，圧縮する関数と解凍する関数を返す *)
    int * (Coord.t -> int) * (int -> Coord.t)
end = struct
  module IntMap = Map.Make (struct
    type t = int
    let compare = compare
  end)
  module CoordMap = Map.Make (Coord)

  let compress cs =
    let (n, comp, decomp) =
      List.fold_left (fun (n, comp, decomp) c ->
        if CoordMap.mem c comp then (n, comp, decomp)
        else (n + 1, CoordMap.add c n comp, IntMap.add n c decomp))
      (0, CoordMap.empty, IntMap.empty) cs in
    (n, (fun c -> CoordMap.find c comp), (fun n -> IntMap.find n decomp))
end

(* 無限大の要素を付け足してトロピカル半環を作る *)
module WithInf
  (S : sig
    type t
    val zero : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  (* Noneで無限大を表す *)
  type t = S.t option
  val inf : t
  val zero : t
  val ( + ) : t -> t -> t
  val compare : t -> t -> int
end =
struct
  type t = S.t option
  let inf = None
  let zero = Some S.zero
  let ( + ) x y =
    match x, y with
    | None, _ -> None
    | _, None -> None
    | Some m, Some n -> Some (S.( + ) m n)
  let compare x y =
    match x, y with
    | None, None -> 0
    | None, _ -> 1
    | _, None -> -1
    | Some m, Some n -> S.compare m n
end

module WeightedDirectedGraph
  (Vertex : sig
    type t
    val compare : t -> t -> int
  end)
  (Weight : sig
    type t
    val zero : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  (* 配列版の実装 *)
  val raw_warshall_floyd :
    (* 頂点の数n *)
    int ->
    (* 辺のリスト *)
    (* 頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) list ->
    (* 辿り着けなければNoneを返す *)
    (int -> int -> Weight.t option)

  (* 座標圧縮により，頂点に様々な型を使えるようにしたバージョン *)
  val warshall_floyd :
    (* 辺のリスト *)
    (Vertex.t * Vertex.t * Weight.t) list ->
    (* 辿り着けなければNoneを返す *)
    (Vertex.t -> Vertex.t -> Weight.t option)
end =
struct
  module CC = CoordComp (Vertex)
  module Weight' = WithInf (Weight)

  let raw_warshall_floyd n es =
    (* 準備 *)
    (* Noneで無限を表す *)
    let d = Array.make_matrix n n Weight'.inf in
    List.iter (fun (u, v, c) -> d.(u).(v) <- Some c) es;
    for v = 0 to n - 1 do
      d.(v).(v) <- Weight'.zero
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
        for k = 0 to n - 1 do
          let open Weight' in
          (* d.(j).(i) + d.(i).(k) < d.(j).(k) *)
          if 0 < compare d.(j).(k) (d.(j).(i) + d.(i).(k)) then
            d.(j).(k) <- d.(j).(i) + d.(i).(k)
        done
      done
    done;
    fun u v -> try d.(u).(v) with _ -> Weight'.inf

  let warshall_floyd es =
    let (n, comp, _) =
      CC.compress @@
        List.concat @@
          List.map (fun (u, v, _) -> [u; v]) es in
    let d =
      raw_warshall_floyd n @@
        List.map (fun (u, v, c) -> (comp u, comp v, c)) es in
    fun u v ->
      try d (comp u) (comp v) with Not_found -> None
end

module Int = struct
  type t = int
  let zero = 0
  let ( + ) = ( + )
  let compare = compare
end

module G = WeightedDirectedGraph (Int) (Int)

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let abcs =
    Array.to_list @@
      Array.init m @@ fun _ ->
        Scanf.scanf "%d %d %d\n" @@ fun a b c -> a, b, c in
  let d = G.warshall_floyd (List.map (fun (a, b, c) -> (b, a, c)) abcs @ abcs) in
  List.filter (fun (a, b, c) -> let Some d = d a b in d < c) abcs
  |> List.length
  |> Printf.printf "%d\n"


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

let warshall_floyd ( + ) min n d =
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      for k = 0 to n - 1 do
        d.(j).(k) <- min d.(j).(k) (d.(j).(i) + d.(i).(k))
      done
    done
  done

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let es = Array.init m (fun _ ->
    Scanf.scanf "%d %d %d\n" (fun a b c -> (a, b, c))) in
  let dp = Array.make_matrix n n infinity in
  for i = 0 to n - 1 do
    dp.(i).(i) <- 0.
  done;
  Array.iter (fun (a, b, c) ->
    dp.(a - 1).(b - 1) <- float_of_int c;
    dp.(b - 1).(a - 1) <- float_of_int c) es;
  warshall_floyd ( +. ) min n dp;
  Array.to_list es
  |> List.filter (fun (a, b, c) ->
      dp.(a - 1).(b - 1) < float_of_int c)
  |> List.length
  |> Printf.printf "%d\n"


type 'a set =
  | Empty
  | Singleton of 'a
  | Union of 'a set * 'a set

let rec make_intset acc = function
  | Empty -> ()
  | Singleton x -> acc.(x) <- true
  | Union (s, t) -> make_intset acc s; make_intset acc t

let warshall_floyd ( + ) min n d =
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      for k = 0 to n - 1 do
        d.(j).(k) <- min d.(j).(k) (d.(j).(i) + d.(i).(k))
      done
    done
  done

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let dp = Array.make_matrix n n (infinity, Empty) in
  for i = 0 to n - 1 do
    dp.(i).(i) <- (0., Empty)
  done;
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d %d\n" (fun a b c ->
      dp.(a - 1).(b - 1) <- (float_of_int c, Singleton i);
      dp.(b - 1).(a - 1) <- (float_of_int c, Singleton i))
  done;
  warshall_floyd
    (fun (d, es) (d', es') -> (d +. d', Union (es, es')))
    (fun (d, es) (d', es') ->
      match compare d d' with
      | -1 -> (d, es)
      | 0  -> (d, Union (es, es'))
      | 1  -> (d', es')) n dp;
  let bs = Array.make m false in
  Array.iter (Array.iter (fun (_, es) -> make_intset bs es)) dp;
  Array.to_list bs
  |> List.filter (fun b -> not b)
  |> List.length
  |> Printf.printf "%d\n"


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

let warshall_floyd ( + ) min n d =
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      for k = 0 to n - 1 do
        d.(j).(k) <- min d.(j).(k) (d.(j).(i) + d.(i).(k))
      done
    done
  done

let () =
  let n, m = Scanf.scanf "%d %d\n" (fun n m -> n, m) in
  let dp = Array.make_matrix n n (infinity, IntSet.empty) in
  for i = 0 to n - 1 do
    dp.(i).(i) <- (0., IntSet.empty)
  done;
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d %d\n" (fun a b c ->
      dp.(a - 1).(b - 1) <- (float_of_int c, IntSet.singleton i);
      dp.(b - 1).(a - 1) <- (float_of_int c, IntSet.singleton i))
  done;
  warshall_floyd
    (fun (d, es) (d', es') -> (d +. d', IntSet.union es es'))
    (fun (d, es) (d', es') ->
      match compare d d' with
      | -1 -> (d, es)
      | 0  -> (d, IntSet.union es es')
      | 1  -> (d', es')) n dp;
  Array.map (fun dp ->
    Array.map snd dp
    |> Array.fold_left IntSet.union IntSet.empty) dp
  |> Array.fold_left IntSet.union IntSet.empty
  |> IntSet.cardinal
  |> (fun n -> Printf.printf "%d\n" (m - n))


Scanf.scanf " %d %d" @@ fun x y -> List.fold_left (fun m (x, y, b) -> min m @@ if x <= y then y - x + b else m) max_int [x, y, 0; -x, y, 1; x, -y, 1; -x, -y, 2] |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

Snuke has a calculator. It has a display and two buttons.

Initially, the display shows an integer x.
Snuke wants to change this value into another integer y, by pressing the following two buttons some number of times in arbitrary order:

Button A: When pressed, the value on the display is incremented by 1.

Button B: When pressed, the sign of the value on the display is reversed.

Find the minimum number of times Snuke needs to press the buttons to achieve his objective.
It can be shown that the objective is always achievable regardless of the values of the integers x and y.

Constraints

x and y are integers.

|x|, |y| ≤ 10^9

x and y are different.

Input

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

x y

Output

Print the minimum number of times Snuke needs to press the buttons to achieve his objective.

Sample Input 1

10 20

Sample Output 1

10

Press button A ten times.

Sample Input 2

10 -10

Sample Output 2

1

Press button B once.

Sample Input 3

-10 -20

Sample Output 3

12

Press the buttons as follows:

Press button B once.

Press button A ten times.

Press button B once.


let x, y, d, z = Scanf.scanf " %d %d" @@ fun a b -> a, b, abs b - abs a, ref a
let c = if d < 0 then (z := -(abs x + d); if x < 0 then -d else -d + 1) else if d > 0 then (z := abs x + d; if x < 0 then d + 1 else d) else 0
let _ = Printf.printf "%d\n" @@ if !z = y then c else c + 1


Scanf.scanf "%d %c %d" (fun a op b -> print_int (if op = '+' then a+b else a-b))

Score : 100 points

Problem Statement

Joisino wants to evaluate the formula "A op B".
Here, A and B are integers, and the binary operator op is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

1≦A,B≦10^9

op is either + or -.

Input

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

A op B

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since 1 + 2 = 3, the output should be 3.

Sample Input 2

5 - 7

Sample Output 2

-2


Scanf.scanf "%d" (fun n ->
    let t = Array.init n (fun _ -> Scanf.scanf " %d" (fun t -> t)) in
    let sum = Array.fold_left (+) 0 t in
    Scanf.scanf " %d" (fun m ->
        for i = 1 to m do
            Scanf.scanf " %d %d" (fun p x ->
                let p = p - 1 in
                Printf.printf "%d\n" @@ sum + x - t.(p)
            )
        done
    )
)

Score : 200 points

Problem Statement

Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are N problems, numbered 1 through N.
Joisino knows that it takes her T_i seconds to solve problem i(1≦i≦N).

Also, there are M kinds of drinks offered to the contestants, numbered 1 through M.
If Joisino takes drink i(1≦i≦M), her brain will be stimulated and the time it takes for her to solve problem P_i will become X_i seconds.
It does not affect the time to solve the other problems.

A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink.
Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems.
Your task is to write a program to calculate it instead of her.

Constraints

All input values are integers.

1≦N≦100

1≦T_i≦10^5

1≦M≦100

1≦P_i≦N

1≦X_i≦10^5

Input

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

N
T_1 T_2 ... T_N
M
P_1 X_1
P_2 X_2
:
P_M X_M

Output

For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line.

Sample Input 1

3
2 1 4
2
1 1
2 3

Sample Output 1

6
9

If Joisino takes drink 1, the time it takes her to solve each problem will be 1, 1 and 4 seconds, respectively, totaling 6 seconds.

If Joisino takes drink 2, the time it takes her to solve each problem will be 2, 3 and 4 seconds, respectively, totaling 9 seconds.

Sample Input 2

5
7 2 3 8 5
3
4 2
1 7
4 13

Sample Output 2

19
25
30


open Scanf
let () =
  let xs = scanf " %d" (fun n -> Array.init n (fun _ -> scanf " %d" (fun t -> t))) in
  let total = Array.fold_left (+) 0 xs in
  scanf " %d" (fun m -> Array.init m (fun _ -> scanf " %d %d" (fun p u -> p, u)))
  |> Array.iter (fun (p, u) -> Printf.printf "%d\n" (total + (u - xs.(p-1))))


let n = read_int ()
let cs = Array.make n 0
let rec f n a = if n <= 0 then a else f (n - 1) (2 * a mod 1000000007)
let _ = for i = 1 to n do Scanf.scanf " %d" @@ fun a -> cs.(a / 2) <- cs.(a / 2) + 1 done; for i = 0 to n / 2 + n mod 2 - 1 do if i = 0 && cs.(i) <> 2 - n mod 2 || i > 0 && cs.(i) <> 2 then (print_endline "0"; exit 0) done; Printf.printf "%d\n" @@ f (n / 2) 1

Score : 300 points

Problem Statement

There are N people, conveniently numbered 1 through N.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person i is A_i.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo 10^9+7.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print 0.

Constraints

1≦N≦10^5

0≦A_i≦N-1

Input

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

N
A_1 A_2 ... A_N

Output

Print the number of the possible orders in which they were standing, modulo 10^9+7.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

2,1,4,5,3

2,5,4,1,3

3,1,4,5,2

3,5,4,1,2

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is 0.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


print_endline @@ if String.contains "aeiou" (read_line ()).[0] then "vowel" else "consonant"

Score : 100 points

Problem Statement

Given a lowercase English letter c, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

c is a lowercase English letter.

Input

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

c

Output

If c is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant


let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let css = Array.init h @@ fun _ ->
    Scanf.scanf "%s\n" @@ fun cs -> cs in
  Array.iter (fun cs ->
    print_endline cs;
    print_endline cs) css


let read h =
	let rec f img = function
		| 0 -> img
		| n ->
			let line = read_line () in
			f (line::line::img) (n - 1)
	in f [] h |> List.rev

let rec print = function
	| [] -> ()
	| x::xs -> print_string x;print_newline ();print xs

let _ =
	Scanf.scanf "%d %d" (fun h w -> read h) |> print


module M = Map.Make(struct type t = int * int let compare = compare end)
let inc k m = try M.add k (1 + M.find k m) m with Not_found -> M.add k 1 m

let init n = Array.make n (-1)
let rec find x p =
  if p.(x) < 0 then x
  else let x' = find p.(x) p in p.(x) <- x'; x'
let unite x y p =
  let x', y' = find x p, find y p in
  if x' = y' then () else begin
    if p.(x') < p.(y') then begin
      p.(x') <- p.(x') + p.(y'); p.(y') <- x';
    end else begin
      p.(y') <- p.(x') + p.(y'); p.(x') <- y';
    end
  end
let size x p = - p.(find x p)

let () =
  Scanf.scanf "%d %d %d" @@ fun n k l ->
  let e0 = Array.init k (fun _ -> Scanf.scanf " %d %d" (fun x y -> x-1, y-1)) in
  let e1 = Array.init l (fun _ -> Scanf.scanf " %d %d" (fun x y -> x-1, y-1)) in
  let uf0, uf1, uf2  = init n, init n, init n in
  e0 |> Array.iter (fun (u, v) -> unite u v uf0);
  e1 |> Array.iter (fun (u, v) -> unite u v uf1);
  let g = Array.init n (fun i -> (find i uf0, find i uf1)) in
  let m = Array.fold_left (fun m (i, j) -> inc (i, j) m) M.empty g in
  g |> Array.iter (fun p -> M.find p m |> Printf.printf "%d ");
  print_newline ()

Score : 400 points

Problem Statement

There are N cities. There are also K roads and L railways, extending between the cities.
The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities.
No two roads connect the same pair of cities. Similarly, no two railways connect the same pair of cities.

We will say city A and B are connected by roads if city B is reachable from city A by traversing some number of roads. Here, any city is considered to be connected to itself by roads.
We will also define connectivity by railways similarly.

For each city, find the number of the cities connected to that city by both roads and railways.

Constraints

2 ≦ N ≦ 2*10^5

1 ≦ K, L≦ 10^5

1 ≦ p_i, q_i, r_i, s_i ≦ N

p_i < q_i

r_i < s_i

When i ≠ j, (p_i, q_i) ≠ (p_j, q_j)

When i ≠ j, (r_i, s_i) ≠ (r_j, s_j)

Input

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

N K L
p_1 q_1
:
p_K q_K
r_1 s_1
:
r_L s_L

Output

Print N integers. The i-th of them should represent the number of the cities connected to the i-th city by both roads and railways.

Sample Input 1

4 3 1
1 2
2 3
3 4
2 3

Sample Output 1

1 2 2 1

All the four cities are connected to each other by roads.

By railways, only the second and third cities are connected. Thus, the answers for the cities are 1, 2, 2 and 1, respectively.

Sample Input 2

4 2 2
1 2
2 3
1 4
2 3

Sample Output 2

1 2 2 1

Sample Input 3

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

Sample Output 3

1 1 2 1 2 2 2


Scanf.scanf "%s %s" @@ fun _ s -> Printf.printf "A%cC\n" s.[0]

Score : 100 points

Problem Statement

Snuke is going to open a contest named "AtCoder s Contest".
Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "AxC".
Here, x is the uppercase English letter at the beginning of s.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of s is between 1 and 100, inclusive.

The first character in s is an uppercase English letter.

The second and subsequent characters in s are lowercase English letters.

Input

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

AtCoder s Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC


let () =
  Scanf.scanf "AtCoder %s Contest"
    (fun s -> Printf.printf "A%cC\n" s.[0])


Scanf.scanf "%d %d %d" (fun a b x ->
    Printf.printf "%d\n" @@ (b / x) - ((a - 1) / x)
)

Score : 200 points

Problem Statement

You are given nonnegative integers a and b (a ≤ b), and a positive integer x.
Among the integers between a and b, inclusive, how many are divisible by x?

Constraints

0 ≤ a ≤ b ≤ 10^{18}

1 ≤ x ≤ 10^{18}

Input

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

a b x

Output

Print the number of the integers between a and b, inclusive, that are divisible by x.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between 4 and 8, inclusive, that are divisible by 2: 4, 6 and 8.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between 0 and 5, inclusive, that are divisible by 1: 0, 1, 2, 3, 4 and 5.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between 9 and 9, inclusive, that is divisible by 2.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.


let () = Scanf.scanf "%d %d %d" (fun a b x -> b / x - (a-1) / x) |> Printf.printf "%d\n"


let solve a b x =
	(b / x) - ((a - 1) / x)

let () =
	let [a; b; x] =
		read_line ()
		|> Str.split (Str.regexp " ")
		|> List.map int_of_string
	in
	solve a b x
	|> print_int
	|> print_newline


let ($) f g = fun x -> f (g x)

let n, x = Scanf.scanf "%d %d\n" (fun a b -> a, b)
let a = Str.split (Str.regexp " ") @@ read_line ()
      |> List.map int_of_string

let rec cutting l =
  let rec func cnt res = function
      [] -> (cnt, List.rev res)
    | hd :: rest ->
      let n = max 0 (hd-x) in
      func (cnt + n) ((min x hd)::res) rest
  in func 0 [] l

let checking (pre_ans, l) =
  let rec func cnt = function
      [] | [_] -> cnt
    | o::t::rest ->
        let n = max 0 (o+t - x) in
        func (cnt+n) ((max 0 (t-n)) :: rest)
  in
  pre_ans + func 0 l

let () =
  cutting a
  |> checking
  |> (print_endline $ string_of_int)

Score : 300 points

Problem Statement

There are N boxes arranged in a row.
Initially, the i-th box from the left contains a_i candies.

Snuke can perform the following operation any number of times:

Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

Any two neighboring boxes contain at most x candies in total.

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

Constraints

2 ≤ N ≤ 10^5

0 ≤ a_i ≤ 10^9

0 ≤ x ≤ 10^9

Input

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

N x
a_1 a_2 ... a_N

Output

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

Sample Input 1

3 3
2 2 2

Sample Output 1

1

Eat one candy in the second box.
Then, the number of candies in each box becomes (2, 1, 2).

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11

For example, eat six candies in the second box, two in the fourth box, and three in the sixth box.
Then, the number of candies in each box becomes (1, 0, 1, 0, 0, 1).

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0

The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10

All the candies need to be eaten.


let () =
  let s = Scanf.scanf "%s " (fun a -> a) in
  let l = Batteries.String.to_list s in

  let t1 = Batteries.List.filteri (fun i x -> i mod 2 = 0) l in
  let t2 = Batteries.List.filteri (fun i x -> i mod 2 <> 0) l in

  Printf.printf "%s\n" @@
  if (
    (
      List.sort_uniq compare t1 |> List.length = 1
    )
    &&
      (
        List.sort_uniq compare t2 |> List.length = 1
      )
  )
  then "Second"
  else if List.length l mod 2 = 0 then "Second" else "First"

Score : 500 points

Problem Statement

There is a string s of length 3 or greater.
No two neighboring characters in s are equal.

Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:

Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.

The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.

Constraints

3 ≤ |s| ≤ 10^5

s consists of lowercase English letters.

No two neighboring characters in s are equal.

Input

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

s

Output

If Takahashi will win, print First. If Aoki will win, print Second.

Sample Input 1

aba

Sample Output 1

Second

Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring.

Sample Input 2

abc

Sample Output 2

First

When Takahashi removes b from s, it becomes ac.
Then, Aoki cannot perform the operation, since there is no character in s, excluding both ends.

Sample Input 3

abcab

Sample Output 3

First


let h, w = Scanf.scanf " %d %d" @@ fun a b -> a, b
let sss = Array.init h @@ fun _ -> Array.init w @@ fun _ -> Scanf.scanf " %s" @@ fun s -> s
let _ =
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do if sss.(i).(j) = "snuke" then Printf.printf "%c%d\n" (Char.chr @@ Char.code 'A' + j) @@ i + 1 done done

Score : 100 points

Problem Statement

There is a grid with H rows and W columns.

The square at the i-th row and j-th column contains a string S_{i,j} of length 5.

The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from A through the W-th letter of the alphabet.

Exactly one of the squares in the grid contains the string snuke. Find this square and report its location.

For example, the square at the 6-th row and 8-th column should be reported as H6.

Constraints

1≦H, W≦26

The length of S_{i,j} is 5.

S_{i,j} consists of lowercase English letters (a-z).

Exactly one of the given strings is equal to snuke.

Input

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

H W
S_{1,1} S_{1,2} ... S_{1,W}
S_{2,1} S_{2,2} ... S_{2,W}
:
S_{H,1} S_{H,2} ... S_{H,W}

Output

Print the labels of the row and the column of the square containing the string snuke, with no space inbetween.

Sample Input 1

15 10
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snuke snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake

Sample Output 1

H6

Sample Input 2

1 1
snuke

Sample Output 2

A1


let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let xs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun x -> x in
  let count = Array.make m 0 in
  let pairs = Array.make m 0 in
  begin
    let elt = Array.make 100001 false in
    Array.iter (fun x ->
      (if elt.(x) then pairs.(x mod m) <- 1 + pairs.(x mod m));
      elt.(x) <- not elt.(x);
      count.(x mod m) <- 1 + count.(x mod m)) xs
  end;
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.init m @@ fun i ->
    if m - i < i then 0
    else if i = 0 || m - i = i then count.(i) / 2
    else begin
      let x = min count.(i) count.(m - i) in
      x
      + min (count.(i) - x) (2 * pairs.(i)) / 2
      + min (count.(m - i) - x) (2 * pairs.(m - i)) / 2
    end

Score : 700 points

Problem Statement

Takahashi is playing with N cards.

The i-th card has an integer X_i on it.

Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:

The integers on the two cards are the same.

The sum of the integers on the two cards is a multiple of M.

Find the maximum number of pairs that can be created.

Note that a card cannot be used in more than one pair.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦X_i≦10^5

Input

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

N M
X_1 X_2 ... X_N

Output

Print the maximum number of pairs that can be created.

Sample Input 1

7 5
3 1 4 1 5 9 2

Sample Output 1

3

Three pairs (3,2), (1,4) and (1,9) can be created.

It is possible to create pairs (3,2) and (1,1), but the number of pairs is not maximized with this.

Sample Input 2

15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99

Sample Output 2

6


Scanf.(scanf " %d %d" @@ fun h w -> print_endline @@ if Array.(fold_left (+) 0 @@ init (h * w) @@ fun _ -> scanf " %c" @@ fun a -> if a = '#' then 1 else 0) = h + w - 1 then "Possible" else "Impossible")

Score : 200 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).

You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is # if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is .. Please determine whether it is possible that Shik only uses right and down moves in all steps.

Constraints

2 \leq H, W \leq 8

a_{i,j} is either # or ..

There exists a valid sequence of moves for Shik to generate the map a.

Input

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

H W
a_{11}a_{12}...a_{1W}
:
a_{H1}a_{H2}...a_{HW}

Output

If it is possible that Shik only uses right and down moves, print Possible. Otherwise, print Impossible.

Sample Input 1

4 5
##...
.##..
..##.
...##

Sample Output 1

Possible

The matrix can be generated by a 7-move sequence: right, down, right, down, right, down, and right.

Sample Input 2

5 3
###
..#
###
#..
###

Sample Output 2

Impossible

Sample Input 3

4 5
##...
.###.
.###.
...##

Sample Output 3

Impossible


let h, w = Scanf.scanf "%d %d\n" (fun x y -> x, y)

let rec read_char acc = function
  | 0 -> acc
  | k -> read_char (Scanf.scanf " %c" (fun x -> if x = '#' then (acc + 1) else acc)) (k-1)

let () = print_string (if (read_char 0 (h*w)) = h+w-1 then "Possible" else "Impossible")


let () =
	let a,b,c = Scanf.scanf "%d %d %d\n" (fun a b c -> a,b,c) in
    Printf.printf (if a+b=c || a+c=b || b+c=a then "Yes" else "No")

Score : 100 points

Problem Statement

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

1 ≦ a, b, c ≦ 100

Input

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

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.

Sample Input 1

10 30 20

Sample Output 1

Yes

Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.

Sample Input 2

30 30 100

Sample Output 2

No

In this case, the student who gets the pack with 100 candies always has more candies than the other.

Note that every pack must be given to one of them.

Sample Input 3

56 25 31

Sample Output 3

Yes


let () =
	let a,b,c = Scanf.scanf "%d %d %d\n" (fun a b c -> a,b,c) in
    Printf.printf (if (a+b+c) mod 2 = 0 then "Yes" else "No")


let () = Scanf.scanf "%d %d %d" (fun a b c ->
  let m = max a (max b c) in if a+b+c-m = m then "Yes" else "No")
|> print_endline


let () = Scanf.scanf "%d %d %d" (fun a b c ->
  if a + b = c || b + c = a || c + a = b then print_endline "Yes"
  else print_endline "No")


let n = read_int ()
let s = read_line ()
let t = read_line ()
let f m = Printf.printf "%d\n" @@ 2 * n - m; exit 0
let _ = for l = n downto 1 do if String.(sub s (n - l) l = sub t 0 l) then f l done; f 0

Score : 200 points

Problem Statement

Snuke is interested in strings that satisfy the following conditions:

The length of the string is at least N.

The first N characters equal to the string s.

The last N characters equal to the string t.

Find the length of the shortest string that satisfies the conditions.

Constraints

1≤N≤100

The lengths of s and t are both N.

s and t consist of lowercase English letters.

Input

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

N
s
t

Output

Print the length of the shortest string that satisfies the conditions.

Sample Input 1

3
abc
cde

Sample Output 1

5

The shortest string is abcde.

Sample Input 2

1
a
z

Sample Output 2

2

The shortest string is az.

Sample Input 3

4
expr
expr

Sample Output 3

4

The shortest string is expr.


let n = read_int ()
let s = read_line ()
let t = read_line ()
let f m = Printf.printf "%d\n" @@ 2 * n - m; exit 0
let _ = for i = 0 to n - 1 do if String.(sub s i (n - i) = sub t 0 (n - i)) then f (n - i) done; f 0


let s = read_line ()
let f s = print_endline s; exit 0
let i = try String.index s 'C' with _ -> f "No"
let _ = try String.index_from s i 'F' |> ignore; f "Yes" with _ -> f "No"

Score : 100 points

Problem Statement

This contest is CODEFESTIVAL, which can be shortened to the string CF by deleting some characters.

Mr. Takahashi, full of curiosity, wondered if he could obtain CF from other strings in the same way.

You are given a string s consisting of uppercase English letters.
Determine whether the string CF can be obtained from the string s by deleting some characters.

Constraints

2 ≤ |s| ≤ 100

All characters in s are uppercase English letters (A-Z).

Input

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

s

Output

Print Yes if the string CF can be obtained from the string s by deleting some characters.
Otherwise print No.

Sample Input 1

CODEFESTIVAL

Sample Output 1

Yes

CF is obtained by deleting characters other than the first character C and the fifth character F.

Sample Input 2

FESTIVALCODE

Sample Output 2

No

FC can be obtained but CF cannot be obtained because you cannot change the order of the characters.

Sample Input 3

CF

Sample Output 3

Yes

It is also possible not to delete any characters.

Sample Input 4

FCF

Sample Output 4

Yes

CF is obtained by deleting the first character.


let ans a b c =
  if a = b && b = c then 1
  else if a <> b && b <> c && c <> a then 3
  else 2;;

Scanf.scanf "%d %d %d" (fun a b c -> print_int (ans a b c))

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

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

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


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

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

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

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


let a, b = Scanf.scanf "%d %d\n" (fun a b -> a, b)
let rec pow n x =
  match n with
  | 1 -> x
  | n' -> x * pow (n'-1) x

let ans =
  if a = 1 then b
  else b * pow (a-1) (b-1)

let () =
  print_int ans; print_newline ()


let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let t_a = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%d %d " (fun a b -> a,b)) in

  let rec aux cur = function
    | [] -> cur
    | (t,a) :: tl ->
      let (rt,ra) = cur in
      if rt <= t && ra <= a
      then
        aux (t,a) tl
      else (
        let mul = max
            (if ra mod a <> 0 then ra/a+1 else ra/a)
            (if rt mod t <> 0 then rt/t+1 else rt/t)
        in
        aux (t*mul,a*mul) tl

      )
  in

  let (rt, ra) = aux (0,0) t_a in
  Printf.printf "%d\n" (rt + ra)

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

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

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


let inf = 1000000000000000001
let step (a, b) (r1, r2) =
  let c1 = begin
    let ta = (a + r1 - 1) / r1 * r1 in
    let tb = ta / r1 * r2 in
    let m = (b + tb - 1) / tb in
    (m * ta, m * tb)
  end in
  let c2 = begin
    let tb = (b + r2 - 1) / r2 * r2 in
    let ta = tb / r2 * r1 in
    let m = (a + ta - 1) / ta in
    (m * ta, m * tb)
  end in
  min c1 c2

let n = Scanf.scanf "%d" (fun x -> x)
let () =
  Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y))
  |> Array.fold_left step (1, 1)
  |> (fun (a, b) -> Printf.printf "%d\n" (a+b))


let rec input n =
		if n = 0
		then []
		else Scanf.scanf "%d %d\n" (fun x y -> (x,y)) :: input (n - 1)

let solve lst =
	let rec solve_loop before lst = match lst with
		| [] -> let(a,b) = before in a + b
		| first :: xs ->
			let (x,y) = first in
			let (a,b) = before in
			let ratio = max ((a-1)/x+1) ((b-1)/y+1) in
				solve_loop (x*ratio,y*ratio) xs
	in
		solve_loop (1,1) (List.rev lst)

let () =
	Scanf.scanf "%d\n" (fun x -> x) |> input |> solve |> Printf.printf "%d"


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

  let s_len = String.length s in
  let p_len = Batteries.String.to_list s |> List.filter (fun x -> x = 'p') |> List.length in

  Printf.printf "%d\n" @@ (s_len/2) - p_len

Score : 300 points

Problem Statement

AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:

(※) After each turn, (the number of times the player has played Paper)≦(the number of times the player has played Rock).

Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.

(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)

With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.

The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1≦i≦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1≦i≦N) character of s in p, TopCoDeer will play Paper in the i-th turn.

Constraints

1≦N≦10^5

N=|s|

Each character in s is g or p.

The gestures represented by s satisfy the condition (※).

Input

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

s

Output

Print the AtCoDeer's maximum possible score.

Sample Input 1

gpg

Sample Output 1

0

Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.

Sample Input 2

ggppgggpgg

Sample Output 2

2

For example, consider playing gestures in the following order: Rock, Paper, Rock, Paper, Rock, Rock, Paper, Paper, Rock, Paper. This strategy earns three victories and suffers one defeat, resulting in the score of 2, which is the maximum possible score.


let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let tas = Array.init n (fun _ -> Scanf.scanf "%d %d\n" (fun t a -> t, a)) in
  Array.fold_left (fun (x, y) (t, a) ->
    let n = max ((x + t - 1) / t) ((y + a - 1) / a) in
    (t * n, a * n)) (1, 1) tas
  |> (fun (x, y) -> x + y)
  |> Printf.printf "%d\n"


let s = read_line ()
let ans = ref 0
let _ = String.iteri (fun i c -> if c <> "CODEFESTIVAL2016".[i] then incr ans) s; Printf.printf "%d\n" !ans

Score : 100 points

Problem Statement

CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard.

He intended to write CODEFESTIVAL2016 on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length.

So Mr. Takahashi decided to perform an operation that replaces a certain character with another in the minimum number of iterations, changing the string to CODEFESTIVAL2016.

Find the minimum number of iterations for the rewrite operation.

Constraints

S is 16 characters long.

S consists of uppercase and lowercase alphabet letters and numerals.

Input

Inputs are provided from Standard Input in the following form.

S

Output

Output an integer representing the minimum number of iterations needed for the rewrite operation.

Sample Input 1

C0DEFESTIVAL2O16

Sample Output 1

2

The second character 0 must be changed to O and the 14th character O changed to 0.

Sample Input 2

FESTIVAL2016CODE

Sample Output 2

16


module String = struct
  include String
  let to_list s =
    let rec loop acc = function
      | 0 -> acc
      | n -> loop (s.[n - 1] :: acc) (n - 1) in
    loop [] (String.length s)
end

let () =
  let n, a, b = Scanf.scanf "%d %d %d\n" (fun n a b -> n, a, b) in
  let s = Scanf.scanf "%s\n" (fun s -> s) in
  String.to_list s
    |> List.fold_left (fun (accepted, foreigners) -> function
      | 'a' ->
          if accepted < a + b then begin
            print_endline "Yes";
            (accepted + 1, foreigners)
          end else begin
            print_endline "No";
            (accepted, foreigners)
          end
      | 'b' ->
          if accepted < a + b && foreigners < b then begin
            print_endline "Yes";
            (accepted + 1, foreigners + 1)
          end else begin
            print_endline "No";
            (accepted, foreigners + 1)
          end
      | 'c' -> print_endline "No"; (accepted, foreigners)) (0, 0)
    |> ignore

Score : 200 points

Problem Statement

There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.

A string S is assigned indicating attributes of all participants. If the i-th character of string S is a, this means the participant ranked i-th in the Qualification contests is a Japanese student; b means the participant ranked i-th is an overseas student; and c means the participant ranked i-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

S consists only of the letters a, b and c.

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

Output N lines. On the i-th line, output Yes if the i-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

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

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No


let () = Scanf.scanf "%d %d\n" @@ fun w h ->
  begin
    Array.to_list (Array.init w (fun _ ->
      Scanf.scanf "%d\n" (fun p -> (p, `Col)))) @
    Array.to_list (Array.init h (fun _ ->
      Scanf.scanf "%d\n" (fun q -> (q, `Row))))
  end
  |> List.sort (fun (p, _) (q, _) -> compare p q)
  |> List.fold_left (fun (cost, (row, col)) -> function
    | (p, `Col) ->
        (* p_i は，∀j. (i, j)と(i + 1, j)を結ぶコスト *)
        (cost + p * row, (row, col - 1))
    | (q, `Row) ->
        (* q_j は，∀i. (i, j)と(i, j + 1)を結ぶコスト *)
        (cost + q * col, (row - 1, col))) (0, (h + 1, w + 1))
  |> fst
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.

There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.

The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.

Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.

Constraints

1 ≦ W,H ≦ 10^5

1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)

1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)

p_i (0 ≦ i ≦ W−1) is an integer.

q_j (0 ≦ j ≦ H−1) is an integer.

Input

Inputs are provided from Standard Input in the following form.

W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}

Output

Output an integer representing the minimum total cost.

Sample Input 1

2 2
3
5
2
7

Sample Output 1

29

It is enough to pave the following eight roads.

Road connecting houses at (0,0) and (0,1)

Road connecting houses at (0,1) and (1,1)

Road connecting houses at (0,2) and (1,2)

Road connecting houses at (1,0) and (1,1)

Road connecting houses at (1,0) and (2,0)

Road connecting houses at (1,1) and (1,2)

Road connecting houses at (1,2) and (2,2)

Road connecting houses at (2,0) and (2,1)

Sample Input 2

4 3
2
4
8
1
2
9
3

Sample Output 2

60


let () = Scanf.scanf "%d %d\n" @@ fun w h ->
  begin
    Array.to_list (Array.init w (fun i ->
      Scanf.scanf "%d\n" (fun p -> (p, `Col)))) @
    Array.to_list (Array.init h (fun i ->
      Scanf.scanf "%d\n" (fun q -> (q, `Row))))
  end
  |> List.sort (fun (p, _) (q, _) -> compare p q)
  |> List.fold_left (fun (cost, (row, col)) -> function
    | (p, `Col) -> (cost + p * (h + 1 - row), (row, col + 1))
    | (q, `Row) -> (cost + q * (w + 1 - col), (row + 1, col))) (0, (0, 0))
  |> fst
  |> Printf.printf "%d\n"


let rec for_fold a b f v = if a >= b then v else for_fold (a+1) b f (f v a)
let rec pop v = function (y,_)::ys when y > v -> pop v ys | ys -> ys

let _ = Scanf.scanf "%d" @@ fun n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let li = Array.make n (-1) in
  let _ : _ list = for_fold 0 n (fun stk i ->
    let x = a.(i) in
    let stk' = pop x stk in
    li.(i) <- (match stk' with [] -> -1 | (_,j)::_ -> j);
    (x, i)::stk') [] in

  let ri = Array.make n n in
  let _ : _ list = for_fold 0 n (fun stk i ->
    let i = n-1-i in
    let x = a.(i) in
    let stk' = pop x stk in
    ri.(i) <- (match stk' with [] -> n | (_,j)::_ -> j);
    (x, i)::stk') [] in

  for_fold 0 n (fun s i ->
    Printf.printf "-- %d %d %d %d\n" i a.(i) li.(i) ri.(i);
    s + a.(i) * (i - li.(i)) * (ri.(i) - i)) 0
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

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

N
a_1 a_2 ... a_N

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


let s = read_line ()
let _ = String.iteri (fun i c -> if i = 4 then print_char ' '; print_char c) s; print_newline ()

Score : 100 points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string s with 12 letters.
Output the string putting a single space between the first 4 letters and last 8 letters in the string s.

Constraints

s contains exactly 12 letters.

All letters in s are uppercase English letters.

Input

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

s

Output

Print the string putting a single space between the first 4 letters and last 8 letters in the string s.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first 4 letters and last 8 letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun i -> Scanf.scanf " %d" pred
let c = ref 0
let _ = Array.iteri (fun i a -> if a_s.(a) = i then incr c) a_s; Printf.printf "%d\n" @@ !c / 2

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

Input

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

N
a_1 a_2 ... a_N

Output

Print the number of the friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" pred
let c = ref 0
let _ = Array.iteri (fun i a -> if a_s.(a) = i then incr c) a_s; Printf.printf "%d\n" @@ !c / 2


open Printf
open Scanf

let solve a b h = (a + b) * h / 2

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

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

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

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


let a = read_int ()
let b = read_int ()
let h = read_int ()

let () = ((b - a) * h) / 2 + a * h |> Printf.printf "%d\n"


open Batteries
let rec collect acc sum = function
  | [] -> (sum + acc)
  | (x::xs) ->
      collect (10*acc+x) sum xs +
      collect x (sum+acc) xs

let (h::s) = Scanf.scanf "%s" String.to_list
  |> List.map (fun d -> int_of_char d - 48)
;;

collect h 0 s |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

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

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


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

let rec seq a b = if a > b then [] else a :: seq (a+1) b
let (>>=) xs f = List.map f xs |> List.concat

let inc x y m =
  try M.add (x, y) (1 + M.find (x, y) m) m
  with Not_found -> M.add (x, y) 1 m

let () =
  Scanf.scanf "%d %d %d" @@ fun h w n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
  let ret = Array.make 10 0 in
  a |> Array.fold_left (fun m1 (x, y) ->
    seq (max 1 (x-2)) (min (h-2) x) >>= (fun i -> seq (max 1 (y-2)) (min (w-2) y) >>= (fun j -> [(i, j)]))
    |> List.fold_left (fun m2 (i, j) -> inc i j m2) m1
  ) M.empty
  |> M.iter (fun (x, y) v ->
      ret.(v) <- ret.(v) + 1);

  let cur = Array.fold_left (+) 0 ret in
  ret.(0) <- (h-2)*(w-2) - cur;
  Array.iter (Printf.printf "%d\n") ret

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

1 \leq a_i \leq H (1 \leq i \leq N)

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

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

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

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

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

10 10 20
1 1
1 4
1 9
2 5
3 10
4 2
4 7
5 9
6 4
6 6
6 7
7 1
7 3
7 7
8 1
8 5
8 10
9 2
10 4
10 9

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0


let n = read_int ()
let k = read_int ()
let x = read_int ()
let y = read_int ()
let _ = (if n > k then k * x + (n-k) * y else n * x) |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

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

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

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

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

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

Input

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

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


Scanf.scanf "%s" (fun w ->
    let h = Array.make 26 0 in
    String.iter (fun v -> let q = int_of_char v - 97 in h.(q) <- h.(q) + 1) w;
    print_endline @@ if Array.fold_left (lor) 0 h mod 2 = 0 then "Yes" else "No"
)

Score : 200 points

Problem Statement

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

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

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

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

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

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

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

Sample Input 2

hthth

Sample Output 2

No


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

let lst = Str.split (Str.regexp "") (read_line ())
          |> List.sort compare
let lst2 = List.sort_uniq compare lst
let lst3 =
        List.map (fun elmnt1 ->
                List.filter (fun elmnt2 ->
                        elmnt1 = elmnt2
                ) lst
        ) lst2
let lst4 = List.map (fun elst ->
        List.length elst
) lst3

let () =
        (
                if List.exists (fun elmnt -> elmnt mod 2 = 1) lst4 then
                        "No"
                else
                        "Yes"
        ) |> Printf.printf "%s\n"


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

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

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

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

Score : 300 points

Problem Statement

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

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

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

Partial Score

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

Input

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

N A
x_1 x_2 ... x_N

Output

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

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

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

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

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

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

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

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

Sample Output 4

8589934591

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


let get_line () =
    read_line ()
    |> Str.split (Str.regexp " ")

(* use List.cons in 4.03.0 or later *)
let cons elem lst = elem :: lst

let get_sublists lst =
    let rec loop lst acc =
        match lst with
        | [] -> acc
        | x :: xs ->
            loop xs
                (List.append (List.map (cons x) acc) acc)
    in
    loop lst [[]]

let get_average lst =
    let sum = List.fold_left ( +. ) 0.0 lst in
    sum /. float_of_int (List.length lst)

let print_list lst =
    List.map string_of_float lst
    |> String.concat " "
    |> print_endline

let () =
    let a =
        let [_; a] = get_line () in
        float_of_string a
    in
    let cards =
        get_line ()
        |> List.map float_of_string
    in
    get_sublists cards
    |> List.map get_average
    |> List.filter (fun x -> x = a)
    |> List.length
    |> print_int
    |> print_newline


let rec loop x fn =
  match fn x with
  | `Break x -> x
  | `Continue x -> loop x fn

module List = struct
  include List
  let take n lst =
    loop (0, lst, []) begin fun (i, rest, r_acc) ->
      match i < n, rest with
      | true, []  | false, _ -> `Break (rev r_acc)
      | true, x :: rest -> `Continue (i + 1, rest, x :: r_acc) end
  let drop n lst =
    loop (0, lst) begin fun (i, rest) ->
      match i < n, rest with
      | true, _ :: rest -> `Continue (i + 1, rest)
      | true, []  | false, _ -> `Break rest end
end

let () =
  let open Scanf in
  let read_ints () = let open Buffer in
    let buf = create 10 in
    let add = add_bytes buf and get () = contents buf in
    loop () begin fun () ->
      try read_line () ^ " " |> add; `Continue ()
      with _ -> `Break (get ()) end
    |> Str.(split (regexp " ")) |> List.map int_of_string in

  let rest = read_ints () in
  let n :: rest = rest in
  let xs = List.take n rest in
  let l :: q :: qs = List.drop n rest in
  let qs =
    let qs = qs |> List.map (fun q -> q - 1) in
    loop (qs, []) begin fun (rest, r_acc) ->
      match rest with
      | x:: y:: rest -> `Continue (rest, (x, y):: r_acc)
      | []  | _:: [] -> `Break (List.rev r_acc) end in
  (* input stage is finally finished *)

  let xs = Array.of_list xs in
  let bisect fn_shift fn_idx = fun l r x ->
    loop (l, r) begin fun (l, r) ->
      if r - l - 1 = 0 then `Break (fn_idx l r)
      else let m = (l + r) / 2 in
        match fn_shift x xs.(m) with
        | `Left -> `Continue (l, m)
        | `Right -> `Continue (m, r) end in
  let bisect_l = bisect
      (fun x m -> if x < m then `Left else `Right) (fun l r -> l)
  and bisect_r = bisect
      (fun x m -> if x > m then `Right else `Left) (fun l r -> r) in

  let next = let open Hashtbl in
    let memo = create 10 in
    let cache = replace memo and get = find memo in
    let calc init fn_bound direction fn_step fn_shift fn_bisect =
      loop init begin fun here ->
        match fn_bound here with
        | false ->
          cache (here, direction) (fn_step here); `Break ()
        | true ->
          let x' = fn_shift xs.(here) l in
          let next = fn_bisect here x' in
          cache (here, direction) next;
          `Continue (fn_step here) end in
    calc 0 (fun x -> x < n - 1) `Right succ ( + )
      (fun here x -> bisect_l here n x);
    calc (n - 1) (fun x -> x > 0) `Left pred ( - )
      (fun here x -> bisect_r (-1) here x);
    (* let fold init fn t = fold fn t init in *)
    (* memo |> fold () begin fun k v () -> *)
    (*   match k with *)
    (*   | here, `Left -> *)
    (*     Printf.printf "`L, %d = %d;" (succ here) (succ v) *)
    (*   | here, `Right -> *)
    (*     Printf.printf "`R, %d = %d;" (succ here) (succ v) end; *)
    get in

  let add, get = let open Buffer in
    let buf = create (q * 2) in
    let add = add_string buf and get () = contents buf in
    add, get in

  let solve (a, b) =
    let reached, next =
      if a < b
      then (fun x -> b <= x), (fun x -> next (x, `Right))
      else (fun x -> b >= x), (fun x -> next (x, `Left)) in
    loop (a, 0) begin fun (a, cnt) ->
      let a' = next a in
      (* add (Printf.sprintf "(%d,%d), " (a + 1) (a' + 1)); *)
      if reached a' then `Break (cnt + 1)
      else `Continue (a', cnt + 1) end in

  qs |> List.map begin fun q ->
    let open Printf in
    (* printf "q:(%d,%d)" (fst q) (snd q); flush_all (); *)
    add (sprintf "%d\n" (solve q));
  end |> ignore;
  Printf.printf "%s" (get ());


open Printf
open Scanf

let rec loop x fn =
  match fn x with
  | `Break x -> x
  | `Continue x -> loop x fn

let ( |- ) x f = f x; x
let flip f a b = f b a

module Int = struct
  include Int64
  module Infix = struct
    let ( + ) = add and ( - ) = sub
    and ( * ) = mul and ( / ) = div
  end
end

let () =
  let read_ints () =
    let str = loop (Buffer.create 10) begin fun buf ->
        try
          `Continue (buf |- (flip Buffer.add_bytes)
                       (read_line () ^ " "))
        with _ ->
          `Break (buf |> Buffer.contents) end in
    str |> Str.(split (regexp " ")) |> List.map int_of_string in

  let num:: avg:: xs = read_ints () in
  let xs = xs |> Array.of_list in

  let cache, cached, get = let open Hashtbl in
    let memo = create 10 in
    let cache = replace memo in
    let cached = mem memo in
    let get = find memo in
    cache, cached, get in

  let rec solve ~sum ~cnt ~idx : Int64.t =
    if cached (sum, cnt, idx)
    then get (sum, cnt, idx)
    else if idx >= num
    then if cnt != 0 && cnt * avg = sum then 1L else 0L
    else
      let idx' = idx + 1 in
      let sum' = sum + xs.(idx) and cnt' = cnt + 1 in
      let open Int.Infix in
      let ans = solve ~sum ~cnt ~idx: idx'
                + solve ~sum: sum' ~cnt: cnt' ~idx: idx' in
      ans |- cache (sum, cnt, idx) in

  let sum = 0 and cnt = 0 and idx = 0 in
  let ans = solve ~sum ~cnt ~idx in
  printf "%Ld\n" ans


Scanf.scanf "%d %d" (fun n s ->
    let rec f b n = if n < b then n else f b (n/b) + (n mod b) in

    let step3 n =
        if n = s then n + 1 else -1
    in

    let step2 n =
        let ns = n - s in
        let rec loop a =
            if a = 0 then step3 n else
                if ns mod a = 0 && s - a <= ns / a then ns / a + 1 else
                    loop (a - 1)
        in
        loop (min s (int_of_float (floor (sqrt (float ns) +. 0.5))))
    in

    let rec loop i =
        if i * i > n then step2 n else
            if f i n = s then i else
                loop (i + 1)
    in
    loop 2 |> Printf.printf "%d\n"
)

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

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

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


let rec f acc b = function
  | 0 -> acc
  | n -> f (n mod b + acc) b (n / b)
let f = f 0

let () = Scanf.scanf "%d %d" @@ fun n s ->
  let r = int_of_float @@ sqrt @@ float_of_int n in
  try
    Array.init r (( + ) 2)
    |> Array.to_list
    |> List.find (fun b -> f b n = s)
    |> Printf.printf "%d\n"
  with Not_found ->
    try
      Array.init (n / r) (( + ) 1)
      |> Array.to_list
      |> List.rev_map (fun p -> (n - 1) / p + 1)
      |> List.filter (( <= ) 2)
      |> List.find (fun b -> f b n = s)
      |> Printf.printf "%d\n"
    with Not_found -> print_endline "-1"