open Printf
open Scanf

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

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

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

let ans = solve list g;;

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

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

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

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

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

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

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

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

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

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

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

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

Sample Input 4

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

Sample Output 4

66

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


Scanf.scanf "%d %d" @@ fun d g ->
  let a = Array.init d (fun i ->
    Scanf.scanf " %d %d" (fun p c->((i+1)*100,p,c))) in
  let ls = a |> Array.fold_left (fun l (i,p,c) ->
    List.fold_left (fun l (isum,psum)->
      ((Array.init (p+1) (fun pi -> isum+pi,psum+pi*i+if pi=p then c else 0)) |> Array.to_list) @ l
    ) [] l
  ) [0,0] in
  let ls = List.filter(fun (i,p) -> p>= g) ls in
  let ls = List.sort compare ls in
  ls |> List.iter (fun (i,p)->Printf.printf "%d\n" i;exit 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.


open Printf
open Scanf

let solve a1 a2 a3 = max a1 (max a2 a3) - min a1 (min a2 a3)

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

Score : 100 points

Problem Statement

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

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

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

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

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

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

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

Sample Input 1

1 6 3

Sample Output 1

5

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

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


let a, b, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let f a b c = abs (b - a) + abs (c - b)
let _ = List.fold_left min max_int [f a b c; f a c b; f b a c; f b c a; f c a b; f c b a] |> Printf.printf "%d\n"


let () =
  let s = read_line () in
  let t = read_line () in
  Array.init (String.length s) (fun i -> i)
  |> Array.to_list
  |> List.exists (fun i ->
      Array.init (String.length s) (fun j -> j)
      |> Array.to_list
      |> List.for_all (fun j ->
          s.[(i + j) mod String.length s] = t.[j]))
  |> (function true -> "Yes" | false -> "No")
  |> print_endline

Score : 200 points

Problem Statement

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

Determine if S equals T after rotation.

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

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

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

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

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

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


open Batteries
open Printf
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let a_l = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in
  Printf.printf "%d\n" @@
  List.fold_left (fun acc x -> acc + (x-1)) 0 a_l

Score : 300 points

Problem Statement

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

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

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

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

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

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


open Printf open Scanf
module MyInt = struct
	let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v
	(* 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 print_int_endline n = n |> string_of_int |> print_endline *)
end
(* module MyInt64 = struct *)
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * )
	let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v
	let labs p = if p < 0L then -1L*p else p
	let (~|) p = Int64.to_int p
	let (~~|) p = Int64.of_int p

	let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 () = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 () = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 () = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 () = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 () = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let print_i64_endline n =
		n |> Int64.to_string |> print_endline

	let (mod) m n = m - (m/n) * n let (%) = (mod)
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let rec lcm m n = (m*n) / gcd m n
	let rep from_ to_ fbod =
		let i,f = ref ~|from_,ref true in while !i <= ~|to_-$1 && !f do
			match fbod !i with
			| `Ok -> i := !i +$ 1;
			| `Ng -> f := false
		done
(* end open MyInt64 *)

let () =
	let n = get_i64 ()
	in let a = input_i64_array n
	in
	let sum = ref 0L in
	for j=0 to Array.length a -$ 1 do
		sum += (a.(j) - 1L)
	done;
	!sum |> printf "%Ld\n"


open Scanf
open Printf

module Int = struct
  type t = int
  let compare a b = compare a b
end

module S = Set.Make(Int)

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

let f a b c d = let memo = ref S.empty in
  let rec g x = if x < 0
    then printf "No\n"
    else if S.mem x !memo
    then printf "Yes\n"
    else (memo := S.add x !memo; g (consume c b (x+d)))
  in g (consume c b a)

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

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

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

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

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

Constraints

1 \leq T \leq 300

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

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

Output

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

Sample Input 1

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

Sample Output 1

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

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

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

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

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

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

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

Sample Output 2

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


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

let () = Scanf.scanf "%d\n%s\n" @@ fun n s ->
  let m =
    Array.fold_left (fun m rb ->
      M.add rb (1 + try M.find rb m with Not_found -> 0) m) M.empty @@
    Array.init (1 lsl n) @@ fun i ->
      Array.fold_left (fun (r, b) j ->
        if i land (1 lsl j) = 0
        then (s.[j + n] :: r, b)
        else (r, s.[j + n] :: b)) ([], []) @@
      Array.init n @@ fun j -> j in
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.init (1 lsl n) @@ fun i ->
    let (r, b) =
      Array.fold_left (fun (r, b) j ->
        if i land (1 lsl j) = 0
        then (s.[j] :: r, b)
        else (r, s.[j] :: b)) ([], []) @@
      Array.init n @@ fun j -> j in
    try M.find (List.rev b, List.rev r) m with Not_found -> 0

Score : 600 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 18

The length of S is 2N.

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

4
cabaacba

Sample Output 1

4

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

cabaacba

cabaacba

cabaacba

cabaacba

Sample Input 2

11
mippiisssisssiipsspiim

Sample Output 2

504

Sample Input 3

4
abcdefgh

Sample Output 3

0

Sample Input 4

18
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Sample Output 4

9075135300

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


open Scanf
open Printf

let id a = a
let pair a b = a, b
let triplet a b c = a, b, c

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

let f a b = if a + b = 15
  then printf "+\n"
  else if a * b = 15
  then printf "*\n"
  else printf "x\n"

let () = scanf "%d %d\n" f

Score : 100 points

Problem Statement

You are given two integers a and b.
Determine if a+b=15 or a\times b=15 or neither holds.

Note that a+b=15 and a\times b=15 do not hold at the same time.

Constraints

1 \leq a,b \leq 15

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If a+b=15, print +;
if a\times b=15, print *;
if neither holds, print x.

Sample Input 1

4 11

Sample Output 1

+

4+11=15.

Sample Input 2

3 5

Sample Output 2

*

3\times 5=15.

Sample Input 3

1 1

Sample Output 3

x

1+1=2 and 1\times 1=1, neither of which is 15.


Scanf.scanf"%s %d"@@fun s w->String.iteri(fun i c->if i mod w=0 then print_char c)s

Score : 200 points

Problem Statement

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

Constraints

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

S consists of lowercase English letters.

w is an integer.

Input

Input is given from Standard Input in the following format:

S
w

Output

Print the desired string in one line.

Sample Input 1

abcdefgh
3

Sample Output 1

adg

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

abc

def

gh

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

Sample Input 2

lllll
1

Sample Output 2

lllll

Sample Input 3

souuundhound
2

Sample Output 3

suudon


Score : 300 points

Problem Statement

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

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

Constraints

0 \leq d < n \leq 10^9

2 \leq m \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m d

Output

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

Sample Input 1

2 3 1

Sample Output 1

1.0000000000

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

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

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

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

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

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

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

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

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

Sample Input 2

1000000000 180707 0

Sample Output 2

0.0001807060


open Scanf
open Printf

let id a = a
let pair a b = a, b
let triplet a b c = a, b, c

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

let g arr u v s = arr.(u-1) <- (v-1,s) :: arr.(u-1);
  arr.(v-1) <- (u-1,s) :: arr.(v-1)

let f n m = let graph = (Array.make n []) in
  for i = 1 to m do
    scanf "%d %d %d\n" (g graph)
  done;
  for i = 0 to n-1 do
    graph.(i) <- List.sort compare graph.(i)
  done;
  graph

let h graph ans = let queue = Queue.create () in
  let rec enqueue a = function
    | (v, c) :: lst -> if ans.(v) = 0 then Queue.add (a, v, c) queue; enqueue a lst
    | [] -> ()
  in let rec f () = if Queue.is_empty queue
       then `Ok
       else let (u, v, c) = Queue.take queue
         in if ans.(v) = 0
         then begin
           ans.(v) <- (if c > ans.(u) then c - ans.(u) else raise @@ failwith "negative answer");
           enqueue v graph.(v);
           f ()
         end
         else if c = ans.(v) + ans.(u)
         then begin
           enqueue v graph.(v);
           f ()
         end
         else raise @@ failwith "incorrect"
  in enqueue 0 graph.(0); f()

let cost lst = List.map (function (_, c) -> c) lst
let minimum lst = List.fold_left min 10000000000000 lst

let compute graph = let n = ref 0 in
  for i = 1 to minimum (cost graph.(0)) - 1 do
    let ans = Array.make (Array.length graph) 0
    in ans.(0) <- i;
    match h graph ans with
    | `Ok -> n := !n + 1
    | exception Failure s -> eprintf "%s\n" s
  done;
  printf "%d\n" !n

let () = compute @@ scanf "%d %d\n" f

Score : 600 points

Problem Statement

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

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

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

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

Constraints

2 \leq n \leq 10^5

1 \leq m \leq 10^5

1 \leq u_i < v_i \leq n

2 \leq s_i \leq 10^9

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

The graph is connected.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m
u_1 v_1 s_1
:
u_m v_m s_m

Output

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

Sample Input 1

3 3
1 2 3
2 3 5
1 3 4

Sample Output 1

1

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

Sample Input 2

4 3
1 2 6
2 3 7
3 4 5

Sample Output 2

3

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

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

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

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

Sample Input 3

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

Sample Output 3

0


Scanf.scanf "%d" (fun n ->
    Printf.printf "%d\n" @@ if n mod 2 = 0 then n else n * 2
)

Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


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 c a b =
	Array.fold_left (fun u v -> u + abs (v-b)) 0 a

let () =
	let n = get_int ()
	in let a = Array.mapi
		(fun i v -> v - i - 1)
		(input_int_array n)
	in let b =
		let b = Array.copy a
		in Array.sort Pervasives.compare b; b
	in
	(
		if n mod 2 = 1 then (
			c b b.(Array.length b / 2)
		) else (
			min
				(c b b.(Array.length b / 2))
				(c b b.(Array.length b / 2 - 1))
		)
	)
	|> string_of_int |> print_endline

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

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

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

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

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

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

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


open Batteries
open Printf
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let a_lst = Array.to_list @@ Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a)) in

  let rev_cumsum l =
    let rec aux last res = function
      | [] -> res
      | hd :: tl ->
        let last = last + hd in
        aux last (last::res) tl
    in
    aux 0 [] l
  in

  let l = List.rev (rev_cumsum a_lst) in
  let arr = Array.of_list l in
  let n = n-1 in
  let len = Array.length arr in

  let ans = ref max_int in
  let rec loop i j k arr cnt =
    if k < n then (
      let tmp =
        List.max [arr.(i); (arr.(j)-arr.(i)); (arr.(k)-arr.(j)); (arr.(len-1)-arr.(k));] -
        List.min [arr.(i); (arr.(j)-arr.(i)); (arr.(k)-arr.(j)); (arr.(len-1)-arr.(k));] in
      if !ans < tmp then () else ans := tmp;
      loop i j (k+1) arr (cnt+1)
    ) else (
      if j < n-1 then (
        loop i (j+1) (j+2) arr cnt
      ) else (
        if i < n-1 then (
          loop (i+1) (i+2) (i+3) arr cnt
        ) else (
          ()
        )
      )
    )
  in
  loop 0 1 2 arr 0;
  printf "%d\n" !ans

Score : 600 points

Problem Statement

Snuke has an integer sequence A of length N.

He will make three cuts in A and divide it into four (non-empty) contiguous subsequences B, C, D and E.
The positions of the cuts can be freely chosen.

Let P,Q,R,S be the sums of the elements in B,C,D,E, respectively.
Snuke is happier when the absolute difference of the maximum and the minimum among P,Q,R,S is smaller.
Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Find the minimum possible absolute difference of the maximum and the minimum among P,Q,R,S.

Sample Input 1

5
3 2 4 1 2

Sample Output 1

2

If we divide A as B,C,D,E=(3),(2),(4),(1,2), then P=3,Q=2,R=4,S=1+2=3.
Here, the maximum and the minimum among P,Q,R,S are 4 and 2, with the absolute difference of 2.
We cannot make the absolute difference of the maximum and the minimum less than 2, so the answer is 2.

Sample Input 2

10
10 71 84 33 6 47 23 25 52 64

Sample Output 2

36

Sample Input 3

7
1 2 3 1000000000 4 5 6

Sample Output 3

999999994


(*
 * forall l r (p : forall n, l < n <= r -> bool),
 *   ( exists m,
 *     l < m <= r /\ forall n H, p n H = true <-> m <= n ) ->
 *   { m |
 *     l < m <= r /\ forall n H, p n H = true <-> m <= n }
 *)
let rec lower_bound l r p =
  if r <= 1 + l
  then r
  else let m = (l + r) / 2 in
       if p m
       then lower_bound l m p
       else lower_bound m r p

(*
 * forall l r (p : forall n, l <= n < r -> bool),
 *   ( exists m,
 *     l <= m < r /\ forall n H, p n H = true <-> n <= m ) ->
 *   { m |
 *     l <= m < r /\ forall n H, p n H = true <-> n <= m }
 *)
let rec upper_bound l r p =
  if r <= 1 + l
  then l
  else let m = (l + r) / 2 in
       if p m
       then upper_bound m r p
       else upper_bound l m p

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ ->
    Scanf.scanf "%d " @@ fun a -> a in
  let sum_as = Array.make (n + 1) 0 in
  (* sum_as.(i): 添字の範囲[0; i)におけるas_の要素の総和 *)
  (* 添字の範囲[i; j)の総和が欲しければ sum_as.(j) - sum_as.(i) で手に入る *)
  for i = 0 to n - 1 do
    sum_as.(i + 1) <- as_.(i) + sum_as.(i)
  done;
  begin
    List.concat @@ List.map (fun b1 ->
      List.concat @@ List.map (fun b2 ->
        (* 真ん中の切れ目だけ与えてやる *)
        Array.to_list @@ Array.init (n - 3) (fun j ->
          let j = j + 2 in
          (* B は[0; i)，C は[i; j)，D は[j; k)，E は[k; n) *)
          (* PとQどちらを大きくするかをb1に委ね，にぶたんする *)
          let i =
            if b1 then
              (* P <= Q となる最大の添字 *)
              upper_bound 1 j @@ fun i ->
                sum_as.(i) <= sum_as.(j) - sum_as.(i)
            else
              (* P >= Q となる最小の添字 *)
              lower_bound 0 (j - 1) @@ fun i ->
                sum_as.(i) >= sum_as.(j) - sum_as.(i) in
          (* RとSどちらを大きくするかをb2に委ね，にぶたんする *)
          let k =
            if b2 then
              (* R <= S となる最大の添字 *)
              upper_bound (j + 1) n @@ fun k ->
                sum_as.(k) - sum_as.(j) <= sum_as.(n) - sum_as.(k)
            else
              (* R >= S となる最小の添字 *)
              lower_bound j (n - 1) @@ fun k ->
                sum_as.(k) - sum_as.(j) >= sum_as.(n) - sum_as.(k) in
          let pqrs = [ sum_as.(i); sum_as.(j) - sum_as.(i); sum_as.(k) - sum_as.(j); sum_as.(n) - sum_as.(k) ] in
          List.fold_left max min_int pqrs - List.fold_left min max_int pqrs)) [ true; false ]) [ true; false ]
  end
  |> List.fold_left min max_int
  |> Printf.printf "%d\n"


let s = read_line ()
let ans = ref 0
let _ =
  String.iter (function '+' -> incr ans | _ -> decr ans) s;
  Printf.printf "%d\n" !ans

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

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

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

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

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

+-++

Sample Output 1

2

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

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

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

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

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

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

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


let () =
  let s = read_line () in
  Array.init (String.length s) (fun i ->
    if s.[i] = '+' then 1
    else (-1))
  |> Array.fold_left ( + ) 0
  |> Printf.printf "%d\n"


let rec dig_sum n = if n <= 0 then 0 else n mod 10 + dig_sum (n / 10)
let () =
  Scanf.scanf "%d" (fun n -> if n mod dig_sum n = 0 then "Yes" else "No")
  |> print_endline

Score : 200 points

Problem Statement

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

Given an integer N, determine if S(N) divides N.

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

If S(N) divides N, print Yes; if it does not, print No.

Sample Input 1

12

Sample Output 1

Yes

In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.

Sample Input 2

101

Sample Output 2

No

As S(101) = 1 + 0 + 1 = 2, S(N) does not divide N.

Sample Input 3

999999999

Sample Output 3

Yes


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

Score : 300 points

Problem Statement

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

On this sequence, Snuke can perform the following operation:

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

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

Constraints

2 \leq K \leq N \leq 100000

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

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

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

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

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


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


open Scanf
open Printf

let id a = a
let pair a b = a, b
let triplet a b c = a, b, c

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

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

let sunuke n = float_of_int n /. float_of_int (s n)

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

let f n = for i = 1 to n do
    printf "%d99\n" i
  done

let g n = if n > 9
  then begin
    for i = 1 to 9 do
      printf "%d9\n" i
    done;
    f (n-9)
  end
  else
    for i = 1 to n do
      printf "%d9\n" i
    done

let h n = if n > 9
  then begin
    for i = 1 to 9 do
      printf "%d\n" i
    done;
    g (n-9)
  end
  else
    for i = 1 to 9 do
      printf "%d\n" i
    done

let () = scanf "%d\n" h

Score : 500 points

Problem Statement

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

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

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

Constraints

1 \leq K

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

Input

Input is given from Standard Input in the following format:

K

Output

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

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19


Scanf.scanf "%d %d" (fun a b ->
    print_endline @@ if a <= 8 && b <= 8 then "Yay!" else ":("
)

Score: 100 points

Problem Statement

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

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

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

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

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

Constraints

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

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

5 4

Sample Output 1

Yay!

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

Sample Input 2

8 8

Sample Output 2

Yay!

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

Sample Input 3

11 4

Sample Output 3

:(

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


let a, b = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = print_endline @@ if a <= 8 && b <= 8 then "Yay!" else ":("


let () = Scanf.scanf "%d %d" @@ fun a b ->
  if a <= 8 && b <= 8 then print_endline "Yay!"
  else print_endline ":("


Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let calc t =
        let rec loop i acc =
            if i mod 2 = 0 then loop (i lsr 1) (acc + 1) else acc
        in
        loop t 0
    in
    Array.fold_left (fun acc v -> acc + calc v) 0 a |> Printf.printf "%d\n"
)

Score: 300 points

Problem Statement

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

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

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

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

At most how many operations can be performed?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

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

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

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

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

Sample Input 2

4
631 577 243 199

Sample Output 2

0

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

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


open Scanf
open Printf

let () = scanf "%d" (fun k -> if k > 999 then printf "ABC\n" else printf "ABD\n")

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

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

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

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

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

999

Sample Output 1

ABC

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

Sample Input 2

1000

Sample Output 2

ABD

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

Sample Input 3

1481

Sample Output 3

ABD

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


let rec take_while pred = function
    [] -> []
  | (x::xs) -> if pred x then x :: take_while pred xs else []

let rec scan_n n f v = if n <= 0 then [] else v :: scan_n (n-1) f (f v)

let arr = Array.init 101010 (fun i -> i)
let () = Scanf.scanf "%d" (fun n ->
  Array.init (n+1) (fun i ->
    [6; 9] |> List.iter (fun m ->
      scan_n 20 (( * ) m) 1 |> take_while ((>=) i) |> List.iter (fun j ->
        arr.(i) <- min arr.(i) (arr.(i - j) + 1)))) |> ignore;
  Printf.printf "%d\n" arr.(n))

Score : 300 points

Problem Statement

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

1 yen (the currency of Japan)

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

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

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

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

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

127

Sample Output 1

4

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

Sample Input 2

3

Sample Output 2

3

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

Sample Input 3

44852

Sample Output 3

16


(* 与えられたリストからk要素を選ぶ順列 *)
let perm k xs =
  let rec perm_aux trace n k i xs ys acc =
    match k, i, xs with
    | 0, _, _ -> trace :: acc
    | _, 0, _ -> acc
    | _, _, [] -> perm_aux trace n k i (List.rev ys) [] acc
    | _, _, x :: xs ->
        perm_aux trace n k (i - 1) xs (x :: ys) @@
        perm_aux (x :: trace) (n - 1) (k - 1) (n - 1) xs ys acc in
  let n = List.length xs in
  perm_aux [] n k n xs [] []

let () = Scanf.scanf "%d %d\n" @@ fun n c ->
  let dss =
    Array.init c @@ fun _ ->
      Array.init c @@ fun _ ->
        Scanf.scanf "%d " @@ fun d -> d in
  let css =
    Array.init n @@ fun _ ->
      Array.init n @@ fun _ ->
        Scanf.scanf "%d " @@ fun c -> c in
  let colours = Array.make_matrix 3 c 0 in
  Array.iteri (fun i ->
    Array.iteri (fun j c ->
      colours.((i + j + 2) mod 3).(c - 1) <- colours.((i + j + 2) mod 3).(c - 1) + 1)) css;
  Array.init c (fun c -> c)
  |> Array.to_list
  |> perm 3
  |> List.map (List.mapi (fun m y ->
      Array.mapi (fun x n -> n * dss.(x).(y)) colours.(m)
      |> Array.fold_left ( + ) 0))
  |> List.map (List.fold_left ( + ) 0)
  |> List.fold_left min max_int
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

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

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

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

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

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

Here, X \% Y represents X modulo Y.

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

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

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

Constraints

1 \leq N \leq 500

3 \leq C \leq 30

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

3

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

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

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

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

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

Sample Input 2

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

Sample Output 2

428


let rec seq a b = if a > b then [] else a :: seq (a+1) b
let (>>=) x f = List.map f x |> List.concat
let () =
  Scanf.scanf "%d %d" @@ fun n c ->
  let d =
    Array.init c (fun i ->
      Array.init c (fun j -> Scanf.scanf " %d" ((+) 0)))
  in
  let b =
    Array.init n (fun i ->
      Array.init n (fun j -> Scanf.scanf " %d" ((+) 0)))
  in
  (seq 0 (c-1) >>= fun i ->
   seq 0 (c-1) >>= fun j ->
   seq 0 (c-1) >>= fun k ->
     if i = j || j = k || k = i then []
     else [
       let t = [|i; j; k;|] in
       (seq 0 (n-1) >>= fun x ->
        seq 0 (n-1) >>= fun y ->
          [d.(b.(x).(y)-1).(t.((x+y) mod 3))])
       |> List.fold_left (+) 0
     ])
  |> List.fold_left min 10101010101010
  |> Printf.printf "%d\n"


let n = read_line ()
let s = Array.fold_left (+) 0 @@ Array.init (String.length n) @@ fun i -> Char.code n.[i] - Char.code '0'
let _ = Printf.printf "%d\n" @@ if s = 1 then 10 else s

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

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

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

15

Sample Output 1

6

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

Sample Input 2

100000

Sample Output 2

10


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

let () = Scanf.scanf "%d" @@ fun n ->
  Array.init (n - 1) (fun a -> a + 1, n - a - 1)
  |> Array.map (fun (a, b) -> digits_sum a + digits_sum b)
  |> Array.fold_left min max_int
  |> Printf.printf "%d\n"


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

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

Score : 700 points

Problem Statement

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

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

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

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

Constraints

1 ≤ N ≤ 3×10^5

1 ≤ A,B ≤ 3×10^5

0 ≤ K ≤ 18×10^{10}

All values in the input are integers.

Input

Input is given from Standard Input in the following format:

N A B K

Output

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

Sample Input 1

4 1 2 5

Sample Output 1

40

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

1 green, 1 blue

1 red, 2 blues

2 reds, 1 green

3 reds, 1 blue

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

Sample Input 2

2 5 6 0

Sample Output 2

1

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

Sample Input 3

90081 33447 90629 6391049189

Sample Output 3

577742975


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

Score : 100 points

Problem Statement

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

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

3 1

Sample Output 1

4

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

Sample Input 2

4 -2

Sample Output 2

6

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

Sample Input 3

0 0

Sample Output 3

0


open Printf
open Scanf
open BatPervasives

(*open Core*)

(*let map2 f a1 a2 = Array.of_list (List.map2 f (Array.to_list a1) (Array.to_list a2))*)

let count (s1, s2) =
  let count_array s =
    let toi x = int_of_char x - int_of_char 'a' in
    let a = BatArray.create (toi 'z' + 1) 0 in
    BatString.iter (fun x -> a.(toi x) <- 1) s;
    a in
  let a1 = count_array s1 in
  let a2 = count_array s2 in
  let b = BatArray.map2 (fun a b ->
      match (a, b) with
      | (1, 1) -> 1
      | _ -> 0
    ) a1 a2 in
  BatArray.fold_left (+) 0 b

let split_string s i length =
  let s1 = String.sub s 0 i in
  let s2 = String.sub s i (length - i) in
  (s1, s2)

let main =
  let (length, s) = scanf "%d\n%s" (fun a b -> (a, b)) in
  let rec iter i v =
    match i with
    | i when i = length -> v
    | i -> iter (i + 1) (max (count (split_string s i length)) v) in
  let init = count (split_string s 1 length) in
  printf "%d\n" (iter 2 init)

Score : 200 points

Problem Statement

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

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

6
aabbca

Sample Output 1

2

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

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

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

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


let result = ref 1000000
let () =
  let n = Scanf.scanf "%d " (fun x -> x) in
  let s = Array.init n (fun _ -> Scanf.scanf "%c"
                                  (fun x -> x)) in
  for i = 0 to (n-1) do
    let left = Array.sub s 0 i in
    let right = Array.sub s (i+1) (n-i-1)  in
    let left' = Array.to_list left in
    let right' = Array.to_list right in
    let res_l =
      List.fold_left (fun sum x ->
          match x with
          | 'W' -> sum + 1
          | 'E' -> sum) 0 left' in
    let res_r =
      List.fold_left (fun sum x ->
          match x with
          | 'E' -> sum + 1
          | 'W' -> sum) 0 right' in
    let res = res_l + res_r in
    if res < !result then
      result := res
    else
      ()
  done;
  Printf.printf "%d\n" !result

Score : 300 points

Problem Statement

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

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

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

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

5
WEEWW

Sample Output 1

1

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

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


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

let unfair = Int.pow 10 18
let a, b, c, k = Scanf.sscanf (read_line ()) "%d %d %d %d" ( fun a b c k -> a, b, c, k)

let rec f a b c k =
        let ans =
                (
                        if k = 0 then
                                a - b
                        else
                        if k = 1 then
                                (b + c) - (a + c)
                        else
                        if k = 2 then
                                (2 * a + (b + c)) - (2 * b + (a + c))
                        else
                                let ki = 3 + 2 * (k - 3) in
                                        (2 * (ki - 2) * a + ki * (b + c)) - (2 * (ki - 2) * b + ki * (a + c))
                ) in
                if abs ans > unfair then
                        "Unsafe"
                else
                        string_of_int ans

let () =
        f a b c k
        |> Printf.printf "%s\n"

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

1 \leq A,B,C \leq 10^9

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


Scanf.scanf "%d" (fun n ->
    let len = Array.make n 0 in
    for i = 1 to n do
        Scanf.scanf " %d" (fun p ->
            let p = p - 1 in
            len.(p) <- 1;
            if p > 0 && len.(p - 1) > 0 then (
                len.(p) <- len.(p - 1) + 1;
                len.(p - 1) <- 0
            )
        )
    done;
    Printf.printf "%d\n" @@ n - Array.fold_left max 0 len
)

Score : 500 points

Problem Statement

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

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

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

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1
:
P_N

Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4

Sample Output 1

2

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

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

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

Sample Input 2

6
3
2
5
1
4
6

Sample Output 2

4

Sample Input 3

8
6
3
1
2
7
4
8
5

Sample Output 3

5


Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let rec loop i expect acc =
        if i = 0 then (if expect = 0 then acc else -1) else
            if a.(i) < expect then -1 else
                loop (i - 1) (max 0 (a.(i) - 1)) (if expect = a.(i) then acc else acc + a.(i))
    in
    loop (n - 1) 0 0 |> Printf.printf "%d\n"
)

Score : 700 points

Problem Statement

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

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

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

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

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

Sample Input 1

4
0
1
1
2

Sample Output 1

3

We can make X equal to A as follows:

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

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

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

Sample Input 2

3
1
2
1

Sample Output 2

-1

Sample Input 3

9
0
1
1
0
1
2
2
1
2

Sample Output 3

8


let a = ref 0 and b = ref 0 and c = ref 0 and d = ref 0 in
    Scanf.sscanf (read_line ()) "%d %d %d %d" (fun w x y z -> a := w; b := x; c := y; d := z);
    if !b - !c <= !d then begin if !a - !b <= !d then print_string "Yes" else print_string "No" end else print_string "No"; print_string "\n"

Score : 100 points

Problem Statement

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

Constraints

1 ≤ a,b,c ≤ 100

1 ≤ d ≤ 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

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

Sample Input 1

4 7 9 3

Sample Output 1

Yes

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

Sample Input 2

100 10 1 2

Sample Output 2

No

They cannot communicate in this case.

Sample Input 3

10 10 10 1

Sample Output 3

Yes

There can be multiple people at the same position.

Sample Input 4

1 100 2 10

Sample Output 4

Yes


open Batteries

let sqrt_int x = int_of_float @@ sqrt @@ float_of_int x

let pow_below n x =
  let rec aux acc  =
    if acc > x then []
    else
      acc :: (aux @@ ( * ) n acc)
  in
  aux n

let lower_than x =
  let num_exp_below =
    let rec aux n =
      if n =1 then
        [1]
      else
        (pow_below n x) @ (aux @@ pred n)
    in
    let num = sqrt_int x in
    List.sort compare @@ aux num in
  num_exp_below

let main () =
  int_of_string @@ input_line stdin
  |> lower_than
  |> List.rev
  |> List.hd
  |> print_int

let () = main ()

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


module Ss = Set.Make(String)

let s = read_line ()
let len = String.length s
let k = read_int ()

let f i j set =
  let sub = String.sub s i j in
  if (Ss.mem sub set) then set
  else (Ss.add sub set)

let rec inner i j set =
  if j <= k then
    let set' = f i j set in
    inner i (succ j) set'
  else
    set

let rec outer i set =
  if i <= (len - 1) then
    let set' = inner i 1 set in
    outer (succ i) set'
  else
    set

let () =
  let ls = outer 0 Ss.empty |> Ss.elements in
  let ar = Array.of_list ls in
  let () = Array.fast_sort String.compare ar in
  print_endline ar.(k-1)

Score : 300 points

Problem Statement

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

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

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

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

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

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

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

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


let () =
  Scanf.scanf "%d %d" @@ fun n m ->
  let uf = Array.make (n+1) (-1) in
  let rec find x =
    if uf.(x) < 0 then x else begin
      let x' = find uf.(x) in
      uf.(x) <- x'; x'
    end in
  let unite x y =
    let x, y = find x, find y in
    if x <> y then begin
      if uf.(x) < uf.(y) then (
        uf.(x) <- uf.(x) + uf.(y); uf.(y) <- x
      ) else (
        uf.(y) <- uf.(x) + uf.(y); uf.(x) <- y)
    end in
  let same x y = find x = find y in

  let p = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  for _ = 1 to m do Scanf.scanf " %d %d" unite done;

  Array.init n (fun i -> if same (i+1) p.(i) then 1 else 0)
  |> Array.fold_left (+) 0 |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:

Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.

Find the maximum possible number of i such that p_i = i after operations.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

p is a permutation of integers from 1 through N.

1 ≤ x_j,y_j ≤ N

x_j ≠ y_j

If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the maximum possible number of i such that p_i = i after operations.

Sample Input 1

5 2
5 3 1 4 2
1 3
5 4

Sample Output 1

2

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

Sample Input 2

3 2
3 2 1
1 2
2 3

Sample Output 2

3

If we perform the operation by, for example, choosing j=1, j=2, j=1 in this order, p becomes 1 2 3, which is obviously optimal.
Note that we may choose the same j any number of times.

Sample Input 3

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

Sample Output 3

8

Sample Input 4

5 1
1 2 3 4 5
1 5

Sample Output 4

5

We do not have to perform the operation.


module CharMap = Map.Make (Char)

let () =
  let s = read_line () in
  Array.init (String.length s) (fun i -> i, s.[i])
  |> Array.fold_left (fun m (i, c) ->
      CharMap.add c (i :: try CharMap.find c m with Not_found -> []) m) CharMap.empty
  |> CharMap.bindings
  |> List.map (fun (_, is) ->
      List.map (fun i ->
        Array.init 5 (fun n ->
          try [String.init (n + 1) (fun j -> s.[i + j])]
          with _ -> [])
        |> Array.to_list
        |> List.concat) is |> List.concat)
  |> List.concat
  |> List.sort_uniq compare
  |> Scanf.scanf "%d\n" (fun k l -> List.nth l (k - 1))
  |> print_endline


let () = Scanf.scanf "%d\n" @@ fun n ->
  let cas = Array.init (2 * n) @@ fun _ -> Scanf.scanf "%c %d\n" @@ fun c a -> c, a in
  let inv_ws = Array.make n 0 in
  let inv_bs = Array.make n 0 in
  let acc_ws = Array.make_matrix (2 * n + 1) (n + 1) 0 in
  let acc_bs = Array.make_matrix (2 * n + 1) (n + 1) 0 in
  for i = 2 * n - 1 downto 0 do
    begin match cas.(i) with
    | ('W', a) ->
        inv_ws.(a - 1) <- i;
        acc_ws.(i).(a) <- 1 + acc_ws.(i).(a)
    | ('B', a) ->
        inv_bs.(a - 1) <- i;
        acc_bs.(i).(a) <- 1 + acc_bs.(i).(a)
    end;
    for j = 1 to n do
      acc_ws.(i).(j) <- acc_ws.(i).(j) + acc_ws.(i).(j - 1);
      acc_bs.(i).(j) <- acc_bs.(i).(j) + acc_bs.(i).(j - 1)
    done;
    for j = 0 to n do
      acc_ws.(i).(j) <- acc_ws.(i).(j) + acc_ws.(i + 1).(j);
      acc_bs.(i).(j) <- acc_bs.(i).(j) + acc_bs.(i + 1).(j)
    done
  done;
  let dp = Array.make_matrix (n + 1) (n + 1) max_int in
  dp.(0).(0) <- 0;
  for w = 1 to n do
    dp.(w).(0) <- dp.(w - 1).(0) - w + 1
      + inv_ws.(w - 1)
      + acc_ws.(inv_ws.(w - 1) + 1).(w)
  done;
  for b = 1 to n do
    dp.(0).(b) <- dp.(0).(b - 1) - b + 1
      + inv_bs.(b - 1)
      + acc_bs.(inv_bs.(b - 1) + 1).(b)
  done;
  for w = 1 to n do
    for b = 1 to n do
      dp.(w).(b) <- min
        ( dp.(w - 1).(b) + inv_ws.(w - 1)
          + acc_ws.(inv_ws.(w - 1) + 1).(w)
          + acc_bs.(inv_ws.(w - 1) + 1).(b) )
        ( dp.(w).(b - 1) + inv_bs.(b - 1)
          + acc_ws.(inv_bs.(b - 1) + 1).(w)
          + acc_bs.(inv_bs.(b - 1) + 1).(b) ) - w - b + 1
    done
  done;
  Printf.printf "%d\n" @@ dp.(n).(n)

Score : 600 points

Problem Statement

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

Takahashi the human wants to achieve the following objective:

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

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

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

Swap two adjacent balls.

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

Constraints

1 ≤ N ≤ 2000

1 ≤ a_i ≤ N

c_i = W or c_i = B.

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

4

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

Swap the black 3 and white 1.

Swap the white 1 and white 2.

Swap the black 3 and white 3.

Swap the black 3 and black 2.

Sample Input 2

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

Sample Output 2

18

Sample Input 3

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

Sample Output 3

41


module MultiSet = struct
  (* 多重集合 *)

  module type OrderedType =
    sig
      type t
      val compare: t -> t -> int
    end

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

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

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

      let empty = Empty

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      let rec min_elt t = fst (count_min_elt t)

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

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

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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let cas = Array.init (2 * n) @@ fun _ -> Scanf.scanf "%c %d\n" @@ fun c a -> c, a in
  let inv_ws = Array.make n 0 in
  let inv_bs = Array.make n 0 in
  let acc_ws = Array.make (2 * n + 1) IntMultiSet.empty in
  let acc_bs = Array.make (2 * n + 1) IntMultiSet.empty in
  for i = 2 * n - 1 downto 0 do
    match cas.(i) with
    | ('W', a) ->
        inv_ws.(a - 1) <- i;
        acc_ws.(i) <- IntMultiSet.add (a - 1) 1 acc_ws.(i + 1);
        acc_bs.(i) <- acc_bs.(i + 1)
    | ('B', a) ->
        inv_bs.(a - 1) <- i;
        acc_ws.(i) <- acc_ws.(i + 1);
        acc_bs.(i) <- IntMultiSet.add (a - 1) 1 acc_bs.(i + 1)
  done;
  let dp = memoize ((n + 1) * (n + 1)) @@ fun dp (w, b) ->
    if w = 0 && b = 0 then 0
    else min
      (if w = 0 then max_int else
        dp (w - 1, b) + inv_ws.(w - 1) - w - b + 1
        + IntMultiSet.count_lt w acc_ws.(inv_ws.(w - 1) + 1)
        + IntMultiSet.count_lt b acc_bs.(inv_ws.(w - 1) + 1))
      (if b = 0 then max_int else
        dp (w, b - 1) + inv_bs.(b - 1) - w - b + 1
        + IntMultiSet.count_lt w acc_ws.(inv_bs.(b - 1) + 1)
        + IntMultiSet.count_lt b acc_bs.(inv_bs.(b - 1) + 1)) in
  Printf.printf "%d\n" @@ dp (n, n)


open Batteries

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

  print_endline (string_of_int (if a > b then a-1 else a))

Score: 100 points

Problem Statement

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

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

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

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

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

a b

Output

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

Sample Input 1

5 5

Sample Output 1

5

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

Sample Input 2

2 1

Sample Output 2

1

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

Sample Input 3

11 30

Sample Output 3

11

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


let s, m, k = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> a + b + c, max a (max b c), d
let _ = s - m + m * 1 lsl k |> Printf.printf "%d\n"

Score: 200 points

Problem Statement

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

A, B and C are integers between 1 and 50 (inclusive).

K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Sample Input 1

5 3 11
1

Sample Output 1

30

In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once.

There are three choices:

Double 5: The integers written on the board after the operation are 10, 3, 11.

Double 3: The integers written on the board after the operation are 5, 6, 11.

Double 11: The integers written on the board after the operation are 5, 3, 22.

If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 3.

Sample Input 2

3 3 4
2

Sample Output 2

22

E869120 can perform the operation twice. The sum of the integers eventually written on the blackboard is maximized as follows:

First, double 4. The integers written on the board are now 3, 3, 8.

Next, double 8. The integers written on the board are now 3, 3, 16.

Then, the sum of the integers eventually written on the blackboard is 3 + 3 + 16 = 22.


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


open Batteries

let () =
  let h, w = Scanf.scanf "%d %d\n" (fun a b -> a, b) in
  let arr = Array.make h (Array.make w "") in
  for i = 0 to h-1 do
    let str = Scanf.scanf "%s\n" (fun a -> a) in
    let str_list = Str.split (Str.regexp "") str in
    arr.(i) <- (Array.of_list str_list)
  done;

  let res = ref true in

  for i = 0 to h-1 do
    for j = 0 to w-1 do
      if arr.(i).(j) = "#" then (
        let tmp = ref false in
        if i <> 0 then (
          if arr.(i-1).(j) = "#" then tmp := true;
        );
        if i <> h-1 then (
          if arr.(i+1).(j) = "#" then tmp := true;
        );
        if j <> 0 then (
          if arr.(i).(j-1) = "#" then tmp := true;
        );
        if j <> w-1 then (
          if arr.(i).(j+1) = "#" then tmp := true;
        );
        if !tmp = false then res := false
      );
    done;
  done;

  print_endline (if !res then "Yes" else "No")

Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
: :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


open Batteries
module CountDict = Map.Make(Int)
let cnt_int lst =
  let rec add_lst dict l =
    match l with
    | [] -> dict
    | first :: rest ->
      if CountDict.mem first dict then add_lst (CountDict.add first ((CountDict.find first dict) + 1) dict) rest else
      add_lst (CountDict.add first 1 dict) rest
  in add_lst CountDict.empty lst
let n = read_int ()
let a = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ fun a -> a
let dp = Array.init (n+1) (fun _ -> 0)

let rec loop i =
  if i >= n then () else (dp.(i+1) <- dp.(i) + a.(i); loop (i+1))

let _ = dp.(1) <- a.(0); loop 1

let dict = cnt_int @@ Array.to_list dp

let _ = Printf.printf "%d\n" @@ (CountDict.fold (fun f m a -> a + (m * (m - 1))) dict 0) / 2

Score : 200 points

Problem Statement

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

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

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

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

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

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

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are 0.


module P = Map.Make(struct type t = int let compare = (-) end)
let _ = Scanf.scanf "%d" @@ fun n ->
  Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0))
  |> Array.fold_left (fun (v, (s, m)) x ->
      let c = try P.find (s+x) m with | _ -> 0 in
      (v+c, (s+x, P.add (s+x) (c+1) m))) (0, (0, P.singleton 0 1))
  |> fst |> Printf.printf "%d\n"


Scanf.sscanf (read_line ()) "%d" (fun n ->
    let s = Array.init n (fun _ -> read_line ()) in
    let check1 sh =
        let rec loop y =
            let rec loop2 x =
                if x = n then true else
                    if s.(y).[(x + sh) mod n] = s.(x).[(y + sh) mod n] then loop2 (x + 1) else (
                        false
                    )
            in
            if y = n then true else
                if loop2 0 then loop (y + 1) else false
        in
        loop 0
    in
    let rec loop sh acc =
        if sh = n then acc * n else
            let acc = if check1 sh then acc + 1 else acc in
            loop (sh + 1) acc
    in
    loop 0 0 |> Printf.printf "%d\n"
)

Score : 500 points

Problem Statement

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

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

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

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

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

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

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

Constraints

1 \leq N \leq 300

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2
ab
ca

Sample Output 1

2

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

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

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

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

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

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


open Batteries

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

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

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

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

  print_endline (string_of_int !cnt)


let () =
  Scanf.scanf "%1s%1s%1s" (fun a b c ->
      let rec calc li o =
        match li with
        | [] -> o
        | x :: xs when x = "o" -> calc xs (o + 1)
        | x :: xs -> calc xs o
      in
      (calc [a; b; c] 0 * 100) + 700 |> Printf.printf "%d\n" )

Score : 100 points

Problem Statement

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

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

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

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

oxo

Sample Output 1

900

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

Sample Input 2

ooo

Sample Output 2

1000

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

Sample Input 3

xxx

Sample Output 3

700

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


Scanf.scanf "%d %d" (fun n x ->
    let m = Array.init n (fun _ -> Scanf.scanf " %d" (fun m -> m)) in
    Array.sort compare m;
    let s = Array.fold_left (+) 0 m in
    let r = x - s in
    Printf.printf "%d\n" @@ n + r / m.(0)
)

Score : 200 points

Problem Statement

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

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

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

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

Constraints

2 ≤ N ≤ 100

1 ≤ m_i ≤ 1000

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
m_1
m_2
:
m_N

Output

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

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

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

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

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

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26


let () =
  let n, x = Scanf.scanf "%d %d\n" (fun n x -> n, x) in
  let mi = Array.init n (fun _ -> Scanf.scanf "%d\n" (fun x -> x)) in
  Array.sort (-) mi;
  let least = Array.fold_left (+) 0 mi in
  let count = (x - least) / mi.(0) in
  let res = n + count in
  Printf.printf "%d\n" res


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

let (a,b,c,x,y) = scan "%d %d %d %d %d" Tuple5.make

let () =
  [a*x + b*y; 2 * c * (max x y);
   2*c*(min x y) + a*(x- min x y) + b*(y- min x y)]
  |> List.min
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

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

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

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

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

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

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

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

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

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

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


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

  let a1 =
    if x < y
    then c * 2 * x + b * (y - x)
    else c * 2 * y + a * (x - y)
  in
  let a2 = a * x + b * y in
  let a3 = c * 2 * (if x > y then x else y) in

  print_endline (string_of_int (min a1 (min a2 a3)))