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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let vs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun v -> v in
  let (odds, evens) =
    Array.fold_left (fun (odds, evens) v ->
      (evens, IntMap.add v (1 + try IntMap.find v odds with Not_found -> 0) odds))
    (IntMap.empty, IntMap.empty) vs in
  Printf.printf "%d\n" @@ ( - ) n @@
  match
    List.sort (fun (_, x) (_, y) -> compare y x) @@
    IntMap.bindings odds,
    List.sort (fun (_, x) (_, y) -> compare y x) @@
    IntMap.bindings evens
  with
  | [(u, l)], [(v, m)] ->
      if u = v then max l m else l + m
  | (u, l) :: (_, m) :: _, [(v, n)] ->
      if u = v then max l (m + n) else l + n
  | [(u, l)], (v, m) :: (_, n) :: _ ->
      if u = v then max (l + n) m else l + m
  | (u, l) :: (_, m) :: _, (v, n) :: (_, o) :: _ ->
      if u = v then max (l + o) (m + n) else l + n


open Printf
open Scanf

let id x = x
let pair x y = x, y

let n = scanf "%d" id
let vs = Array.init n @@ fun _ -> scanf " %d" id

module IMap = Map.Make(struct type t = int let compare = Pervasives.compare end)

let odd = ref IMap.empty
let even = ref IMap.empty

let incrmap mapr key =
  if IMap.mem key !mapr then
    mapr := IMap.add key (IMap.find key !mapr + 1) !mapr
  else
    mapr := IMap.add key 1 !mapr

let maxi mapr =
  let lis = IMap.bindings !mapr in
  let lis = List.sort (fun (k1,v1) (k1,v2) -> v2 - v1) lis in
  match lis with
  | [] -> failwith ""
  | (v, n) :: rest -> (v, n, rest)

let () =
  for i = 0 to n - 1 do
    if i mod 2 == 0 then begin
      incrmap odd vs.(i)
    end else begin
      incrmap even vs.(i)
    end
  done;
  let (k1, v1, rest1) = maxi odd in
  let (k2, v2, rest2) = maxi even in
  let run k1 k2 v1 v2 rest1 rest2 =
    if k1 <> k2 then begin
      let n1 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest1 in
      let n2 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest2 in
      n1 + n2
    end else if v1 > v2 then begin
      let n1 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest1 in
      match rest2 with
      | [] -> n1 + n / 2
      | (k, v) :: _ -> n1 + n / 2 - v
    end else if v1 < v2 then begin
      let n2 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest2 in
      match rest1 with
      | [] -> n2 + n / 2
      | (k, v) :: _ -> n2 + n / 2 - v
    end else begin
      (* k1 = k2, v1 = v2 *)
      let rec loop rest1 rest2 =
        match rest1, rest2 with
        | [], [] -> 0
        | [], (k', v') :: rest' -> v'
        | (k', v') :: rest', [] -> v'
        | (k1', v1') :: rest1', (k2', v2') :: rest2' ->
          if v1' < v2' then
            let n1 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest1' in
            let n2 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest2' in
            n1 + n2 + (v1 - v1')
          else if v1' > v2' then
            let n1 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest1' in
            let n2 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest2' in
            n1 + n2 + (v1 - v2')
          else n / 0 (* loop rest1' rest2' *)
      in
      v1 + loop rest1 rest2
    end
  in
  let result = run k1 k2 v1 v2 rest1 rest2 in
  printf "%d\n" result

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

Score : 300 points

Problem Statement

A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied:

For each i = 1,2,..., n-2, a_i = a_{i+2}.

Exactly two different numbers appear in the sequence.

You are given a sequence v_1,v_2,...,v_n whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

2 \leq n \leq 10^5

n is even.

1 \leq v_i \leq 10^5

v_i is an integer.

Input

Input is given from Standard Input in the following format:

n
v_1 v_2 ... v_n

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence 3,1,3,2 is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it 3,1,3,1.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence 105,119,105,119,105,119 is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence 1,1,1,1 are all the same, so it is not /\/\/\/.

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 id x = x
let pair x y = x, y

let n = scanf "%d" id
let vs = Array.init n @@ fun _ -> scanf " %d" id

module IMap = Map.Make(struct type t = int let compare = Pervasives.compare end)

let odd = ref IMap.empty
let even = ref IMap.empty

let incrmap mapr key =
  if IMap.mem key !mapr then
    mapr := IMap.add key (IMap.find key !mapr + 1) !mapr
  else
    mapr := IMap.add key 1 !mapr

let maxi mapr =
  let lis = IMap.bindings !mapr in
  let lis = List.sort (fun (k1,v1) (k1,v2) -> v2 - v1) lis in
  match lis with
  | [] -> failwith ""
  | (v, n) :: rest -> (v, n, rest)

let () =
  for i = 0 to n - 1 do
    if i mod 2 == 0 then begin
      incrmap odd vs.(i)
    end else begin
      incrmap even vs.(i)
    end
  done;
  let (k1, v1, rest1) = maxi odd in
  let (k2, v2, rest2) = maxi even in
  let run k1 k2 v1 v2 rest1 rest2 =
    if k1 <> k2 then begin
      let n1 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest1 in
      let n2 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest2 in
      n1 + n2
    end else if v1 > v2 then begin
      let n1 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest1 in
      match rest2 with
      | [] -> n1 + n / 2
      | (k, v) :: _ -> n1 + n / 2 - v
    end else if v1 < v2 then begin
      let n2 = List.fold_left (fun acc (v, n) -> acc + n) 0 rest2 in
      match rest1 with
      | [] -> n2 + n / 2
      | (k, v) :: _ -> n2 + n / 2 - v
    end else begin
      (* k1 = k2, v1 = v2 *)
      let rec loop rest1 rest2 =
        match rest1, rest2 with
        | [], [] -> 0
        | [], (k', v') :: rest' -> v'
        | (k', v') :: rest', [] -> v'
        | (k1', v1') :: rest1', (k2', v2') :: rest2' ->
          if v1' < v2' then v1 - v1'
          else if v1' > v2' then v1 - v2'
          else loop rest1' rest2'
      in
      v1 + loop rest1 rest2
    end
  in
  let result = run k1 k2 v1 v2 rest1 rest2 in
  printf "%d\n" result


module CharSet = Set.Make (Char)

let () =
  let s = read_line () in
  let t = read_line () in
  let a = Array.make 26 CharSet.empty in
  let b = Array.make 26 CharSet.empty in
  let ix c = Char.code c - Char.code 'a' in
  for i = 0 to String.length s - 1 do
    if s.[i] <> t.[i] then begin
      a.(ix s.[i]) <- CharSet.add t.[i] a.(ix s.[i]);
      b.(ix t.[i]) <- CharSet.add s.[i] b.(ix t.[i])
    end
  done;
  print_endline @@
  if
    List.for_all (List.for_all (fun s -> CharSet.cardinal s <= 1)) @@
    List.map Array.to_list [a; b]
  then "Yes"
  else "No"

Score : 300 points

Problem Statement

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

You can perform the following operation on S any number of times:

Operation: Choose two distinct lowercase English letters c_1 and c_2, then replace every occurrence of c_1 with c_2, and every occurrence of c_2 with c_1.

Determine if S and T can be made equal by performing the operation zero or more times.

Constraints

1 \leq |S| \leq 2 \times 10^5

|S| = |T|

S and T consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

If S and T can be made equal, print Yes; otherwise, print No.

Sample Input 1

azzel
apple

Sample Output 1

Yes

azzel can be changed to apple, as follows:

Choose e as c_1 and l as c_2. azzel becomes azzle.

Choose z as c_1 and p as c_2. azzle becomes apple.

Sample Input 2

chokudai
redcoder

Sample Output 2

No

No sequences of operation can change chokudai to redcoder.

Sample Input 3

abcdefghijklmnopqrstuvwxyz
ibyhqfrekavclxjstdwgpzmonu

Sample Output 3

Yes


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

    let rec loop i acc =
        if i = n then (if acc = x then i else i - 1) else
            if acc + a.(i) <= x then loop (i + 1) (acc + a.(i)) else i
    in
    loop 0 0 |> Printf.printf "%d\n"
)

Score : 200 points

Problem Statement

There are N children, numbered 1, 2, ..., N.

Snuke has decided to distribute x sweets among them.
He needs to give out all the x sweets, but some of the children may get zero sweets.

For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

2 \leq N \leq 100

1 \leq x \leq 10^9

1 \leq a_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N x
a_1 a_2 ... a_N

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is (20, 30, 20).

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is (0, 0, 10).

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is (1, 10, 100, 1000).

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.


open Batteries

let calc x li =
  let rec aux c sum = function
    | [] when sum = x -> c
    | [] -> c - 1
    | a :: al when a + sum > x -> c
    | a :: al -> aux (1 + c) (a + sum) al
  in
  aux 0 0 li

let () =
  Scanf.scanf " %d %d " (fun n x ->
      List.init n (fun _ -> Scanf.scanf " %d" (fun x -> x))
      |> List.sort (fun x y -> x - y)
      |> calc x |> Printf.printf "%d\n" )


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 %d\n" @@ fun n x ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Array.sort compare as_;
  let acc = Array.make (n + 1) 0 in
  for i = 0 to n - 1 do
    acc.(i + 1) <- acc.(i) + as_.(i)
  done;
  Printf.printf "%d\n" @@
    if acc.(n) < x then n - 1
    else if x = acc.(n) then n
    else upper_bound 0 (n + 1) @@ fun i -> acc.(i) <= x


let (h, w) = Scanf.scanf "%d %d" (fun x y -> (x, y)) in
let a = Array.make h (Array.make w 0) in
for i = 0 to h - 1 do
  for j = 0 to w - 1 do
    a.(i).(j) <- Scanf.scanf (if j = 0 then "\n%d" else " %d") (fun x -> x)
  done
done;
let ans = ref [] in
for i = 0 to h - 2 do
  for j = 0 to w - 1 do
    if a.(i).(j) mod 2 = 1 then begin
      a.(i).(j) <- a.(i).(j) - 1;
      a.(i + 1).(j) <- a.(i + 1).(j) + 1;
      ans := (i, j, i + 1, j)::!ans
    end
  done
done;
for j = 0 to w - 2 do
  if a.(h - 1).(j) mod 2 = 1 then begin
    a.(h - 1).(j) <- a.(h - 1).(j) - 1;
    a.(h - 1).(j + 1) <- a.(h - 1).(j + 1) + 1;
    ans := (h - 1, j, h - 1, j + 1)::!ans
  end
done;
let ans = List.rev !ans in
print_int (List.length ans);
print_newline ();
ans |> List.iter (fun (y1, x1, y2, x2) -> Printf.printf "%d %d %d %d\n" (y1 + 1) (x1 + 1) (y2 + 1) (x2 + 1));;

Score : 400 points

Problem Statement

There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).

In Cell (i, j), a_{ij} coins are placed.

You can perform the following operation any number of times:

Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.

Maximize the number of cells containing an even number of coins.

Constraints

All values in input are integers.

1 \leq H, W \leq 500

0 \leq a_{ij} \leq 9

Input

Input is given from Standard Input in the following format:

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

Output

Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:

N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'

That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.

In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').

Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.

Sample Input 1

2 3
1 2 3
0 1 1

Sample Output 1

3
2 2 2 3
1 1 1 2
1 3 1 2

Every cell contains an even number of coins after the following sequence of operations:

Move the coin in Cell (2, 2) to Cell (2, 3).

Move the coin in Cell (1, 1) to Cell (1, 2).

Move one of the coins in Cell (1, 3) to Cell (1, 2).

Sample Input 2

3 2
1 0
2 1
1 0

Sample Output 2

3
1 1 1 2
1 2 2 2
3 1 3 2

Sample Input 3

1 5
9 9 9 9 9

Sample Output 3

2
1 1 1 2
1 3 1 4


let rec for_fold a b v f = if a >= b then v else for_fold (a+1) b (f v a) f

let rec print_trace = function
  | (a,b)::(c,d)::xs -> (
    Printf.printf "%d %d %d %d\n" (a+1) (b+1) (c+1) (d+1);
    print_trace ((c,d)::xs)
  )
  | _ -> ()

let () =
  Scanf.scanf "%d %d" @@ fun h w ->
  let a = Array.init h (fun _ -> Array.init w (fun _ -> Scanf.scanf " %d" ((+) 0))) in

  let moves, _ = for_fold 0 (h*w) ([], None) (fun (ac, tr) i ->
    let x = i / w in
    let y = if x mod 2 = 0 then i mod w else (w-1) - i mod w in
    match tr with
    | None ->
      if a.(x).(y) mod 2 = 1 then (ac, Some [(x, y)]) else (ac, None)
    | Some tr -> begin
      if a.(x).(y) mod 2 = 1 then (List.rev ((x,y)::tr) :: ac, None) else (ac, Some ((x,y)::tr))
    end)
  in

  let moves = List.rev moves in

  let n = List.fold_left (fun n x -> n + List.length x - 1) 0 moves in
  Printf.printf "%d\n" n;
  List.iter print_trace moves


Scanf.scanf "%d" (fun k ->
    Printf.printf "%d\n" @@ (k / 2) * (k - k / 2)
)

Score : 100 points

Problem Statement

Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.

Constraints

2\leq K\leq 100

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive).

Sample Input 1

3

Sample Output 1

2

Two pairs can be chosen: (2,1) and (2,3).

Sample Input 2

6

Sample Output 2

9

Sample Input 3

11

Sample Output 3

30

Sample Input 4

50

Sample Output 4

625


let () = Scanf.scanf "%d" (fun k -> k / 2 * (k - k / 2)) |> Printf.printf "%d\n"


let k = read_int ()
let _ = Printf.printf "%d\n" @@ k/2 * (k - k/2)


let f n = match n with
n when (mod) n 2 = 0 -> (n/2)*(n/2)
| n -> (((n-1)/2)+1)*((n-1)/2);;
let () = Scanf.scanf "%d" f
|> Printf.printf "%d\n"


Scanf.scanf "%d %d %d %d" (fun x1 y1 x2 y2 ->
    let rot_x cx cy x y =  y + cx - cy in
    let rot_y cx cy x y = -x + cy + cx in
    let x3 = rot_x x2 y2 x1 y1 in
    let y3 = rot_y x2 y2 x1 y1 in
    let x4 = rot_x x3 y3 x2 y2 in
    let y4 = rot_y x3 y3 x2 y2 in
    Printf.printf "%d %d %d %d\n" x3 y3 x4 y4
)

Score : 200 points

Problem Statement

There is a square in the xy-plane. The coordinates of its four vertices are (x_1,y_1),(x_2,y_2),(x_3,y_3) and (x_4,y_4) in counter-clockwise order.
(Assume that the positive x-axis points right, and the positive y-axis points up.)

Takahashi remembers (x_1,y_1) and (x_2,y_2), but he has forgot (x_3,y_3) and (x_4,y_4).

Given x_1,x_2,y_1,y_2, restore x_3,y_3,x_4,y_4. It can be shown that x_3,y_3,x_4 and y_4 uniquely exist and have integer values.

Constraints

|x_1|,|y_1|,|x_2|,|y_2| \leq 100

(x_1,y_1) ≠ (x_2,y_2)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

x_1 y_1 x_2 y_2

Output

Print x_3,y_3,x_4 and y_4 as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

(0,0),(0,1),(-1,1),(-1,0) is the four vertices of a square in counter-clockwise order.
Note that (x_3,y_3)=(1,1),(x_4,y_4)=(1,0) is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131


let x1, y1, x2, y2, x, y = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> a, b, c, d, c - a, d - b
let _ = Printf.printf "%d %d %d %d\n" (x2 - y) (y2 + x) (x1 - y) (y1 + x)


let train n i = n - i + 1

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

Score : 100 points

Problem Statement

There is an N-car train.

You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."

Constraints

1 \leq N \leq 100

1 \leq i \leq N

Input

Input is given from Standard Input in the following format:

N i

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a 4-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5


let () = Scanf.scanf "%d %d" @@ fun n i ->
  Printf.printf "%d\n" @@ n - i + 1


let rec for_fold a b v f = if a >= b then v else for_fold (a+1) b (f a v) f
let () =
  Scanf.scanf "%d %d" @@ fun n k ->
  let x = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  for_fold 0 (n-k+1) 10101010101010 (fun i v ->
    let l, r = x.(i), x.(i+k-1) in
    if r <= 0 || l >= 0 then min v @@ max (abs l) (abs r)
    else min v @@ min (2 * r - l) (r - 2 * l))
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

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

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

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

Find the minimum time required to light K candles.

Constraints

1 \leq N \leq 10^5

1 \leq K \leq N

x_i is an integer.

|x_i| \leq 10^8

x_1 < x_2 < ... < x_N

Input

Input is given from Standard Input in the following format:

N K
x_1 x_2 ... x_N

Output

Print the minimum time required to light K candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate 0 to -10.

Light the second candle from the left.

Move from coordinate -10 to 10.

Light the third candle from the left.

Move from coordinate 10 to 20.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate 0.

Sample Input 4

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

Sample Output 4

10


let rec firstNth list n = match list with
  | [] -> []
  | _ when n = 0 -> []
  | x::rest -> x::(firstNth rest (n-1))

let solve n k list =
  let dists = List.map (fun x -> (x, abs x)) list in
  let sorted = firstNth (List.sort (fun x y -> if (snd x) < (snd y) then -1 else 1) dists) k in
  let maxL = List.fold_left (fun acc x -> max acc (fst x)) 0 sorted and
      minL = List.fold_left (fun acc x -> min acc (fst x)) 0 sorted in
  maxL - (min minL 0) + (min maxL (abs (min minL 0)))

let read_list_of_int () =
  let rec read_list_of_int_inner lst =
    try let ans = (Scanf.scanf "%d " (fun x->x)) in
        read_list_of_int_inner (ans::lst)
    with End_of_file ->
      List.rev lst
  in
  read_list_of_int_inner []

let () =
  let n, k = (Scanf.scanf "%d %d\n" (fun x y -> x,y)) in
  let list = read_list_of_int () in
  let ans = solve n k list in
  Printf.printf "%d\n" ans;
;;


open Scanf
open Printf

let garden a b = a * b - (a + b - 1)

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

Score: 100 points

Problem Statement

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

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

Note

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


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


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


open Batteries

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

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

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

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

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

let n = scan "%d" identity

let aux n =
  Enum.Labels.map (1 -- n)
    ~f:(fun i -> if n mod i = 0 then 1 else 0 )
  |> Enum.sum
  |> (=) 8

let () =
  Enum.Labels.map (1 -- n)
    ~f:(fun i -> if i mod 2 = 1 && aux i then 1 else 0)
  |> Enum.sum
  |> Printf.printf "%d\n"

Score: 200 points

Problem Statement

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

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

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

Sample Input 2

7

Sample Output 2

0

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


open Printf
open Scanf

let id x = x

let n = scanf "%d" id

let f n =
    let r = ref 0 in
    for i = 1 to n do
        if n mod i = 0 then incr r
    done;
    !r

let () =
    let r = ref 0 in
    for i = 1 to n do
        if i mod 2 = 1 && f i = 8 then incr r
    done;
    printf "%d\n" !r


let solve s _ =
  let by = Bytes.of_string s in
  let non_one = Bytes.map (fun c -> if c = '1' then ' ' else c) by in
  let trimmed = Bytes.trim non_one in
  trimmed.[0]

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

Score: 300 points

Problem Statement

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

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

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

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

S
K

Output

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

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

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

Sample Input 2

3
157

Sample Output 2

3

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

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


open Scanf
open Printf

let tail s = String.sub s 1 (String.length s - 1)
let head s = int_of_string (String.sub s 0 1)

let n = float_of_int @@ 5000 * 10000 * 10000 * 10000

let pow i n = if i = 1
  then 1
  else begin
    let rec pow' k n = if n = 1 then k else pow' (k * i) (n - 1)
    in pow' i n
  end

let rec f s k = let i = head s in
  let a = log @@ float_of_int i in
  if k < n *. a
  then i
  else f (tail s) (k +. log (1. -. exp (n *. a -. k)))

let () = let ans = scanf "%s\n%d\n" (fun s k -> f s (log @@ float_of_int k)) in
  printf "%d\n" ans


open Scanf
open Printf

let tail s = String.sub s 1 (String.length s - 1)
let head s = int_of_string (String.sub s 0 1)

let num = 5000 * 10000 * 10000 * 10000

let pow i n = if i = 1
  then 1
  else begin
    let rec pow' k n = if n = 1 then k else pow' (k * i) (n - 1)
    in pow' i n
  end

let rec f s k = let i = head s in
  if log (float_of_int k) < (float_of_int num) *. log (float_of_int i)
  then i
  else f (tail s) (k - pow i num)

let () = let ans = scanf "%s\n%d\n" f in
  printf "%d\n" ans


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


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

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

let id = identity

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

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

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

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

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

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

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

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

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

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

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

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

let (n,m,q) = scan "%d %d %d" Tuple3.make

let () =
  let mat = Array.make_matrix (succ n) (succ n) 0 in
  ListL.iter (0 ++^ m) ~f:(fun _ ->
      let (l, r) = scan "%d %d" Tuple2.make in
      mat.(r).(l) <- mat.(r).(l) + 1);
  ListL.iter (1 ++ n) ~f:(fun i ->
      List.fold_left (fun p j ->
          let p = p + mat.(i).(j) in
          mat.(i).(j) <- p + mat.(pred i).(j); p
        ) 0 (1 ++ n) |> ignore);
  ListL.iter (0 ++^ q) ~f:(fun _ ->
      let (p,q) = scan "%d %d" Tuple2.make in
      mat.(q).(q) - mat.(q).(pred p) - mat.(pred p).(q) + mat.(pred p).(pred p)
      |> Printf.printf "%d\n"
    )

Score: 400 points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and N cities along it, numbered 1, 2, 3, ..., N from west to east.
A company called AtCoder Express possesses M trains, and the train i runs from City L_i to City R_i (it is possible that L_i = R_i).
Takahashi the king is interested in the following Q matters:

The number of the trains that runs strictly within the section from City p_i to City q_i, that is, the number of trains j such that p_i \leq L_j and R_j \leq q_i.

Although he is genius, this is too much data to process by himself. Find the answer for each of these Q queries to help him.

Constraints

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

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

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

1 \leq L_i \leq R_i \leq N (1 \leq i \leq M)

1 \leq p_i \leq q_i \leq N (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N M Q
L_1 R_1
L_2 R_2
:
L_M R_M
p_1 q_1
p_2 q_2
:
p_Q q_Q

Output

Print Q lines. The i-th line should contain the number of the trains that runs strictly within the section from City p_i to City q_i.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City 1 to City 2, the answer to the only query is 3.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City 1 to 7. There is only one train that runs strictly within that section: Train 1.
The second query is on the section from City 3 to 10. There is only one train that runs strictly within that section: Train 3.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


let _ = Scanf.sscanf (read_line ()) "%d %d" (fun n k ->
  print_endline @@ string_of_int (n mod k)
)

Score : 100 points

Problem Statement

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

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

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

Sample Input 1

7 3

Sample Output 1

1

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

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


Scanf.scanf "%d" (fun n ->
    let a = Array.make (n + 1) false in
    let rec loop i =
        let rec loop2 j =
            if j <= n then (a.(j) <- true; loop2 (j + 7))
        in
        if i <= n then (loop2 i; loop (i + 4))
    in
    loop 0;
    print_endline @@ if a.(n) then "Yes" else "No"
)

Score : 200 points

Problem Statement

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

Constraints

N is an integer between 1 and 100, inclusive.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

11

Sample Output 1

Yes

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

Sample Input 2

40

Sample Output 2

Yes

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

Sample Input 3

3

Sample Output 3

No

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


let m a b = a mod b + if a mod b < 0 then abs b else 0
let rec f n a = if n = 0 then a else f ((n - m n ~-2) / -2) (m n ~-2 :: a)
let _ = print_newline @@ match f (read_int ()) [] with [] -> print_int 0 | a -> List.iter print_int a

Score : 300 points

Problem Statement

Given an integer N, find the base -2 representation of N.

Here, S is the base -2 representation of N when the following are all satisfied:

S is a string consisting of 0 and 1.

Unless S = 0, the initial character of S is 1.

Let S = S_k S_{k-1} ... S_0, then S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S_k \times (-2)^k = N.

It can be proved that, for any integer M, the base -2 representation of M is uniquely determined.

Constraints

Every value in input is integer.

-10^9 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

Print the base -2 representation of N.

Sample Input 1

-9

Sample Output 1

1011

As (-2)^0 + (-2)^1 + (-2)^3 = 1 + (-2) + (-8) = -9, 1011 is the base -2 representation of -9.

Sample Input 2

123456789

Sample Output 2

11000101011001101110100010101

Sample Input 3

0

Sample Output 3

0


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

Scanf.scanf "%d %d" (fun n m ->

    let rec loop i cur map =
        if i = n then map else
            let a = Scanf.scanf " %d" (fun a -> a) in
            let cur = (cur + a) mod m in
            let map = M.add cur (1 + try M.find cur map with _ -> 0) map in
            loop (i + 1) cur map
    in
    let map = loop 0 0 (M.add 0 1 M.empty) in
    M.fold (fun _ v acc -> acc + v * (v - 1) / 2) map 0 |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

There are N boxes arranged in a row from left to right. The i-th box from the left contains A_i candies.

You will take out the candies from some consecutive boxes and distribute them evenly to M children.

Such being the case, find the number of the pairs (l, r) that satisfy the following:

l and r are both integers and satisfy 1 \leq l \leq r \leq N.

A_l + A_{l+1} + ... + A_r is a multiple of M.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

Print the number of the pairs (l, r) that satisfy the conditions.

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

Sample Input 1

3 2
4 1 5

Sample Output 1

3

The sum A_l + A_{l+1} + ... + A_r for each pair (l, r) is as follows:

Sum for (1, 1): 4

Sum for (1, 2): 5

Sum for (1, 3): 10

Sum for (2, 2): 1

Sum for (2, 3): 6

Sum for (3, 3): 5

Among these, three are multiples of 2.

Sample Input 2

13 17
29 7 5 7 9 51 7 13 8 55 42 9 81

Sample Output 2

6

Sample Input 3

10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

25


let r = read_int () in
print_endline @@
if r < 1200 then "ABC" else
    if r < 2800 then "ARC" else "AGC"

Score : 100 points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

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

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

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

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

Constraints

0 ≤ R ≤ 4208

R is an integer.

Input

Input is given from Standard Input in the following format:

R

Output

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

Sample Input 1

1199

Sample Output 1

ABC

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

Sample Input 2

1200

Sample Output 2

ARC

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

Sample Input 3

4208

Sample Output 3

AGC


let s = read_line ()
let f g s = let n = ref 0 in String.iter (fun c -> if g c then incr n) s; !n
let _ = print_endline @@ if s.[0] = 'A' && String.(contains (sub s 2 (length s - 3)) 'C') && f (fun c -> Char.uppercase c = c) s = 2 then "AC" else "WA"

Score : 200 points

Problem Statement

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

The initial character of S is an uppercase A.

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

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

Constraints

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

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

AtCoder

Sample Output 1

AC

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

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


Str.(if string_match (regexp "^A[a-z]+C[a-z]+$") (read_line()) 0 then "AC" else "WA")


let inf = 10101010101010
let () =
  Scanf.scanf "%d %d" @@ fun d g ->
  let pc = Array.init d (fun i -> Scanf.scanf " %d %d" (fun x y -> i, x, y))
    |> Array.to_list |> List.rev in

  Array.init (1 lsl d) (fun b ->
    let s', n' =
      List.fold_left (fun (s, n) (i, p, c) ->
        if b land (1 lsl i) <> 0 then begin
          (s + p * 100 * (i+1) + c, n + p)
        end else (s, n)) (0, 0) pc
    in
    let s, n =
      List.fold_left (fun (s, n) (i, p, c) ->
      if b land (1 lsl i) <> 0 then (s, n) else begin
        let u = 100 * (i+1) in
        let m = (g - s + u - 1) / u |> min (p-1) |> max 0 in
        (s + m * u, n + m)
      end) (s', n') pc in
    if s >= g then n else inf
  ) |> Array.fold_left min inf |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

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

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

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

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

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

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

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

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

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

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

Sample Input 4

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

Sample Output 4

66

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


open Batteries
open Printf
let () =
  let s,t = Scanf.scanf "%s %s " (fun a b -> a,b) in
  let ss = s^s in
  let res =
    try (
      let _ = String.rfind ss t in true
    ) with _ -> false
  in
  Printf.printf "%s\n" @@
  if res then "Yes" else "No"

Score : 200 points

Problem Statement

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

Determine if S equals T after rotation.

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

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

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

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

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

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


let () =
  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


let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let ax = Array.init n (fun _ ->
               Scanf.scanf " %d" (fun x -> x)) in
   let res = Array.fold_left (fun res x ->
                res + x - 1
              ) 0 ax in

  Printf.printf "%d\n" res

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


let rec gcd a b =
  if b = 0 then a else gcd b (a mod b)
let rec lcm a b =
  a * b / gcd a b
let () =
    let n = Scanf.scanf "%d\n" (fun x -> x) in
  let ax = Array.init n (fun _ ->
               Scanf.scanf " %d" (fun x -> x)) in
  let l = Array.fold_left (lcm) 1 ax in
  let m = (if l = 1 then 1 else  l - 1) in
  let res = Array.fold_left (fun res x ->
                res + (m mod x)
              ) 0 ax in

  Printf.printf "%d\n" res


let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let es = Array.make n max_int in
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- min (b - 1) es.(a - 1)
  done;
  let acc = ref 0 in
  for i = 0 to n - 2 do
    if es.(i) = i + 1 then incr acc
    else es.(i + 1) <- min es.(i) es.(i + 1)
  done;
  Printf.printf "%d\n" !acc

Score : 400 points

Problem Statement

There are N islands lining up from west to east, connected by N-1 bridges.

The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west.

One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands:

Request i: A dispute took place between the a_i-th island from the west and the b_i-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these M requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq a_i < b_i \leq N

All pairs (a_i, b_i) are distinct.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
a_2 b_2
:
a_M b_M

Output

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

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

Sample Output 3

4


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

    let rec loop i acc =
        if i = n then acc else
            if a.(i) = a.(i - 1) then (
                a.(i) <- -i;
                loop (i + 1) (acc + 1)
            ) else loop (i + 1) acc
    in
    loop 1 0 |> Printf.printf "%d\n"
)

Score : 200 points

Problem Statement

Takahashi lives in another world. There are slimes (creatures) of 10000 colors in this world. Let us call these colors Color 1, 2, ..., 10000.

Takahashi has N slimes, and they are standing in a row from left to right. The color of the i-th slime from the left is a_i.
If two slimes of the same color are adjacent, they will start to combine themselves. Because Takahashi likes smaller slimes, he has decided to change the colors of some of the slimes with his magic.

Takahashi can change the color of one slime to any of the 10000 colors by one spell.
How many spells are required so that no slimes will start to combine themselves?

Constraints

2 \leq N \leq 100

1 \leq a_i \leq N

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 number of spells required.

Sample Input 1

5
1 1 2 2 2

Sample Output 1

2

For example, if we change the color of the second slime from the left to 4, and the color of the fourth slime to 5, the colors of the slimes will be 1, 4, 2, 5, 2, which satisfy the condition.

Sample Input 2

3
1 2 1

Sample Output 2

0

Although the colors of the first and third slimes are the same, they are not adjacent, so no spell is required.

Sample Input 3

5
1 1 1 1 1

Sample Output 3

2

For example, if we change the colors of the second and fourth slimes from the left to 2, the colors of the slimes will be 1, 2, 1, 2, 1, which satisfy the condition.

Sample Input 4

14
1 2 2 3 3 3 4 4 4 4 1 2 3 4

Sample Output 4

4


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 = if c > 64000000
  then let memo = 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 (ignore (S.add x memo); g (consume c b (x+d)))
    in g (consume c b a)
  else let memo = Array.make (c+1) false in
    let rec g x = if x < 0
      then printf "No\n"
      else if memo.(x)
      then printf "Yes\n"
      else (memo.(x) <- true; 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


let a, b = Scanf.scanf " %d %d" @@ fun a b -> a, b
let _ = print_endline @@ if a + b = 15 then "+" else if a * b = 15 then "*" else "x"

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.


let () = Scanf.scanf "%s\n%d\n" @@ fun s w ->
  for i = 0 to (String.length s + w - 1) / w - 1 do
    print_char s.[i * w]
  done;
  print_newline ()

Score : 200 points

Problem Statement

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

Constraints

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

S consists of lowercase English letters.

w is an integer.

Input

Input is given from Standard Input in the following format:

S
w

Output

Print the desired string in one line.

Sample Input 1

abcdefgh
3

Sample Output 1

adg

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

abc

def

gh

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

Sample Input 2

lllll
1

Sample Output 2

lllll

Sample Input 3

souuundhound
2

Sample Output 3

suudon


let () =
  let n, m, d = Scanf.scanf "%d %d %d" (fun n m d -> n, m, d) in
  (if d = 0 then
     1.0 /. float n *. float (m-1)
   else
     2.0 *. float (n - d) /. float (n * n) *. float (m-1))
  |> Printf.printf "%.7f\n"

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


let n = read_int ()
let _ = (if n mod 2 = 0 then n else n * 2) |> Printf.printf "%d\n"

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 n = read_int ()
let _ = Printf.printf "%d\n" @@ if n mod 2 = 0 then n else 2 * n


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


let get_int () = Scanf.scanf "%d " (fun v -> v)

let () =
  let n = get_int ()
  in (if n mod 2 = 0 then n else n*2
  ) |> string_of_int |> print_endline


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let _ = Array.(fold_left max a_s.(0) a_s - fold_left min a_s.(0) a_s) |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

You are given an integer sequence A of length N.
Find the maximum absolute difference of two elements (with different indices) in A.

Constraints

2 \leq N \leq 100

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 maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

The maximum absolute difference of two elements is A_3-A_1=6-1=5.

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let _ = Array.fold_left max 0 a_s - Array.fold_left min a_s.(0) a_s |> Printf.printf "%d\n"


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

let test a b =
  Array.fold_left (fun (u,i) v ->
    (* Printf.printf "  %d::abs(%d-(%d+%d))=%d\n"
      i v b i (abs (v-(b+i)))
    ; *)
    (u + (abs (v - (b+i)))), i+1) (0,1) a
  |> fst

let () =
  let n = get_int ()
  in let a = input_int_array n
  in let l = a |> Array.to_list
  in let lmax = List.fold_left max min_int l
  in let v = ref lmax in let f = ref true
  in let la = ref max_int
  in while !f do
    let r = test a !v
    in
    (* Printf.printf "%d::%d\n" !v r; *)
    if r < !la then (
      la := r; v := !v - 1
    ) else (
      f := false
    )
  done;
  !la |> string_of_int |> print_endline

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

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

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

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

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

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

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


let rec for_fold a b f v = if a > b then v else for_fold (a+1) b f (f v a)

let () =
  Scanf.scanf "%d" @@ fun n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  for i = 1 to n-1 do a.(i) <- a.(i) + a.(i-1) done;

  let psum l r =
    if l >= r then 0
    else if l = 0 then a.(r-1) else a.(r-1) - a.(l-1)
  in
  let halve a b =
    let rec loop l r =
      if l >= r then r
      else
        let m = (l+r) / 2 in
        if psum a m >= psum m b then loop l m else loop (l+1) r
    in
    let m = loop a b in
    if abs (psum a m - psum m b) <= abs (psum a (m-1) - psum (m-1) b) then
      psum a m, psum m b
    else
      psum a (m-1), psum (m-1) b
  in

  for_fold 2 (n-3) (fun v i ->
    let a, b = halve 0 i in
    let c, d = halve i n in
    List.(fold_left max a [a;b;c;d] - fold_left min a [a;b;c;d])
    |> min v
  ) a.(n-1)
  |> Printf.printf "%d\n"

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


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 rec take n = function
  | [] -> []
  | x :: xs ->
      if n = 0 then []
      else x :: take (n - 1) xs

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init (1 lsl n) @@ fun _ ->
    Scanf.scanf "%d " @@ fun a -> a in
  let dp = Array.init (1 lsl n) (fun i -> [i]) in
  for i = 0 to (1 lsl n) - 1 do
    for j = 0 to n - 1 do
      if 0 < i land (1 lsl j) then
        dp.(i) <-
          take 2 @@
          List.sort (fun i j -> compare as_.(j) as_.(i)) @@
          List.sort_uniq compare @@
          dp.(i) @ dp.(i land (lnot (1 lsl j)))
    done
  done;
  let a = Array.map (fun is ->
    List.fold_left ( + ) 0 @@
    List.map (Array.get as_) is) dp in
  for i = 1 to (1 lsl n) - 1 do
    a.(i) <- max a.(i) a.(i - 1);
    Printf.printf "%d\n" a.(i)
  done

Score : 700 points

Problem Statement

There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.)

For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem:

Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K.
Here, or denotes the bitwise OR.

Constraints

1 \leq N \leq 18

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_0 A_1 ... A_{2^N-1}

Output

Print 2^N-1 lines.
In the i-th line, print the answer of the problem above for K=i.

Sample Input 1

2
1 2 3 1

Sample Output 1

3
4
5

For K=1, the only possible pair of i and j is (i,j)=(0,1), so the answer is A_0+A_1=1+2=3.

For K=2, the possible pairs of i and j are (i,j)=(0,1),(0,2).
When (i,j)=(0,2), A_i+A_j=1+3=4. This is the maximum value, so the answer is 4.

For K=3, the possible pairs of i and j are (i,j)=(0,1),(0,2),(0,3),(1,2),(1,3),(2,3) .
When (i,j)=(1,2), A_i+A_j=2+3=5. This is the maximum value, so the answer is 5.

Sample Input 2

3
10 71 84 33 6 47 23 25

Sample Output 2

81
94
155
155
155
155
155

Sample Input 3

4
75 26 45 72 81 47 97 97 2 2 25 82 84 17 56 32

Sample Output 3

101
120
147
156
156
178
194
194
194
194
194
194
194
194
194


let rec arr_string str =
        let length = String.length str in
        match length with
        | 0 -> []
       | len ->
                let first = String.sub str 0 1 in
                let rest = String.sub str 1 (len - 1) in
                (String.get first 0) :: (arr_string rest)

let print_intline num = print_endline (string_of_int num)

let rec sum ls = match ls with
    | [] -> 0
    | (x::xs) -> x + (sum xs)

let digits n =
    let rec loop n acc =
        if n = 0 then acc
        else loop (n/10) (n mod 10::acc) in
    match n with
    | 0 -> [0]
    | _ -> loop n []

let () =
    let line = read_line () in
    let input = int_of_string line in
    let ans = sum (digits input) in
    let resp = input mod ans in
    match resp with
        | 0 -> print_endline "Yes"
         | _ -> print_endline "No"

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 () =
  Scanf.scanf "%d %d" @@ fun n k ->
  let _ = Array.init n @@ fun _ -> Scanf.scanf " %d" (fun x -> x) in
  Printf.printf "%d\n" ((n+k-3) / (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 rec s = function
  | 0 -> 0
  | n -> n mod 10 + s (n / 10)

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

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

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

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

Score : 500 points

Problem Statement

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

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

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

Constraints

1 \leq K

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

Input

Input is given from Standard Input in the following format:

K

Output

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

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19


open Printf
open Scanf

let solve a b =
  if a <= 8 && b <= 8 then "Yay!" else ":("

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

Score: 100 points

Problem Statement

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

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

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

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

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

Constraints

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

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

5 4

Sample Output 1

Yay!

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

Sample Input 2

8 8

Sample Output 2

Yay!

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

Sample Input 3

11 4

Sample Output 3

:(

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


let f x y = if x <= 8 && y <= 8 then true else false
let calc = if Scanf.scanf "%d %d" f then "Yay!" else ":("
let main = print_string calc


let n = read_int ()
let _ = if n < 1000 then print_endline "ABC" else print_endline "ABD"

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

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

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

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

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

999

Sample Output 1

ABC

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

Sample Input 2

1000

Sample Output 2

ABD

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

Sample Input 3

1481

Sample Output 3

ABD

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


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

Score : 200 points

Problem Statement

In some village, there are 999 towers that are 1,(1+2),(1+2+3),...,(1+2+3+...+999) meters high from west to east, at intervals of 1 meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located 1 meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are a meters for the west tower, and b meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least 1 meter.

Constraints

1 \leq a < b < 499500(=1+2+3+...+999)

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

If the depth of the snow cover is x meters, print x as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are 10 meters and 15 meters, respectively.
Thus, we can see that the depth of the snow cover is 2 meters.

Sample Input 2

54 65

Sample Output 2

1


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

  let h_arr = Array.init 1000 (fun _ -> 0) in
  for i = 1 to 999 do
    h_arr.(i) <- h_arr.(i-1)+i
  done;
  let d = b - a in

  Printf.printf "%d\n" (h_arr.(d) - b)


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 () = let a,b = scanf "%d %d\n" pair in
  let n = b - a - 1 in
  printf "%d\n" (n*(n+1)/2 - a)


let rec digits r = function
  | 0 -> []
  | n -> n mod r :: digits r (n / r)

let () = Scanf.scanf "%d" @@ fun n ->
  Array.init (n + 1) (fun i ->
    List.fold_left ( + ) 0 (digits 6 i) + List.fold_left ( + ) 0 (digits 9 (n - i)))
  |> Array.fold_left min max_int
  |> Printf.printf "%d\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


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

Score : 200 points

Problem Statement

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

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

6
aabbca

Sample Output 1

2

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

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

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

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


let () = Scanf.scanf "%d" @@ fun n ->
  let s = read_line () in
  Array.init (n + 1) (fun i ->
    Array.init 26 (fun c -> Char.chr @@ Char.code 'a' + c)
    |> Array.to_list
    |> List.filter (fun c ->
        List.exists (fun i -> s.[i] = c) (Array.to_list @@ Array.init i @@ fun j -> j) && List.exists (fun i -> s.[i] = c) (Array.to_list @@ Array.init (n - i) (( + ) i)))
    |> List.length)
  |> Array.fold_left max min_int
  |> Printf.printf "%d\n"


let base = int_of_char 'a'
let () =
  Scanf.scanf "%d " @@ fun n  ->
  let s =  Array.init n (fun _ ->
               Scanf.scanf "%c" (fun x -> x)) in
  let result = ref 0 in
  for i = 0 to (n-1) do
    let left = Array.sub s 0 i in
    let right = Array.sub s i (n-i)  in
    let left' = Array.to_list left in
    let right' = Array.to_list right in
    let num = ref 0 in
    for i = 0 to 26 do
      if List.mem (char_of_int (i+base)) left' = true
         && List.mem (char_of_int (i+base)) right' = true then
        num := 1 + !num
      else
        ()
    done;
    if !num > !result then result := !num
    else ()
  done;
  Printf.printf "%d\n" (!result)


let n, s = Scanf.scanf " %d %s" @@ fun a b -> a, b
let ans = ref max_int
let ls, rs = Array.make (n + 1) 0, Array.make (n + 1) 0
let _ =
  for i = 0 to n - 1 do ls.(i + 1) <- ls.(i) + if s.[i] = 'W' then 1 else 0 done;
  for i = n - 1 downto 0 do rs.(i) <- rs.(i + 1) + if s.[i] = 'E' then 1 else 0 done;
  for i = 0 to n - 1 do ans := min !ans @@ ls.(i) + rs.(i + 1) done;
  Printf.printf "%d\n" !ans

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


open Batteries

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

  let char_arr = Array.of_list (String.to_list s) in
  let res = ref n in

  let left_w = Array.make n 0 in
  let right_e = Array.make n 0 in

  for i=1 to (n-1) do
    if char_arr.(i-1) = 'W' then
      left_w.(i) <- left_w.(i-1) + 1
    else
      left_w.(i) <- left_w.(i-1)
  done;

  for i=1 to (n-1) do
    let i = n-1-i in
    if char_arr.(i+1) = 'E' then
      right_e.(i) <- right_e.(i+1) + 1
    else
      right_e.(i) <- right_e.(i+1)
  done;

  for i=0 to (n-1) do
    let v = left_w.(i) + right_e.(i) in
    if v < !res then res := v
  done;

  Array.iter print_int left_w;
  print_endline "";
  Array.iter print_int right_e;
  print_endline "";
  print_endline (string_of_int (!res))


open Batteries

let main () =
  let n, s = Scanf.scanf "%d\n%s" (fun x y -> x, y) in
  let ans = ref 30001 in
  for i = 0 to n - 1 do
    let x = if i > 0 then String.slice ~first:0 ~last:i s else "" in
    let y = String.slice ~first:(i+1) ~last:n s in
    ans := min !ans (String.fold_left (fun acc elem -> if Char.equal 'W' elem then acc + 1 else acc) 0 x +
                     String.fold_left (fun acc elem -> if Char.equal 'E' elem then acc + 1 else acc) 0 y)
  done;
  Printf.printf "%d\n" !ans

let _ = main ()


Scanf.scanf "%d %s" (fun n s ->
    let e = Array.make n 0 in
    let w = Array.make n 0 in
    if s.[0] = 'E' then e.(0) <- 1 else w.(0) <- 1;
    for j = 1 to n - 1 do
        if s.[j] = 'E' then (e.(j) <- e.(j - 1) + 1; w.(j) <- w.(j - 1))
                       else (w.(j) <- w.(j - 1) + 1; e.(j) <- e.(j - 1))
    done;
    let rec loop i acc =
        if i = n then acc else (
            let q =
                if i = 0     then e.(n - 1) - e.(i) else
                if i = n - 1 then w.(i - 1)         else
                                  e.(n - 1) - e.(i) + w.(i - 1)
            in
            let acc = min acc q in
            loop (i + 1) acc

        )
    in
    loop 0 max_int |> Printf.printf "%d\n"
)


(*
 * 西=左
 * 東=右
 *)

let () = Scanf.scanf "%d\n%s\n" @@ fun n s ->
  let west = Array.make (n + 2) 0
  in
  let east = Array.make (n + 2) 0
  in
  for i = 0 to n - 1 do
    (if s.[i] = 'W' then
      west.(i + 2) <- 1);
    (if s.[i] = 'E' then
      east.(i) <- 1)
  done;
  for i = 1 to n + 1 do
    west.(i) <- west.(i) + west.(i - 1);
  done;
  for i = n downto 0 do
    east.(i) <- east.(i) + east.(i + 1)
  done;
  Array.init n (fun i -> west.(i + 1) + east.(i + 1))
  |> Array.fold_left min max_int
  |> Printf.printf "%d\n"


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
    (* 最小の要素 空集合が与えられた場合は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 min_elt t = fst (count_min_elt t)

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

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

(*
 * 西=左
 * 東=右
 *)

let () = Scanf.scanf "%d\n%s\n" @@ fun n s ->
  let west, east =
    Array.init (String.length s) (fun i -> (i, s.[i]))
      |> Array.fold_left (fun (west, east) -> function
        | (i, 'W') -> (IntMultiSet.add i 1 west, east)
        | (i, 'E') -> (west, IntMultiSet.add i 1 east)) (IntMultiSet.empty, IntMultiSet.empty) in
  Array.init (String.length s - 1) (fun i ->
    IntMultiSet.count_lt i west + IntMultiSet.count_gt i east)
  |> Array.fold_left min max_int
  |> Printf.printf "%d\n"


let _ =
  Scanf.scanf "%d" @@ fun n ->
  let p = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let c = Array.make (n+1) 0 in
  Array.fold_left (fun s x ->
    c.(x) <- c.(x-1) + 1;
    min s (n - c.(x))
  ) n p
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

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

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

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

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1
:
P_N

Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4

Sample Output 1

2

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

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

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

Sample Input 2

6
3
2
5
1
4
6

Sample Output 2

4

Sample Input 3

8
6
3
1
2
7
4
8
5

Sample Output 3

5


Scanf.scanf "%d %d %d %d" (fun a b c d ->
    print_endline @@
        if abs (b - a) <= d && abs (c - b) <= d || abs (c - a) <= d then "Yes" else "No"
)

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


Scanf.scanf "%d %d %d %d" @@ fun a b c d -> print_endline @@ if abs (a - c) <= d || abs (a - b) <= d && abs (b - c) <= d then "Yes" else "No"


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


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

let exp_less_than_dec x =
  let rec exps n =
    if n = 1 then [1]
    else exps_base_n_less_than x n @ exps @@ pred n
  in
  List.filter (fun n -> n <= x) @@ exps x
  |> List.sort compare
  |> List.rev

let main () =
  let x = Scanf.scanf "%d" (fun x -> x) in
  exp_less_than_dec x
  |> 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


let rec iter a b f = if a >= b then () else (f a; iter (a+1) b f)
let () =
  Scanf.scanf "%d" @@ fun x ->
  let a = Array.make (x+1) false in
  a.(1) <- true;
  iter 2 (x+1) (fun b ->
    let rec loop v =
      if v > x then ()
      else (a.(v) <- true; loop (v*b))
    in loop (b*b));
  Array.mapi (fun i e -> i,e) a
  |> Array.fold_left (fun v (i,t) -> if t then i else v) 1
  |> Printf.printf "%d\n"


let main () =
  let x = Scanf.scanf "%d\n" (fun a -> a) in
  let ans = BatArray.make (x+1) false in
  ans.(1) <- true;
  for i = 2 to x do
    let n = ref @@ i * i in
    while !n <= x do
      ans.(!n) <- true;
      n := !n * i;
    done;
  done;
  for i = x downto 1 do
    if ans.(i) then (print_int i; exit 0)
  done;;

let _ = main ()


let main () =
  let rec expi a b = if b = 1 then a else expi (a*a) (b-1) in
  let x = Scanf.scanf "%d\n" (fun a -> a) in
  let xs = ref [1] in
  let rec minexp x i acc = if expi i acc <= x then minexp x i (acc+1) else expi i (acc-1) in
  for i = 2 to int_of_float (sqrt (float_of_int x)) + 1 do
    xs := minexp x i 2 :: !xs;
  done;
  xs := List.sort (fun a b -> (-1 * compare a b)) !xs;
  print_int @@ List.hd !xs

let _ = main ()


Scanf.scanf "%s %d" (fun s k ->
    let module S = Set.Make (struct type t = string let compare = compare end) in

    let n = String.length s in

    let rec loop st en set =
        if st = n then set else
            if en = n then loop (st + 1) (st + 1) set else
                loop st (en + 1) (S.add (String.sub s st (en - st + 1)) set)
    in
    let set = loop 0 0 S.empty in

    let rec loop i set =
        let m = S.min_elt set in
        if i = k then m else loop (i + 1) (S.remove m set)
    in
    loop 1 set |> print_endline
)

Score : 300 points

Problem Statement

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

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

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

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

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

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

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

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


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

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

  let length = String.length s in

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

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

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


let () =
  let a, b = Scanf.scanf "%d %d" (fun a b -> a, b) in
  let result =
    if a <= b then
      a
    else
      a - 1
  in
  Printf.printf "%d\n" result

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 a = ref 0 and b = ref 0 in
    Scanf.sscanf (read_line ()) "%d %d" (fun x y -> a := x; b := y);
    if !b - !a >= 0 then print_string ((string_of_int !a) ^ "\n") else print_string ((string_of_int (!a - 1)) ^ "\n")


let () =
  let x,  k = Scanf.scanf "%d %d %d %d" (fun a b c k -> [a;b;c], k) in
  let x' = List.rev (List.sort (-) x) in
  let y = (List.hd x') * 2 * k in
  let res = y + List.fold_left (+) 0 (List.tl x') in
  Printf.printf "%d\n" res

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.