let scan_int () = Scanf.scanf " %d" (fun x -> x)
let scan_array len read_func = Array.init len (fun _ -> read_func())
let print_int n = Printf.printf "%d\n" n

let input n =
  let arr = Array.make n 0 in
  let _ =
    for i = 0 to n-1 do
      let a = scan_int() in
      arr.(a-1) <- arr.(a-1) + 1
    done in
  arr

let cumulative_sum n arr =
  let ret = Array.make (n+1) 0 in
  let _ =
    for i = 0 to n-1 do
      ret.(i+1) <- ret.(i) + arr.(i)
    done in
  ret

let rec binary_search left right eval =
  if right - left <= 1 then right
  else
    let mid = (right + left) / 2 in
    if eval mid then binary_search mid right eval
    else binary_search left mid eval

let inner_eval arr value mid = arr.(mid) > value

let eval i arr cum remain mid =
  let r = binary_search (-1) i (inner_eval arr mid) in
  let require = (i-r) * mid - (cum.(i) - cum.(r)) in
  remain >= require

let solve i n arr cum =
  let remain = n - cum.(i) in
  (binary_search 0 (n+1) (eval i arr cum remain)) - 1  (* get left *)

let () =
  let n = scan_int() in
  let arr = input n in
  let _ = Array.fast_sort (fun x y -> if x < y then 1 else 0) arr in
  let cum = cumulative_sum n arr in
  for i = 1 to n do
    print_int (solve i n arr cum)
  done

Score : 600 points

Problem Statement

Takahashi has N cards. The i-th of these cards has an integer A_i written on it.

Takahashi will choose an integer K, and then repeat the following operation some number of times:

Choose exactly K cards such that the integers written on them are all different, and eat those cards. (The eaten cards disappear.)

For each K = 1,2, \ldots, N, find the maximum number of times Takahashi can do the operation.

Constraints

1 \le N \le 3 \times 10^5

1 \le A_i \le N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print N integers.
The t-th (1 \le t \le N) of them should be the answer for the case K=t.

Sample Input 1

3
2 1 2

Sample Output 1

3
1
0

For K = 1, we can do the operation as follows:

Choose the first card to eat.

Choose the second card to eat.

Choose the third card to eat.

For K = 2, we can do the operation as follows:

Choose the first and second cards to eat.

For K = 3, we cannot do the operation at all. Note that we cannot choose the first and third cards at the same time.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

5
2
1
1
1

Sample Input 3

4
1 3 3 3

Sample Output 3

4
1
0
0


let n = read_int ()
let ans = if n mod 2 = 0 then 0.5 else (float_of_int (n/2+1)) /. (float_of_int n)
let () = print_float ans

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

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000

Submitted source-code file size, in bytes.

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

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


open Printf
open Scanf

let solve n =
  float_of_int ((n + 1) / 2) /. float_of_int n

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


let n = read_int ()
let _ = Printf.printf "%.10f\n" @@ float (n - n / 2) /. float n


let () =
  Scanf.scanf "%d %d\n" @@ fun n k ->
  let h = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  let ans = Array.fold_left (fun a x -> if x >= k then a+1 else a) 0 h in
  Printf.printf "%d\n" ans

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


(* unihernandez22
 * https://atcoder.jp/contests/abc142/tasks/abc142_b
 * implementation, simulation
 * *)

Scanf.scanf "%d %d\n" @@ fun n k ->
    Printf.printf "%d\n" @@ Array.fold_left ( + ) 0 @@
    Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun h -> if h >= k then 1 else 0


let i_inp_list : unit -> int list = fun () ->
  let inp_split = Str.split (Str.regexp " ") (input_line stdin) in
  List.map (fun x -> int_of_string x) (inp_split)

let () =
  let (n, k) = Scanf.sscanf (input_line stdin) "%d %d" (fun a b -> (a, b)) in
  let l = i_inp_list () in
  let ans = List.fold_right (fun h num -> num + (if h >= k then 1 else 0)) l 0
  in
  print_int ans;
  print_newline ()


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

let n = Scanf.sscanf (read_line ()) "%d" (
        fun n ->
                n
)

let lst = Str.split (Str.regexp " ") (read_line ())
          |> BatList.map int_of_string

let lst2 = BatList.map2 (fun i elmnt -> (i, elmnt)) (BatList.range 1 `To n) lst
           |> BatList.fast_sort (fun (ai, ae) (bi, be) -> if ae = be then 0 else if ae < be then -1 else 1)
           |> BatList.map (fun (i, e) -> string_of_int i)

let () =
        BatList.fold_right (fun a b -> a ^ " " ^ b) lst2 ""
        |> Printf.printf "%s\n"

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


type 'a tree =
    Leaf
  | Node of 'a tree * 'a * 'a tree

let empty : 'a tree = Leaf

let rec insert : ('a -> 'b) -> 'a -> 'a tree -> 'a tree = fun f x t ->
  match t with
    Leaf -> Node (Leaf, x , Leaf)
  | Node (l, y, r) ->
     if f x < f y then
       Node (insert f x l, y, r)
     else
       Node (l, y, insert f x  r)

let rec print_tree_int t =
  match t with
    Leaf -> ()
  | Node (l, (x, i), r) ->
     print_tree_int l;
     print_int i;
     print_char ' ' ;
     print_tree_int r

let i_inp_list : unit -> (int * int) list = fun () ->
  let inp_split = Str.split (Str.regexp " ") (input_line stdin) in
  List.mapi (fun i x -> (int_of_string x, i + 1)) (inp_split)

let () =
  let _ = Scanf.sscanf (input_line stdin) "%d" (fun a -> a) in
  let l = i_inp_list () in
  let ans = List.fold_left (fun t x -> insert (fun (a, b) -> b) x t) empty l in
  print_tree_int ans;
  print_newline ()


type 'a tree =
    Leaf
  | Node of 'a tree * 'a * 'a tree

let empty = Leaf

let rec insert (x, i) t =
  match t with
    Leaf -> Node (Leaf, (x, i) , Leaf)
  | Node (l, (y, j), r) ->
     if x < y then
       Node (insert (x, i) l, (y, j), r)
     else
       Node (l, (y, j), insert (x, i) r)

let rec print_tree_int t =
  match t with
    Leaf -> ()
  | Node (l, (x, i), r) ->
     print_tree_int l;
     print_int i;
     print_char ' ' ;
     print_tree_int r

let i_inp_list : unit -> (int * int) list = fun () ->
  let inp_split = Str.split (Str.regexp " ") (input_line stdin) in
  List.mapi (fun i x -> (int_of_string x, i + 1)) (inp_split)

let () =
  let _ = Scanf.sscanf (input_line stdin) "%d" (fun a -> a) in
  let l = i_inp_list () in
  let ans = List.fold_left (fun t x -> insert x t) empty l in
  print_tree_int ans;
  print_newline ()


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" pred
let rs = Array.make n 0
let _ = Array.(iteri (fun i a -> rs.(a) <- i + 1) a_s; iteri (fun i r -> Printf.printf (if i = 0 then "%d" else " %d") r) rs; print_newline ())


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let as' = Array.make n 0 in
  Array.iteri (fun i a -> as'.(a - 1) <- i + 1) as_;
  Array.iter (Printf.printf "%d ") as';
  print_newline ()


Scanf.scanf "%d %d" (fun n k ->
    let p = Array.init n (fun _ -> Scanf.scanf " %d" (fun p -> p)) in
    let module S = Set.Make (struct type t = int let compare = compare end) in

    let rec loop i streak count =
        if i = n then count else
            let streak = if p.(i - 1) < p.(i) then streak + 1 else 0 in
            let count = if streak = k - 1 then count + 1 else count in
            loop (i + 1) streak count
    in
    let count = loop 1 0 0 in

    let rec loop i set acc =
        if i = n then acc else
            let set = S.remove p.(i - k) set in
            let nmi = S.min_elt set in
            let nmx = S.max_elt set in
            let acc = if p.(i - k) > nmi || p.(i) < nmx then acc + 1 else acc in
            let set = S.add p.(i) set in
            loop (i + 1) set acc
    in
    let init =
        let rec loop i set =
            if i = k then set else loop (i + 1) (S.add p.(i) set)
        in
        loop 0 S.empty
    in
    let ans = loop k init 1 in
    Printf.printf "%d\n" (ans - max 0 (count - 1))
)

Score : 700 points

Problem Statement

Snuke has a permutation (P_0,P_1,\cdots,P_{N-1}) of (0,1,\cdots,N-1).

Now, he will perform the following operation exactly once:

Choose K consecutive elements in P and sort them in ascending order.

Find the number of permutations that can be produced as P after the operation.

Constraints

2 \leq N \leq 200000

2 \leq K \leq N

0 \leq P_i \leq N-1

P_0,P_1,\cdots,P_{N-1} are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_0 P_1 \cdots P_{N-1}

Output

Print the number of permutations that can be produced as P after the operation.

Sample Input 1

5 3
0 2 1 4 3

Sample Output 1

2

Two permutations can be produced as P after the operation: (0,1,2,4,3) and (0,2,1,3,4).

Sample Input 2

4 4
0 1 2 3

Sample Output 2

1

Sample Input 3

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

Sample Output 3

6


let () =
  Scanf.scanf "%s\n" @@ fun s ->
  let ans = ref true in
  let check i c =
    if i mod 2 = 1 then
      if c = 'R' || c = 'U' || c = 'D' then () else ans := !ans && false
    else
      if c = 'L' || c = 'U' || c = 'D' then () else ans := !ans && false in
  StringLabels.iteri (fun i c -> check (i+1) c) s;
  Printf.printf "%s\n" (if !ans then "Yes" else "No")

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

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

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


let () = Scanf.scanf "%d %d %d\n" @@ fun n k q ->
  let ppoint = Array.make n 0 in
  for i = 1 to q do
    Scanf.scanf "%d\n" @@ fun a -> ppoint.(a-1) <- ppoint.(a-1) + 1
  done;
  for i = 0 to n - 1 do
    if k - q + ppoint.(i) > 0 then Printf.printf "Yes\n"
    else Printf.printf "No\n"
  done;

Score: 300 points

Problem Statement

Takahashi has decided to hold fastest-finger-fast quiz games. Kizahashi, who is in charge of making the scoreboard, is struggling to write the program that manages the players' scores in a game, which proceeds as follows.

A game is played by N players, numbered 1 to N. At the beginning of a game, each player has K points.

When a player correctly answers a question, each of the other N-1 players receives minus one (-1) point. There is no other factor that affects the players' scores.

At the end of a game, the players with 0 points or lower are eliminated, and the remaining players survive.

In the last game, the players gave a total of Q correct answers, the i-th of which was given by Player A_i.
For Kizahashi, write a program that determines whether each of the N players survived this game.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 10^9

1 \leq Q \leq 10^5

1 \leq A_i \leq N\ (1 \leq i \leq Q)

Input

Input is given from Standard Input in the following format:

N K Q
A_1
A_2
.
.
.
A_Q

Output

Print N lines. The i-th line should contain Yes if Player i survived the game, and No otherwise.

Sample Input 1

6 3 4
3
1
3
2

Sample Output 1

No
No
Yes
No
No
No

In the beginning, the players' scores are (3, 3, 3, 3, 3, 3).

Player 3 correctly answers a question. The players' scores are now (2, 2, 3, 2, 2, 2).

Player 1 correctly answers a question. The players' scores are now (2, 1, 2, 1, 1, 1).

Player 3 correctly answers a question. The players' scores are now (1, 0, 2, 0, 0, 0).

Player 2 correctly answers a question. The players' scores are now (0, 0, 1, -1, -1, -1).

Players 1, 2, 4, 5 and 6, who have 0 points or lower, are eliminated, and Player 3 survives this game.

Sample Input 2

6 5 4
3
1
3
2

Sample Output 2

Yes
Yes
Yes
Yes
Yes
Yes

Sample Input 3

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

Sample Output 3

No
No
No
No
Yes
No
No
No
Yes
No


let n, k, q = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let rs = Array.make n 0
let s = for i = 1 to q do Scanf.scanf " %d" @@ fun a -> rs.(a - 1) <- rs.(a - 1) + 1 done; Array.fold_left (+) 0 rs
let _ = Array.iter (fun r -> print_endline @@ if k - (s - r) > 0 then "Yes" else "No") rs


let password n = n * n * n
let () = Printf.printf "%d\n" (password (read_int ()))

Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


let () = Scanf.scanf "%d\n" @@ fun n ->
  let ss =
    Array.init (1 lsl n) @@ fun _ ->
      Scanf.scanf "%d " @@ fun s -> s in
  print_endline @@
  try
    Array.sort (fun s s' -> compare s' s) ss;
    let ssq = Queue.create () in
    Array.iter (fun s -> Queue.push s ssq) ss;
    let q = Queue.create () in
    Queue.push (Queue.pop ssq, n) q;
    while not (Queue.is_empty q) do
      let (s, n) = Queue.pop q in
      for m = n - 1 downto 0 do
        let s' = Queue.pop ssq in
        if s <= s'
        then raise Not_found
        else Queue.push (s', m) q
      done
    done;
    "Yes"
  with Not_found -> "No"

Score : 600 points

Problem Statement

We have one slime.

You can set the health of this slime to any integer value of your choice.

A slime reproduces every second by spawning another slime that has strictly less health. You can freely choose the health of each new slime. The first reproduction of our slime will happen in one second.

Determine if it is possible to set the healths of our first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals a multiset S.

Here S is a multiset containing 2^N (possibly duplicated) integers: S_1,~S_2,~...,~S_{2^N}.

Constraints

All values in input are integers.

1 \leq N \leq 18

1 \leq S_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
S_1 S_2 ... S_{2^N}

Output

If it is possible to set the healths of the first slime and the subsequent slimes spawn so that the multiset of the healths of the 2^N slimes that will exist in N seconds equals S, print Yes; otherwise, print No.

Sample Input 1

2
4 2 3 1

Sample Output 1

Yes

We will show one way to make the multiset of the healths of the slimes that will exist in 2 seconds equal to S.

First, set the health of the first slime to 4.

By letting the first slime spawn a slime whose health is 3, the healths of the slimes that exist in 1 second can be 4,~3.

Then, by letting the first slime spawn a slime whose health is 2, and letting the second slime spawn a slime whose health is 1, the healths of the slimes that exist in 2 seconds can be 4,~3,~2,~1, which is equal to S as multisets.

Sample Input 2

2
1 2 3 1

Sample Output 2

Yes

S may contain multiple instances of the same integer.

Sample Input 3

1
1 1

Sample Output 3

No

Sample Input 4

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

Sample Output 4

No


let scan_string () = Scanf.scanf " %s" (fun x -> x)
let print_int n = Printf.printf "%d\n" n

let () =
  let s = scan_string() and t = scan_string() in
  let judge i = if (s.[i] == t.[i]) then 1 else 0 in
  print_int (judge 0 + judge 1 + judge 2)

Score : 100 points

Problem Statement

You will be given a string S of length 3 representing the weather forecast for three days in the past.

The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

You will also be given a string T of length 3 representing the actual weather on those three days.

The i-th character (1 \leq i \leq 3) of S represents the actual weather on the i-th day. S, C, and R stand for sunny, cloudy, and rainy, respectively.

Print the number of days for which the forecast was correct.

Constraints

S and T are strings of length 3 each.

S and T consist of S, C, and R.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the number of days for which the forecast was correct.

Sample Input 1

CSS
CSR

Sample Output 1

2

For the first day, it was forecast to be cloudy, and it was indeed cloudy.

For the second day, it was forecast to be sunny, and it was indeed sunny.

For the third day, it was forecast to be sunny, but it was rainy.

Thus, the forecast was correct for two days in this case.

Sample Input 2

SSR
SSR

Sample Output 2

3

Sample Input 3

RRR
SSS

Sample Output 3

0


let divu x y =
        if x mod y >= 1 then
                (x / y) + 1
        else
                (x / y)

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

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


let scan_int () = Scanf.scanf " %d" (fun x -> x)
let print_int n = Printf.printf "%d\n" n

let () =
  let a = scan_int() and b = scan_int() in
  let ans =
    if b < a then 1
    else 1 + (b-2) / (a-1) in
  print_int ans


open Scanf;;
open Printf;;

let rint () = scanf " %d" (fun x -> x);;

let () =
  let a = rint () and b = rint () in
  let ans = (b - 1 + a - 2) / (a - 1) in
  printf "%d\n" ans;


Scanf.scanf "%d" (fun n ->
    let xy = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in
    Array.sort (fun (x0, y0) (x1, y1) ->
        compare (atan2 (float y0) (float x0)) (atan2 (float y1) (float x1))) xy;
    let sum = Array.make (2 * n + 1) (0, 0) in
    for i = 1 to 2 * n do
        let (x, y) = sum.(i - 1) in
        let (vx, vy) = xy.((i - 1) mod n) in
        sum.(i) <- x + vx, y + vy
    done;
    let rec loop0 i acc =
        let rec loop1 j acc =
            if j = 2 * n + 1 || j >= i + n + 1 then loop0 (i + 1) acc else
                let (x0, y0) = sum.(i) in
                let (x1, y1) = sum.(j) in
                let x = x1 - x0 in
                let y = y1 - y0 in
                let acc = max acc (x * x + y * y) in
                loop1 (j + 1) acc
        in
        if i = 2 * n then float acc |> sqrt else loop1 (i + 1) acc
    in
    loop0 0 0 |> Printf.printf "%.12f\n"
)

Score: 600 points

Problem Statement

E869120 is initially standing at the origin (0, 0) in a two-dimensional plane.

He has N engines, which can be used as follows:

When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the coordinates (X + x_i, Y + y_i).

E869120 can use these engines in any order, but each engine can be used at most once. He may also choose not to use some of the engines.

He wants to go as far as possible from the origin.
Let (X, Y) be his final coordinates. Find the maximum possible value of \sqrt{X^2 + Y^2}, the distance from the origin.

Constraints

1 \leq N \leq 100

-1 \ 000 \ 000 \leq x_i \leq 1 \ 000 \ 000

-1 \ 000 \ 000 \leq y_i \leq 1 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
: :
x_N y_N

Output

Print the maximum possible final distance from the origin, as a real value.
Your output is considered correct when the relative or absolute error from the true answer is at most 10^{-10}.

Sample Input 1

3
0 10
5 -5
-5 -5

Sample Output 1

10.000000000000000000000000000000000000000000000000

The final distance from the origin can be 10 if we use the engines in one of the following three ways:

Use Engine 1 to move to (0, 10).

Use Engine 2 to move to (5, -5), and then use Engine 3 to move to (0, -10).

Use Engine 3 to move to (-5, -5), and then use Engine 2 to move to (0, -10).

The distance cannot be greater than 10, so the maximum possible distance is 10.

Sample Input 2

5
1 1
1 0
0 1
-1 0
0 -1

Sample Output 2

2.828427124746190097603377448419396157139343750753

The maximum possible final distance is 2 \sqrt{2} = 2.82842....
One of the ways to achieve it is:

Use Engine 1 to move to (1, 1), and then use Engine 2 to move to (2, 1), and finally use Engine 3 to move to (2, 2).

Sample Input 3

5
1 1
2 2
3 3
4 4
5 5

Sample Output 3

21.213203435596425732025330863145471178545078130654

If we use all the engines in the order 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 5, we will end up at (15, 15), with the distance 15 \sqrt{2} = 21.2132... from the origin.

Sample Input 4

3
0 0
0 1
1 0

Sample Output 4

1.414213562373095048801688724209698078569671875376

There can be useless engines with (x_i, y_i) = (0, 0).

Sample Input 5

1
90447 91000

Sample Output 5

128303.000000000000000000000000000000000000000000000000

Note that there can be only one engine.

Sample Input 6

2
96000 -72000
-72000 54000

Sample Output 6

120000.000000000000000000000000000000000000000000000000

There can be only two engines, too.

Sample Input 7

10
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20

Sample Output 7

148.660687473185055226120082139313966514489855137208


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

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

let sort_count cmp xs =
  let rec rev_merge_count xs lxs ys invs acc k =
    match xs, ys with
    | _, [] -> k invs (List.rev_append xs acc)
    | [], _ -> k invs (List.rev_append ys acc)
    | x :: xs', y :: ys' ->
        if cmp x y <= 0
        then rev_merge_count xs' (lxs - 1) ys invs (x :: acc) k
        else rev_merge_count xs lxs ys' (lxs + invs) (y :: acc) k in
  let rec rev_merge_count_rev xs ys lys invs acc k =
    match xs, ys with
    | _, [] -> k invs (List.rev_append xs acc)
    | [], _ -> k invs (List.rev_append ys acc)
    | x :: xs', y :: ys' ->
        if cmp x y > 0
        then rev_merge_count_rev xs' ys lys (lys + invs) (x :: acc) k
        else rev_merge_count_rev xs ys' (lys - 1) invs (y :: acc) k in
  let rec sort_count invs n xs k =
    match n, xs with
    | 0, _ -> k xs invs []
    | 1, x :: xs -> k xs invs [x]
    | _, _ ->
        sort_count_rev invs ((n + 1) lsr 1) xs @@ fun xs invs ys ->
          sort_count_rev invs (n lsr 1) xs @@ fun xs invs zs ->
            rev_merge_count_rev ys zs (n lsr 1) invs [] @@ k xs
  and sort_count_rev invs n xs k =
    match n, xs with
    | 0, _ -> k xs invs []
    | 1, x :: xs -> k xs invs [x]
    | _, _ ->
        sort_count invs (n lsr 1) xs @@ fun xs invs ys ->
          sort_count invs ((n + 1) lsr 1) xs @@ fun xs invs zs ->
            rev_merge_count ys (n lsr 1) zs invs [] @@ k xs in
  sort_count 0 (List.length xs) xs @@ fun _ invs zs -> invs, zs

let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  Printf.printf "%d\n" @@
  ( +^ ) (k *^ fst (sort_count compare (Array.to_list as_))) @@
  ( *^ ) (k * (k - 1) / 2 mod m) @@
  fst @@
  IntMap.fold (fun _ n (acc, sum) -> (acc + n * sum, sum + n))
    (Array.fold_left (fun m a ->
      IntMap.add a (1 +
        try IntMap.find a m
        with Not_found -> 0) m) IntMap.empty as_) (0, 0)

Score : 300 points

Problem Statement

We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.

Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.

Find the inversion number of B, modulo 10^9 + 7.

Here the inversion number of B is defined as the number of ordered pairs of integers (i,~j)~(0 \leq i < j \leq K \times N - 1) such that B_i > B_j.

Constraints

All values in input are integers.

1 \leq N \leq 2000

1 \leq K \leq 10^9

1 \leq A_i \leq 2000

Input

Input is given from Standard Input in the following format:

N K
A_0 A_1 ... A_{N - 1}

Output

Print the inversion number of B, modulo 10^9 + 7.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, B~=~2,~1,~2,~1. We have:

B_0 > B_1

B_0 > B_3

B_2 > B_3

Thus, the inversion number of B is 3.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

A may contain multiple occurrences of the same number.

Sample Input 3

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

Sample Output 3

185297239

Be sure to print the output modulo 10^9 + 7.


Scanf.scanf "%d" (fun n ->
    let v = Array.init n (fun _ -> Scanf.scanf " %f" (fun v -> v)) in
    Array.sort compare v;
    let rec loop i cur =
        if i = n then cur else
            loop (i + 1) ((cur +. v.(i)) /. 2.)
    in
    loop 1 v.(0) |> Printf.printf "%.6f\n"
)

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


Scanf.scanf "%d" (fun n ->
    let module S = Set.Make (struct type t = int * int let compare = compare end) in
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in
    let b = Array.make n 0 in
    let rec loop i set =
        if i = n then set else
            let set = Scanf.scanf " %d" (fun k -> b.(i) <- k; S.add (k, i) set) in
            loop (i + 1) set
    in
    let set = loop 0 S.empty in

    let check set = S.for_all (fun (k, i) -> a.(i) = k) set in

    let rec loop set c =
        let (k, i) = S.max_elt set in
        let set = S.remove (k, i) set in
        let (k2 ,i2) = S.max_elt set in
        let delta = b.((i - 1 + n) mod n) + b.((i + 1) mod n) in
        let q = (k - k2 + delta) / delta in
        let nb = b.(i) - q * delta in
        if nb < a.(i) then (if check set then c + q - 1 else -1) else (
            b.(i) <- nb;
            loop (S.add (nb, i) set) (c + q)
        )
    in
    loop set 0 |> Printf.printf "%d\n"
)

Score : 800 points

Problem Statement

There are N positive integers arranged in a circle.

Now, the i-th number is A_i. Takahashi wants the i-th number to be B_i. For this objective, he will repeatedly perform the following operation:

Choose an integer i such that 1 \leq i \leq N.

Let a, b, c be the (i-1)-th, i-th, and (i+1)-th numbers, respectively. Replace the i-th number with a+b+c.

Here the 0-th number is the N-th number, and the (N+1)-th number is the 1-st number.

Determine if Takahashi can achieve his objective.
If the answer is yes, find the minimum number of operations required.

Constraints

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

1 \leq A_i, B_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
B_1 B_2 ... B_N

Output

Print the minimum number of operations required, or -1 if the objective cannot be achieved.

Sample Input 1

3
1 1 1
13 5 7

Sample Output 1

4

Takahashi can achieve his objective by, for example, performing the following operations:

Replace the second number with 3.

Replace the second number with 5.

Replace the third number with 7.

Replace the first number with 13.

Sample Input 2

4
1 2 3 4
2 3 4 5

Sample Output 2

-1

Sample Input 3

5
5 6 5 2 1
9817 1108 6890 4343 8704

Sample Output 3

25


let a_calc a b =
  max (a + b) (max (a - b) (a * b))

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

Score : 100 points

Problem Statement

We have two integers: A and B.

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

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among A + B = -32, A - B = 34, and A \times B = -33 is 34.

Sample Input 3

13 3

Sample Output 3

39

The largest number among A + B = 16, A - B = 10, and A \times B = 39 is 39.


let () = Scanf.scanf "%d %d" @@ fun k x ->
  let left = max (-1000000) (x - k + 1) in
  let right = min 1000000 (x + k -1) in
  Printf.printf "%d" left;
  for i = (left + 1) to right do
    Printf.printf " %d" i
  done;

Score : 200 points

Problem Statement

There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000.

Among them, some K consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate X is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

1 \leq K \leq 100

0 \leq X \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K X

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate 7 is painted black. There are three possible cases:

The three stones painted black are placed at coordinates 5, 6, and 7.

The three stones painted black are placed at coordinates 6, 7, and 8.

The three stones painted black are placed at coordinates 7, 8, and 9.

Thus, five coordinates potentially contain a stone painted black: 5, 6, 7, 8, and 9.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100


let k, x = Scanf.sscanf (read_line()) "%d %d" (fun k x ->k,x)
let rec show i e =
  if i > e then () else
  (Printf.printf "%d " i; show (i+1) e)

let _ = show (x-k+1) (x+k-1); Printf.printf "\n"


open Scanf
open Printf

let rint () = scanf " %d" (fun x -> x)
let stoa s = Array.init (String.length s) (String.get s)
let atos a = String.init (Array.length a) (Array.get a)

let () =
  let k = rint () and x = rint () in
  for i = -1000000 to 1000000 do
    if i >= x - k + 1 && i <= x + k - 1 then
      printf "%d " i
  done;
  printf "\n"


open Batteries
(* 文字列をcharのlistにする *)
let explode s = List.init (String.length s) (String.get s)
let n = read_int ()
let dict = Array.init (n+1) @@ fun a -> 0
let rec get_basyo lst s i =
  match lst with
  | [] -> -1
  | first :: rest -> if first = s then i else get_basyo rest s (i+1)
let rec loop lst i =
  if i >= n then () else
  let s = read_line () |> explode |> List.sort compare in
  if List.mem s lst then (dict.(get_basyo lst s 0) <- dict.(get_basyo lst s 0) + 1; loop lst (i+1)) else
  (dict.(List.length lst) <- 1; loop (List.append lst [s]) (i+1))

let rec answ i ans =
  if dict.(i) = 0 then ans else
  answ (i+1) (ans + (dict.(i) * (dict.(i)-1)))

let _ = loop [] 0; Printf.printf "%d\n" @@ (answ 0 0) / 2

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


module StringMap = Map.Make (struct
  type t = string
  let compare = compare
end)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let ss = Array.init n @@ fun _ ->
    Scanf.scanf "%s\n" @@ fun s ->
      let a = Array.init (String.length s) (String.get s) in
      Array.sort compare a;
      String.init (String.length s) (Array.get a) in
  Printf.printf "%d\n" @@
  StringMap.fold (fun _ n acc -> acc + n * (n - 1) / 2)
    (Array.fold_left (fun m s ->
      StringMap.add s
        (1 + try StringMap.find s m with Not_found -> 0) m)
    StringMap.empty ss) 0


type 'a t = Empty | Node of (int * 'a * 'a t * 'a t)

let rec merge q1 q2 =
    match q1, q2 with
    | Empty, Empty            -> Empty
    | Node(_, _, _, _), Empty -> q1
    | Node(n1, v1, l1, r1), Node(n2, v2, l2, r2) ->
        if v1 < v2
        then Node(n1 + n2, v2, q1, merge l2 r2)
        else Node(n1 + n2, v1, q2, merge l1 r1)
    | _, _ -> failwith "merge"

let pop q =
    match q with
    | Empty -> failwith "pop"
    | Node(_, _, l, r) -> merge l r

let rec push x q =
    match q with
    | Empty -> Node(1, x, Empty, Empty)
    | Node(_, v, l, r) ->
        let large = max x v in
        let small = min x v in
        match l, r with
        | Empty, Empty         -> Node(2, large, Node(1, small, Empty, Empty), Empty)
        | Node(n, _, _, _), Empty -> Node(n + 2, large, l, Node(1, small, Empty, Empty))
        | Node(nl, _, _, _), Node(nr, _, _, _) ->
            if nl > nr
            then Node(nl + nr + 2, large, l, push small r)
            else Node(nl + nr + 2, large, push small l, r)
        | _, _ -> failwith "push"

let top q =
    match q with
    | Empty -> failwith "top"
    | Node(_, v, _, _) -> v

let rec insert_while i ws q =
    match ws with
    | w :: ws' when fst w = i ->
        insert_while i ws' (push (snd w) q)
    | _ -> (ws, q)

let rec solve ws m q i sum =
    if i > m then sum
    else
        let (ws', q') = insert_while i ws q in
        if q' = Empty
        then solve ws' m q' (i + 1) sum
        else solve ws' m (pop q') (i + 1) (sum + top q')

let rec input n =
    if n = 0 then []
    else Scanf.scanf "%d %d\n" @@ fun a b ->
        let ws = input (n - 1) in
        (a, b) :: ws

let () =
    Scanf.scanf "%d %d\n" @@ fun n m ->
    let ws = input n in
    let ws' = List.sort (fun a b -> compare (fst a) (fst b)) ws in
    Printf.printf "%d\n" @@ solve ws' m Empty 1 0

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


type 'a t = Empty | Node of (int * 'a * 'a t * 'a t)

let rec merge q1 q2 =
    match q1, q2 with
    | Empty, _ -> q2
    | _, Empty -> q1
    | Node(n1, v1, l1, r1), Node(n2, v2, l2, r2) ->
        if v1 < v2
        then Node(n1 + n2, v2, q1, merge l2 r2)
        else Node(n1 + n2, v1, merge l1 r1, q2)

let pop q =
    match q with
    | Empty -> failwith "pop"
    | Node(_, _, l, r) ->
        match l, r with
        | Empty, Empty -> Empty
        | Node(_, _, _, _), Empty -> l
        | Node(nl, vl, ll, rl), Node(nr, vr, lr, rr) ->
            if vl < vr
            then Node(nl + nr, vr, l, merge lr rr)
            else Node(nl + nr, vl, merge ll rl, r)
        | _, _ -> failwith "pop"

let rec push x q =
    match q with
    | Empty -> Node(1, x, Empty, Empty)
    | Node(_, v, l, r) ->
        let large = max x v in
        let small = min x v in
        match l, r with
        | Empty, Empty         -> Node(2, large, Node(1, small, Empty, Empty), Empty)
        | Node(n, _, _, _), Empty -> Node(n + 2, large, push small l, Empty)
        | Node(nl, _, _, _), Node(nr, _, _, _) ->
            if nl > nr
            then Node(nl + nr + 2, large, l, push small r)
            else Node(nl + nr + 2, large, push small l, r)
        | _, _ -> failwith "push"

let top q =
    match q with
    | Empty -> failwith "top"
    | Node(_, v, _, _) -> v

let rec insert_while i ws q =
    match ws with
    | w :: ws' when fst w = i ->
        insert_while i ws' (push (snd w) q)
    | _ -> (ws, q)

let rec solve ws m q i sum =
    if i > m then sum
    else
        let (ws', q') = insert_while i ws q in
        if q' = Empty
        then solve ws' m q' (i + 1) sum
        else solve ws' m (pop q') (i + 1) (sum + top q')

let rec input n =
    if n = 0 then []
    else Scanf.scanf "%d %d\n" @@ fun a b ->
        let ws = input (n - 1) in
        (a, b) :: ws

let () =
    Scanf.scanf "%d %d\n" @@ fun n m ->
    let ws = input n in
    let ws' = List.sort (fun a b -> compare (fst a) (fst b)) ws in
    Printf.printf "%d\n" @@ solve ws' m Empty 1 0


let _ = Scanf.sscanf (read_line()) "%d %d %d" (fun a b c ->
  match c - (a - b) with
  | x when x <= 0 -> print_endline "0"
  | x -> print_endline (string_of_int x)
)

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


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


let () = Scanf.sscanf (read_line()) "%d %d" (
  fun a b ->
    if a mod 2 = b mod 2
      then print_int ((a + b) / 2)
    else print_string "IMPOSSIBLE\n"
); print_string "\n";;

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

0 \leq A,\ B \leq 10^9

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


let answer a b =
  let sa = a - b in
    if (sa mod 2) = 1 then
      "IMPOSSIBLE"
    else
      if sa < 0 then
        sa / 2 * (-1) |> string_of_int
      else
        sa / 2 |> string_of_int

let () = Scanf.scanf "%d %d" (fun a b -> print_endline (answer a b))


open Batteries
let n = read_int ()
let p = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ fun a -> a

let rec loop i ans =
  if i >= n then ans else
  if p.(i) != i+1 then loop (i+1) ans+1 else loop (i+1) ans

let _ = (if loop 0 0 > 2 then "NO" else "YES") |> print_endline

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


let c, n = ref 0, Scanf.scanf " %d" (+) 0
let _ = for i = 1 to n do Scanf.scanf " %d" @@ fun p -> if i <> p then incr c done; print_endline @@ if !c <= 2 then "YES" else "NO"


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

let borders s =
  let n = String.length s in
  let b = Array.make (n+1) (-1) in
  for i=0 to n-1 do
    let j = ref b.(i) in
    while !j >= 0 && s.[!j] <> s.[i] do
      j := b.(!j)
    done;
    b.(i+1) <- !j+1
  done;
  b

type result = [`Unknown | `Cycle | `Length of int]
type knownResult = [`Cycle | `Length of int]

let rec compare (a: result) (b: result) =
  match (a, b) with
  | (`Unknown, `Unknown) -> 0
  | (`Cycle, `Cycle) -> 0
  | (`Length x, `Length y) -> Pervasives.compare x y
  | (`Unknown, _) -> -1
  | (`Cycle, _) -> 1
  | _ -> -(compare b a)

let solve s t : knownResult =
  let n = String.length s in
  let m = String.length t in
  let b = borders t in
  let yes = Array.make n false in
  let j = ref 0 in
  for i=0 to n+m-2 do
    while !j >= 0 && (!j >= m || t.[!j] <> s.[i mod n]) do
      j := b.(!j)
    done;
    incr j;
    if !j = m then yes.(i+1-m) <- true
  done;
  let plen: result array = Array.make n `Unknown in
  let rec calc ?(start = None) i : knownResult =
    let i0 = match start with None -> i | Some i0 -> i0 in
    match plen.(i) with
    | `Unknown ->
        begin
          let ans =
            if start <> None && i = i0 then `Cycle
            else if not yes.(i) then `Length 0
            else
              match calc ~start:(Some i0) ((i + m) mod n) with
              | `Cycle -> `Cycle
              | `Length x -> `Length (1 + x)
          in
          plen.(i) <- ans;
          ans
        end
    | `Cycle -> `Cycle
    | `Length x -> `Length x
  in
  let res: knownResult ref = ref (`Length 0) in
  for i=0 to n-1 do
    let x = calc i in
    if compare (!res :> result) (x :> result) < 0 then res := x
  done;
  match !res with
  | `Cycle -> `Cycle
  | `Length x -> `Length x

let main () =
  let s = readString () in
  let t = readString () in
  Printf.printf "%d\n" (match solve s t with `Cycle -> -1 | `Length x -> x)

let () = main ()

Score : 600 points

Problem Statement

Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.

There exists a non-negative integer j such that the concatenation of i copies of t is a substring of the concatenation of j copies of s.

Notes

A string a is a substring of another string b if and only if there exists an integer x (0 \leq x \leq |b| - |a|) such that, for any y (1 \leq y \leq |a|), a_y = b_{x+y} holds.

We assume that the concatenation of zero copies of any string is the empty string. From the definition above, the empty string is a substring of any string. Thus, for any two strings s and t, i = 0 satisfies the condition in the problem statement.

Constraints

1 \leq |s| \leq 5 \times 10^5

1 \leq |t| \leq 5 \times 10^5

s and t consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s
t

Output

If the number of non-negative integers i satisfying the following condition is finite, print the maximum value of such i; if the number is infinite, print -1.

Sample Input 1

abcabab
ab

Sample Output 1

3

The concatenation of three copies of t, ababab, is a substring of the concatenation of two copies of s, abcabababcabab, so i = 3 satisfies the condition.

On the other hand, the concatenation of four copies of t, abababab, is not a substring of the concatenation of any number of copies of s, so i = 4 does not satisfy the condition.

Similarly, any integer greater than 4 does not satisfy the condition, either. Thus, the number of non-negative integers i satisfying the condition is finite, and the maximum value of such i is 3.

Sample Input 2

aa
aaaaaaa

Sample Output 2

-1

For any non-negative integer i, the concatenation of i copies of t is a substring of the concatenation of 4i copies of s. Thus, there are infinitely many non-negative integers i that satisfy the condition.

Sample Input 3

aba
baaab

Sample Output 3

0

As stated in Notes, i = 0 always satisfies the condition.


let answer a b =
  let n = a / (b * 2 + 1) in
    n

let () = Scanf.scanf "%d %d" (fun a b -> print_endline (string_of_int (answer a b)))

Score : 200 points

Problem Statement

There are N apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq D \leq 20

Input

Input is given from Standard Input in the following format:

N D

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3


let () =
    let main () =
        let n, d = Scanf.sscanf (read_line ()) "%d %d" (fun n d -> n, d) in
        let c = 2 * d + 1 in
        Printf.printf "%d\n" ((n + c - 1) / c)
    in
    main ()


let n = read_int ()
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let bs = Array.make n 0
let _ = for k = n downto 1 do let s, i = ref 0, ref 2 in while !i * k <= n do s := !s + bs.(!i * k - 1); incr i done; bs.(k - 1) <- if !s mod 2 = a_s.(k - 1) mod 2 then 0 else 1 done; Array.(Printf.printf "%d\n" @@ fold_left (+) 0 bs; iteri (fun i b -> if b = 1 then Printf.printf "%d " (i + 1)) bs)

Score : 400 points

Problem Statement

There are N empty boxes arranged in a row from left to right.
The integer i is written on the i-th box from the left (1 \leq i \leq N).

For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.

We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:

For every integer i between 1 and N (inclusive), the total number of balls contained in the boxes with multiples of i written on them is congruent to a_i modulo 2.

Does there exist a good set of choices? If the answer is yes, find one good set of choices.

Constraints

All values in input are integers.

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

a_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If a good set of choices does not exist, print -1.

If a good set of choices exists, print one such set of choices in the following format:

M
b_1 b_2 ... b_M

where M denotes the number of boxes that will contain a ball, and b_1,\ b_2,\ ...,\ b_M are the integers written on these boxes, in any order.

Sample Input 1

3
1 0 0

Sample Output 1

1
1

Consider putting a ball only in the box with 1 written on it.

There are three boxes with multiples of 1 written on them: the boxes with 1, 2, and 3. The total number of balls contained in these boxes is 1.

There is only one box with a multiple of 2 written on it: the box with 2. The total number of balls contained in these boxes is 0.

There is only one box with a multiple of 3 written on it: the box with 3. The total number of balls contained in these boxes is 0.

Thus, the condition is satisfied, so this set of choices is good.

Sample Input 2

5
0 0 0 0 0

Sample Output 2

0

Putting nothing in the boxes can be a good set of choices.


let () =
    let main () =
        let n = int_of_string (read_line ()) in
        if n <> 1 && n mod 2 = 1 then (
            print_endline "Yes";
            for i = 1 to (n - 1) / 2 do
                Printf.printf "%d %d\n" 1 (2 * i);
                Printf.printf "%d %d\n" (2 * i) (2 * i + 1);
                Printf.printf "%d %d\n" 1 (2 * i + 1 + n);
                Printf.printf "%d %d\n" (2 * i + n) (2 * i + 1 + n);
            done;
            Printf.printf "%d %d\n" 3 (n + 1)
        ) else print_endline "No"
    in
    main ()

Score : 700 points

Problem Statement

You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes.

Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, the bitwise XOR of the weights of the vertices on the path between Vertex i and N+i (including themselves) is i.

Constraints

N is an integer.

1 \leq N \leq 10^{5}

Input

Input is given from Standard Input in the following format:

N

Output

If there exists a tree satisfying the condition in the statement, print Yes; otherwise, print No.
Then, if such a tree exists, print the 2N-1 edges of such a tree in the subsequent 2N-1 lines, in the following format:

a_{1} b_{1}
\vdots
a_{2N-1} b_{2N-1}

Here each pair (a_i, b_i) means that there is an edge connecting Vertex a_i and b_i. The edges may be printed in any order.

Sample Input 1

3

Sample Output 1

Yes
1 2
2 3
3 4
4 5
5 6

The sample output represents the following graph:

Sample Input 2

1

Sample Output 2

No

There is no tree satisfying the condition.


Scanf.sscanf (read_line ()) "%d %d %d" (fun n a b ->
    Printf.printf "%d\n" (min b (a * n)))

Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


let is_integer xs ys =
  let dim = Array.length xs in
  let sq_dist = Array.fold_left ( + ) 0 @@
    Array.init dim @@ fun i -> (xs.(i) - ys.(i)) * (xs.(i) - ys.(i)) in
  let check = Array.exists (fun d -> d * d = sq_dist) (Array.init 160 @@ fun i -> (i + 1)) in
  if check then 1 else 0

let () = Scanf.scanf "%d %d\n" @@ fun n d ->
  let points =
    Array.init n @@ fun _ ->
      Array.init d @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let check_boxes =
    Array.init (n - 1) @@ fun i ->
      Array.init (n - 1 - i) @@ fun j -> is_integer points.(i) points.(i + j + 1) in
  let ans =
    Array.fold_left (Array.fold_left ( + )) 0 check_boxes in
  Printf.printf "%d\n" ans

(*
  Array.fold_left: ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
  1つ目の fold_left は (int -> int array -> int) -> int -> int array array -> int
  2つ目の fold_left は ( + ) を渡しているので ('a -> 'a array -> 'a) になる
  ここで期待するのは int -> int list -> int
*)

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


let is_integer xs ys =
  let dim = Array.length xs in
  let sq_dist = Array.fold_left ( + ) 0 @@
    Array.init dim @@ fun i -> (xs.(i) - ys.(i)) * (xs.(i) - ys.(i)) in
  let check = Array.exists (fun d -> d * d = sq_dist) (Array.init 44 @@ fun i -> (i + 1)) in
  if check then 1 else 0

let () = Scanf.scanf "%d %d\n" @@ fun n d ->
  let points =
    Array.init n @@ fun _ ->
      Array.init d @@ fun _ -> Scanf.scanf " %d" Fun.id in
  let check_boxes =
    Array.init (n - 1) @@ fun i ->
      Array.init (n - 1 - i) @@ fun j -> is_integer points.(i) points.(i + j) in
  let ans =
    Array.fold_left (Array.fold_left ( + )) 0 check_boxes in
  Printf.printf "%d\n" ans

(*
  Array.fold_left: ('a -> 'b -> 'a) -> 'a -> 'b array -> 'a
  1つ目の fold_left は (int -> int array -> int) -> int -> int array array -> int
  2つ目の fold_left は ( + ) を渡しているので ('a -> 'a array -> 'a) になる
  ここで期待するのは int -> int list -> int
*)


let ans, n, xss = Scanf.(scanf "%d %d" @@ fun n d -> ref 0, n, Array.(init n @@ fun _ -> init d @@ fun _ -> scanf " %d" (+) 0))
let rec f n i = if i * i >= n then i * i = n else f n (i + 1)
let g a b = let s = ref 0 in Array.iteri (fun i x -> s := !s + (x - b.(i)) * (x - b.(i))) a; !s
let _ = for i = 0 to n - 1 do for j = i + 1 to n - 1 do if f (g xss.(i) xss.(j)) 0 then incr ans done done; Printf.printf "%d\n" !ans


let rec fix f x = f (fix f) x
let ans =
  Scanf.scanf "%d" @@ fun n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let w0 =
    (0, min a.(0) a.(n-1) + 1) |> fix (fun f (l, r) ->
      if l+1 >= r then l else
        let m = (l+r) / 2 in
        let w = Array.fold_left (fun w h -> h - w) m a in
        if w < m then f (l, m) else f (m, r))
  in
  let wn, h' = Array.fold_left (fun (w, acc) h -> (h-w, (2*w)::acc)) (w0, []) a in
  List.rev h' |> List.iter (Printf.printf "%d ");
  print_newline ()

Score : 400 points

Problem Statement

There are N mountains in a circle, called Mountain 1, Mountain 2, ..., Mountain N in clockwise order. N is an odd number.

Between these mountains, there are N dams, called Dam 1, Dam 2, ..., Dam N. Dam i (1 \leq i \leq N) is located between Mountain i and i+1 (Mountain N+1 is Mountain 1).

When Mountain i (1 \leq i \leq N) receives 2x liters of rain, Dam i-1 and Dam i each accumulates x liters of water (Dam 0 is Dam N).

One day, each of the mountains received a non-negative even number of liters of rain.

As a result, Dam i (1 \leq i \leq N) accumulated a total of A_i liters of water.

Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

Constraints

All values in input are integers.

3 \leq N \leq 10^5-1

N is an odd number.

0 \leq A_i \leq 10^9

The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print N integers representing the number of liters of rain Mountain 1, Mountain 2, ..., Mountain N received, in this order.

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

If we assume Mountain 1, 2, and 3 received 4, 0, and 4 liters of rain, respectively, it is consistent with this input, as follows:

Dam 1 should have accumulated \frac{4}{2} + \frac{0}{2} = 2 liters of water.

Dam 2 should have accumulated \frac{0}{2} + \frac{4}{2} = 2 liters of water.

Dam 3 should have accumulated \frac{4}{2} + \frac{4}{2} = 4 liters of water.

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0


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

let () = Scanf.scanf "%d %d\n" @@ fun n q ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d %d %d\n" @@ fun a b c d ->
      es.(a - 1) <- (b - 1, c, d) :: es.(a - 1);
      es.(b - 1) <- (a - 1, c, d) :: es.(b - 1)
  done;
  let dist = Array.make n (-1) in
  let depth = Array.make n 0 in
  let count_colors = Array.make n IntMap.empty in
  let acc_colors = Array.make n IntMap.empty in
  let parent = Array.make_matrix 17 n 0 in
  let rec visit c cd d dp u v =
    if 0 <= dist.(v) then ()
    else begin
      dist.(v) <- d;
      depth.(v) <- dp;
      parent.(0).(v) <- u;
      acc_colors.(v) <- cd;
      count_colors.(v) <- c;
      List.iter (fun (u, c', d') ->
        visit
          (IntMap.add c'
            (1 +
              try IntMap.find c' c
              with Not_found -> 0) c)
          (IntMap.add c'
            (d' +
              try IntMap.find c' cd
              with Not_found -> 0) cd)
          (d + d') (1 + dp) v u) es.(v)
    end in
  visit IntMap.empty IntMap.empty 0 0 0 0;
  for i = 1 to 16 do
    for v = 0 to n - 1 do
      parent.(i).(v) <- parent.(i - 1).(parent.(i - 1).(v))
    done
  done;
  let rec up d v i =
    if i < 0 then v
    else up d (if d land (1 lsl i) = 0 then v else parent.(i).(v)) (i - 1) in
  let up d v = up d v 16 in
  let rec lca u v = function
    | 0 ->
        if parent.(0).(u) = parent.(0).(v)
        then parent.(0).(u)
        else parent.(1).(u)
    | i ->
        ( if parent.(i).(u) = parent.(i).(v)
          then lca u v
          else lca (parent.(i).(u)) (parent.(i).(u)) ) (i - 1) in
  let lca u v =
    if u = v then u
    else
      lca
        (up (max 0 (depth.(u) - depth.(v))) u)
        (up (max 0 (depth.(v) - depth.(u))) v) 16 in
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d %d %d\n" @@ fun x y u v ->
      let w = lca (u - 1) (v - 1) in
      Printf.printf "%d\n" @@
      (dist.(u - 1) - (try IntMap.find x acc_colors.(u - 1) with Not_found -> 0) + y * (try IntMap.find x count_colors.(u - 1) with Not_found -> 0))
      + (dist.(v - 1) - (try IntMap.find x acc_colors.(v - 1) with Not_found -> 0) + y * (try IntMap.find x count_colors.(v - 1) with Not_found -> 0))
      - 2 * (dist.(w) - (try IntMap.find x acc_colors.(w) with Not_found -> 0) + y * (try IntMap.find x count_colors.(w) with Not_found -> 0))
  done

Score : 600 points

Problem Statement

There is a tree with N vertices numbered 1 to N.
The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively.
Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and different integers correspond to different colors.

Answer the following Q queries:

Query j (1 \leq j \leq Q): assuming that the length of every edge whose color is x_j is changed to y_j, find the distance between Vertex u_j and Vertex v_j. (The changes of the lengths of edges do not affect the subsequent queries.)

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

1 \leq a_i, b_i \leq N

1 \leq c_i \leq N-1

1 \leq d_i \leq 10^4

1 \leq x_j \leq N-1

1 \leq y_j \leq 10^4

1 \leq u_j < v_j \leq N

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1 c_1 d_1
:
a_{N-1} b_{N-1} c_{N-1} d_{N-1}
x_1 y_1 u_1 v_1
:
x_Q y_Q u_Q v_Q

Output

Print Q lines. The j-th line (1 \leq j \leq Q) should contain the answer to Query j.

Sample Input 1

5 3
1 2 1 10
1 3 2 20
2 4 4 30
5 2 1 40
1 100 1 4
1 100 1 5
3 1000 3 4

Sample Output 1

130
200
60

The graph in this input is as follows:

Here the edges of Color 1 are shown as solid red lines, the edge of Color 2 is shown as a bold green line, and the edge of Color 4 is shown as a blue dashed line.

Query 1: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 4 is 100 + 30 = 130.

Query 2: Assuming that the length of every edge whose color is 1 is changed to 100, the distance between Vertex 1 and Vertex 5 is 100 + 100 = 200.

Query 3: Assuming that the length of every edge whose color is 3 is changed to 1000 (there is no such edge), the distance between Vertex 3 and Vertex 4 is 20 + 10 + 30 = 60. Note that the edges of Color 1 now have their original lengths.


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

let () = Scanf.scanf "%d %d\n" @@ fun n q ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d %d %d\n" @@ fun a b c d ->
      es.(a - 1) <- (b - 1, c, d) :: es.(a - 1);
      es.(b - 1) <- (a - 1, c, d) :: es.(b - 1)
  done;
  let dist = Array.make n (-1) in
  let count_colors = Array.make n IntMap.empty in
  let acc_colors = Array.make n IntMap.empty in
  let parent = Array.make_matrix 17 n 0 in
  let rec visit c cd d u v =
    if 0 <= dist.(v) then ()
    else begin
      dist.(v) <- d;
      parent.(0).(v) <- u;
      acc_colors.(v) <- cd;
      count_colors.(v) <- c;
      List.iter (fun (u, c', d') ->
        visit
          (IntMap.add c'
            (1 +
              try IntMap.find c' c
              with Not_found -> 0) c)
          (IntMap.add c'
            (d' +
              try IntMap.find c' cd
              with Not_found -> 0) cd)
          (d + d') v u) es.(v)
    end in
  visit IntMap.empty IntMap.empty 0 0 0;
  for i = 1 to 16 do
    for v = 0 to n - 1 do
      parent.(i).(v) <- parent.(i - 1).(parent.(i - 1).(v))
    done
  done;
  let rec lca u v = function
    | 0 ->
        if u = v then u
        else if parent.(0).(u) = parent.(0).(v)
        then parent.(0).(u)
        else parent.(1).(u)
    | i ->
        ( if parent.(i).(u) = parent.(i).(v)
          then lca u v
          else lca (parent.(i).(u)) (parent.(i).(u)) ) (i - 1) in
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d %d %d\n" @@ fun x y u v ->
      let w = lca (u - 1) (v - 1) 16 in
      Printf.printf "%d\n" @@
      (dist.(u - 1) - (try IntMap.find x acc_colors.(u - 1) with Not_found -> 0) + y * (try IntMap.find x count_colors.(u - 1) with Not_found -> 0))
      + (dist.(v - 1) - (try IntMap.find x acc_colors.(v - 1) with Not_found -> 0) + y * (try IntMap.find x count_colors.(v - 1) with Not_found -> 0))
      - 2 * (dist.(w) - (try IntMap.find x acc_colors.(w) with Not_found -> 0) + y * (try IntMap.find x count_colors.(w) with Not_found -> 0))
  done


open Batteries
let explode s = List.init (String.length s) (String.get s)
let s = read_line () |> explode

let get_all_elements l =
  let rec get existed lst =
    match lst with
     [] -> existed
    | first :: rest -> if List.exists (fun a -> a = first) existed then get existed rest
                       else get (first :: existed) rest
  in get [] l

let ans l =
  let rec p lst =
    match lst with
    | [] -> true
    | first :: rest -> if List.length (List.find_all (fun a -> a = first) s) = 2 then p rest else false
  in p l

let all = get_all_elements s
let _ = if List.length all != 2 then print_endline "No"
        else if ans all then print_endline "Yes" else print_endline "No"

Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


open Printf
open Scanf

let solve s =
  let l = List.sort compare @@ List.map (fun i -> String.get s i) [0;1;2;3] in
  match l with
    a::b::c::d::_ when a = b && c = d && b <> c -> "Yes"
  | _ -> "No"

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


let inp : unit -> string = fun () ->
  input_line stdin

let () =
  let s = inp () in
  let rec count n l =
    if n = 4 then
      l
    else
      if List.mem s.[n] l then
        count (n + 1) l
      else
        count (n + 1) (s.[n] :: l)
  in
  let c = List.length (count 0 []) in
  let n =
    let rec f n m =
          if n = 4 then
            m
          else
            if s.[n] = s.[0] then
              f (n + 1) (m + 1)
            else
              f (n + 1) m in
    f 0 0
  in
  if c = 2 && n = 2 then
    print_endline "Yes"
  else
    print_endline "No"


let ans, n = ref 0, Scanf.scanf " %d" (+) 0
let ps = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let _ = for i = 1 to n - 2 do if ps.(i - 1) < ps.(i) && ps.(i) < ps.(i + 1) || ps.(i - 1) > ps.(i) && ps.(i) > ps.(i + 1) then incr ans done; Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


open Batteries

let read_two () = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> (a, b))

let read_three () =
  Scanf.sscanf (read_line ()) "%d %d %d" (fun a b c -> (a, b, c))

let read_four () =
  Scanf.sscanf (read_line ()) "%d %d %d" (fun a b c d -> (a, b, c, d))

let read_list () =
  read_line () |> String.split_on_char ' '
  |> List.map (fun s -> int_of_string s)

(* a**x *)
let pow a x =
  let rec aux acc = function 0 -> acc | n -> aux (acc * a) (n - 1) in
  aux 1 x

let rec pow2 n = if n mod 2 = 0 then 1 + pow2 (n / 2) else 0

let rec f n = function
  | d1 :: d2 :: rest -> if n = 1 then (d1, d2) else f (n - 2) rest
  | _ -> (0, 0)

let () =
  let n = read_int () in
  let d = read_list () |> List.sort compare in
  let a, b = f (n / 2) d in
  print_int (b - a);
  print_newline ()

Score : 300 points

Problem Statement

Takahashi made N problems for competitive programming.
The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder).

He is dividing the problems into two categories by choosing an integer K, as follows:

A problem with difficulty K or higher will be for ARCs.

A problem with difficulty lower than K will be for ABCs.

How many choices of the integer K make the number of problems for ARCs and the number of problems for ABCs the same?

Problem Statement

2 \leq N \leq 10^5

N is an even number.

1 \leq d_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the number of choices of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 1

6
9 1 4 4 6 7

Sample Output 1

2

If we choose K=5 or 6, Problem 1, 5, and 6 will be for ARCs, Problem 2, 3, and 4 will be for ABCs, and the objective is achieved.
Thus, the answer is 2.

Sample Input 2

8
9 1 14 5 5 4 4 14

Sample Output 2

0

There may be no choice of the integer K that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 3

14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1

Sample Output 3

42685


open Batteries

let read_two () = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> (a, b))

let read_three () =
  Scanf.sscanf (read_line ()) "%d %d %d" (fun a b c -> (a, b, c))

let read_four () =
  Scanf.sscanf (read_line ()) "%d %d %d" (fun a b c d -> (a, b, c, d))

let read_list () =
  read_line () |> String.split_on_char ' '
  |> List.map (fun s -> int_of_string s)

(* a**x *)
let pow a x =
  let rec aux acc = function 0 -> acc | n -> aux (acc * a) (n - 1) in
  aux 1 x

let rec pow2 n = if n mod 2 = 0 then 1 + pow2 (n / 2) else 0

let rec f n = function
  | d1 :: d2 :: rest -> if n = 1 then (d1, d2) else f (n - 2) rest
  | _ -> invalid_arg "list smaller than n/2"

let () =
  let n = read_int () in
  let d = read_list () |> List.sort compare in
  let a, b = f (n / 2) d in
  print_int (b - a);
  print_newline ()


let () =
  Printf.printf "%d\n" @@
  Scanf.scanf "%d" @@ fun n ->
  let d = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  Array.sort (-) d;
  if n mod 2 = 1 then 0 else d.(n/2) - d.(n/2-1)


let modulo = 1_000_000_007
let (+%) a b = (a + b) mod modulo
let (-%) a b = let tmp = (a - b) mod modulo in
               if tmp >= 0 then tmp
               else tmp + modulo
let ( *% ) a b = (a * b) mod modulo
let rec ( **% ) a n =
  if n = 0 then 1
  else if n mod 2 = 1 then a *% a **% (n - 1)
  else let t = a **% (n / 2) in t *% t
let (/%) a b =
  let inv a = a **% (modulo - 2)
  in
  a *% inv b

let m_fact = Array.make 3000 (-1)
let rec fact n =
  if n <= 0 then 1
  else
    if m_fact.(n) >= 0 then m_fact.(n)
    else (m_fact.(n) <- n *% fact (n - 1);
          m_fact.(n))

let m_nCr = Array.make_matrix 3000 3000 (-1)
let rec nCr n r =
  fact n /% fact (n - r) /% fact r

let () =
  let (n, k) = Scanf.sscanf (input_line stdin) "%d %d" (fun a b -> (a, b)) in
  let rec loop i =
    if i > k then ()
    else
      let ans = nCr (n-k+1) i *% nCr (k-1) (i-1) in
      (print_int ans;
       print_newline ();
       loop (i + 1))
  in loop 1

Score : 400 points

Problem Statement

There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.

First, Snuke will arrange the N balls in a row from left to right.

Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive blue balls. He will collect all the blue balls in the fewest moves possible.

How many ways are there for Snuke to arrange the N balls in a row so that Takahashi will need exactly i moves to collect all the blue balls? Compute this number modulo 10^9+7 for each i such that 1 \leq i \leq K.

Constraints

1 \leq K \leq N \leq 2000

Input

Input is given from Standard Input in the following format:

N K

Output

Print K lines. The i-th line (1 \leq i \leq K) should contain the number of ways to arrange the N balls so that Takahashi will need exactly i moves to collect all the blue balls, modulo 10^9+7.

Sample Input 1

5 3

Sample Output 1

3
6
1

There are three ways to arrange the balls so that Takahashi will need exactly one move: (B, B, B, R, R), (R, B, B, B, R), and (R, R, B, B, B). (R and B stands for red and blue, respectively).

There are six ways to arrange the balls so that Takahashi will need exactly two moves: (B, B, R, B, R), (B, B, R, R, B), (R, B, B, R, B), (R, B, R, B, B), (B, R, B, B, R), and (B, R, R, B, B).

There is one way to arrange the balls so that Takahashi will need exactly three moves: (B, R, B, R, B).

Sample Input 2

2000 3

Sample Output 2

1998
3990006
327341989

Be sure to print the numbers of arrangements modulo 10^9+7.


let n, k = Scanf.scanf " %d %d" @@ fun a b -> a, b
let r = n - k
let memo = Array.make_matrix 4010 4010 @@ -1
let rec comb n k =
  if memo.(n).(k) > -1 then memo.(n).(k)
  else
    (memo.(n).(k) <- if n < k then 0 else if n = k then 1 else if k = 0 then 1
      else (comb (n - 1) (k - 1) + comb (n - 1) k) mod 1_000_000_007;
    memo.(n).(k))
let h n k = comb (n + k - 1) k
let _ =
  for i = 1 to k do
    Printf.printf "%d\n" @@ comb (k - 1) (i - 1) * h (i + 1) (r - i + 1) mod 1_000_000_007 done


let n, l, m = Scanf.scanf " %d %d" @@ fun a b -> a, b, b + a - 1
let _ = Printf.printf "%d\n" @@ n * (l + m) / 2 - if l * m <= 0 then 0 else snd @@ min (abs l, l) (abs m, m)

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


module Union_find : sig
  type t
  val make : int -> t
  val find : int -> t -> int
  val size : int -> t -> int
  val same : int -> int -> t -> bool
  val unite : int -> int -> t -> unit
end = struct
  type t = int array
  let make n = Array.make n (-1)
  let rec find x uf =
    if uf.(x) < 0 then x
    else (( let x' = find uf.(x) uf in uf.(x) <- x'; x' ))
  let same x y uf = find x uf = find y uf
  let size x uf = - uf.(find x uf)
  let unite x y uf =
    let x = find x uf and y = find y uf in
    if x <> y then
      if uf.(x) < uf.(y) then ((
        uf.(x) <- uf.(x) + uf.(y);
        uf.(y) <- x
      )) else ((
        uf.(y) <- uf.(x) + uf.(y);
        uf.(x) <- y
      ))
end
module UF = Union_find

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

let () =
  Scanf.scanf "%d" @@ fun n ->
  let uf = UF.make 100000 in
  let xy = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x-1, y-1)) in
  Array.sort (fun (a,_) (c,_) -> a-c) xy;
  let _ = Array.fold_left (fun (u, v) (w, x) ->
    if u = w then UF.unite v x uf; (w, x)
  ) (-1, -1) xy in
  let ss = Array.fold_left (fun ss (x, y) ->
    let k = UF.find x uf in
    try M.add k (S.add y (M.find k ss)) ss
    with Not_found -> M.add k (S.singleton y) ss
  ) M.empty xy in
  let t = M.fold (fun k v s -> UF.size k uf * S.cardinal v + s) ss 0 in
  Printf.printf "%d\n" (t - n)

Score : 600 points

Problem Statement

There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).

We will repeat the following operation as long as possible:

Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at the remaining position.

We can prove that we can only do this operation a finite number of times. Find the maximum number of times we can do the operation.

Constraints

1 \leq N \leq 10^5

1 \leq x_i, y_i \leq 10^5

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the maximum number of times we can do the operation.

Sample Input 1

3
1 1
5 1
5 5

Sample Output 1

1

By choosing a = 1, b = 1, c = 5, d = 5, we can add a dot at (1, 5). We cannot do the operation any more, so the maximum number of operations is 1.

Sample Input 2

2
10 10
20 20

Sample Output 2

0

There are only two dots, so we cannot do the operation at all.

Sample Input 3

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

Sample Output 3

16

We can do the operation for all choices of the form a = 1, b = 1, c = i, d = j (2 \leq i,j \leq 5), and no more. Thus, the maximum number of operations is 16.


module Union_find : sig
  type t
  val make : int -> t
  val find : int -> t -> int
  val size : int -> t -> int
  val same : int -> int -> t -> bool
  val unite : int -> int -> t -> unit
end = struct
  type t = int array
  let make n = Array.make n (-1)
  let rec find x uf =
    if uf.(x) < 0 then x
    else (( let x' = find uf.(x) uf in uf.(x) <- x'; x' ))
  let same x y uf = find x uf = find y uf
  let size x uf = - uf.(find x uf)
  let unite x y uf =
    let x = find x uf and y = find y uf in
    if x <> y then
      if uf.(x) < uf.(y) then ((
        uf.(x) <- uf.(x) + uf.(y);
        uf.(y) <- x
      )) else ((
        uf.(y) <- uf.(x) + uf.(y);
        uf.(x) <- y
      ))
end
module UF = Union_find

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

let () =
  Scanf.scanf "%d" @@ fun n ->
  let uf = UF.make 10000 in
  let xy = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x-1, y-1)) in
  Array.sort (fun (a,_) (c,_) -> a-c) xy;
  let _ = Array.fold_left (fun (u, v) (w, x) ->
    if u = w then UF.unite v x uf; (w, x)
  ) (-1, -1) xy in
  let ss = Array.fold_left (fun ss (x, y) ->
    let k = UF.find x uf in
    try M.add k (S.add y (M.find k ss)) ss
    with Not_found -> M.add k (S.singleton y) ss
  ) M.empty xy in
  let t = M.fold (fun k v s -> UF.size k uf * S.cardinal v + s) ss 0 in
  Printf.printf "%d\n" (t - n)


let rounding x a = if x < a then 0 else 10

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

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


let f x a = match a-x with
y when y > 0 -> 10
| y when y <= 0 -> 0;;
let () = Scanf.scanf "%d %d" f
|> Printf.printf "%d\n"


let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then (
                if flag then cur :: acc else acc
            ) else (
                match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) 0 false (cur :: acc)
                | false, ' ' -> loop (i + 1) 0 false acc
                | true,  v   -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc
                | false, v   -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc
            )
        in
        List.rev (loop 0 0 false [])
    in
    let main () =
        let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun n k -> n, k) in
        let arrs = Array.of_list (split (read_line ())) in
        let arrt = Array.of_list (split (read_line ())) in
        let mat = Array.make_matrix (n + 1) (m + 1) 1 in
        let mm = 1000000000 + 7 in
        for y = 1 to n do
            for x = 1 to m do
                mat.(y).(x) <- (mat.(y - 1).(x) + mat.(y).(x - 1) +
                    if arrs.(y - 1) = arrt.(x - 1) then 0 else -mat.(y - 1).(x - 1) + mm) mod mm
            done
        done;
        Printf.printf "%d\n" mat.(n).(m)
    in
    main ()

Score : 500 points

Problem Statement

You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive).

In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content?

Here the subsequence of A is a sequence obtained by removing zero or more elements from A and concatenating the remaining elements without changing the order.

For both S and T, we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Since the answer can be tremendous, print the number modulo 10^9+7.

Constraints

1 \leq N, M \leq 2 \times 10^3

The length of S is N.

The length of T is M.

1 \leq S_i, T_i \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
S_1 S_2 ... S_{N-1} S_{N}
T_1 T_2 ... T_{M-1} T_{M}

Output

Print the number of pairs of a subsequence of S and a subsequence of T such that the subsequences are the same in content, modulo 10^9+7.

Sample Input 1

2 2
1 3
3 1

Sample Output 1

3

S has four subsequences: (), (1), (3), (1, 3).

T has four subsequences: (), (3), (1), (3, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 1 \times 1 pair of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (3), for a total of three pairs.

Sample Input 2

2 2
1 1
1 1

Sample Output 2

6

S has four subsequences: (), (1), (1), (1, 1).

T has four subsequences: (), (1), (1), (1, 1).

There are 1 \times 1 pair of subsequences in which the subsequences are both (), 2 \times 2 pairs of subsequences in which the subsequences are both (1), and 1 \times 1 pair of subsequences in which the subsequences are both (1,1), for a total of six pairs.
Note again that we distinguish two subsequences if the sets of the indices of the removed elements are different, even if the subsequences are the same in content.

Sample Input 3

4 4
3 4 5 6
3 4 5 6

Sample Output 3

16

Sample Input 4

10 9
9 6 5 7 5 9 8 5 6 7
8 6 8 5 5 7 9 9 7

Sample Output 4

191

Sample Input 5

20 20
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

Sample Output 5

846527861

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


module Array = ArrayLabels
module List = ListLabels

let inf = 1000000000.
let (>>=) x f = List.map f x |> List.concat

let () =
  Scanf.scanf "%d" @@ fun n ->
  let xyds = Array.init n (fun _ -> Scanf.scanf " %f %f %s" (fun x y d -> x, y, d)) in
  let find_edges axis dir =
    Array.fold_left xyds ~init:(inf, -.inf) ~f:(fun (minv, maxv) (x, y, d) ->
      let v = match axis with `X -> x | `Y -> y in
      if d = dir then (min minv v, max maxv v) else (minv, maxv))
  in
  let dirs = ["R"; "L"; "U"; "D"] in
  let exs = List.map dirs ~f:(fun d ->
    let x1, x2 = find_edges `X d in
    (x1, x2, match d with "R" -> 1. | "L" -> -1. | _ -> 0.))
  and eys = List.map dirs ~f:(fun d ->
    let y1, y2 = find_edges `Y d in
    (y1, y2, match d with "U" -> 1. | "D" -> -1. | _ -> 0.))
  in

  let area_of_time (t : float) =
    let (+), (-), ( * ) = (+.), (-.), ( *.) in
    let xm, xM = List.fold_left exs ~init:(inf, -.inf) ~f:(fun (xm, xM) (x1, x2, mul) ->
      (min xm (x1 + mul * t), max xM (x2 + mul * t)))
    in
    let ym, yM = List.fold_left eys ~init:(inf, -.inf) ~f:(fun (ym, yM) (y1, y2, mul) ->
      (min ym (y1 + mul * t), max yM (y2 + mul * t)))
    in
    (xM - xm) * (yM - ym)
  in

  let txs =
    exs >>= fun (xa1, xa2, da) ->
    exs >>= fun (xb1, xb2, db) ->
      if da = db then [] else
        [xa1; xa2] >>= fun xa ->
        [xb1; xb2] >>= fun xb -> [abs_float @@ (xa -. xb) /. (da -. db)]
  and tys =
    eys >>= fun (ya1, ya2, da) ->
    eys >>= fun (yb1, yb2, db) ->
      if da = db then [] else
        [ya1; ya2] >>= fun ya ->
        [yb1; yb2] >>= fun yb -> [abs_float @@ (ya -. yb) /. (da -. db)]
  in
  List.map area_of_time ([0.] @ txs @ tys) |> List.fold_left ~f:min ~init:inf
  |> Printf.printf "%.11f\n"

Score : 600 points

Problem Statement

There are N points in a two-dimensional plane. The initial coordinates of the i-th point are (x_i, y_i). Now, each point starts moving at a speed of 1 per second, in a direction parallel to the x- or y- axis. You are given a character d_i that represents the specific direction in which the i-th point moves, as follows:

If d_i = R, the i-th point moves in the positive x direction;

If d_i = L, the i-th point moves in the negative x direction;

If d_i = U, the i-th point moves in the positive y direction;

If d_i = D, the i-th point moves in the negative y direction.

You can stop all the points at some moment of your choice after they start moving (including the moment they start moving).
Then, let x_{max} and x_{min} be the maximum and minimum among the x-coordinates of the N points, respectively. Similarly, let y_{max} and y_{min} be the maximum and minimum among the y-coordinates of the N points, respectively.

Find the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}) and print it.

Constraints

1 \leq N \leq 10^5

-10^8 \leq x_i,\ y_i \leq 10^8

x_i and y_i are integers.

d_i is R, L, U, or D.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1 d_1
x_2 y_2 d_2
.
.
.
x_N y_N d_N

Output

Print the minimum possible value of (x_{max} - x_{min}) \times (y_{max} - y_{min}).

The output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-9}.

Sample Input 1

2
0 3 D
3 0 L

Sample Output 1

0

After three seconds, the two points will meet at the origin. The value in question will be 0 at that moment.

Sample Input 2

5
-7 -10 U
7 -6 U
-8 7 D
-3 3 D
0 -6 R

Sample Output 2

97.5

The answer may not be an integer.

Sample Input 3

20
6 -10 R
-4 -9 U
9 6 D
-3 -2 R
0 7 D
4 5 D
10 -10 U
-1 -8 U
10 -6 D
8 -5 U
6 4 D
0 3 D
7 9 R
9 -4 R
3 10 D
1 9 U
1 -6 U
9 -8 R
6 7 D
7 -3 D

Sample Output 3

273


let dir = function "R" -> 0 | "U" -> 1 | "L" -> 2 | _ -> 3
let foi = float_of_int
let () =
  Scanf.scanf "%d" @@ fun n ->
  let xyd = Array.init n (fun _ -> Scanf.scanf " %d %d %s" @@ fun x y d -> x, y, dir d) in
  let calc1 d =
    let fld, v0, g =
      if d < 2 then max, min_int, (fun x -> x)
      else          min, max_int, (fun x -> -x)
    in
    let c = Array.fold_left (fun v (x,y,d') ->
      if (d-d'+4) mod 2 = 1 then fld v (if d mod 2 = 0 then y else x) else v
    ) v0 xyd
    in
    let i = Array.fold_left (fun v (x,y,d') ->
      if d = d' then fld v (if d mod 2 = 0 then x else y) else v
    ) v0 xyd in
    let r = Array.fold_left (fun v (x,y,d') ->
      if (d-d'+4) mod 4 = 2 then fld v (if d mod 2 = 0 then x else y) else v
    ) v0 xyd
    in
    [ 2 * g (r - c);
      2 * g (c - i);
      g (r - i); ]
  in
  let calc2 t =
    let xmin, xmax, ymin, ymax =
      Array.fold_left (fun (xmin, xmax, ymin, ymax) (x,y,d) ->
        let x, y = foi x, foi y in
        let x, y = match d with
          | 0 -> x +. t, y
          | 1 -> x,      y +. t
          | 2 -> x -. t, y
          | _ -> x,      y -. t
        in
        min xmin x, max xmax x, min ymin y, max ymax y) (1e30, -.1e30, 1e30, -.1e30) xyd
    in
    (xmax -. xmin) *. (ymax -. ymin)
  in
  List.concat [calc1 0; calc1 1; calc1 2; calc1 3; ]
  |> List.filter (fun x -> 0 <= x && x <= 100000)
  |> List.sort_uniq (-)
  |> List.fold_left (fun v t -> min v (calc2 (foi t /. 2.0))) max_float
  |> Printf.printf "%.10f\n"


(* O(n^4) *)
let n = Scanf.scanf " %d" @@ (+) 0
let xys = Array.init n @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let ans = ref max_int
let _ =
  if n = 1 then (print_endline "1"; exit 0);
  (xys |> Array.iteri @@ fun i (x0, y0) ->
    xys |> Array.iteri @@ fun j (x, y) ->
      if i <> j then
        let p, q = x - x0, y - y0 in
        let e = ref 0 in
        xys |> Array.iter @@ fun (x1, y1) ->
          (xys |> Array.iter @@ fun (x2, y2) ->
            if x2 - x1 = p && y2 - y1 = q then incr e);
          ans := min !ans @@ n - !e);
  Printf.printf "%d\n" @@ !ans

Score : 300 points

Problem Statement

There are N balls in a two-dimensional plane. The i-th ball is at coordinates (x_i, y_i).

We will collect all of these balls, by choosing two integers p and q such that p \neq 0 or q \neq 0 and then repeating the following operation:

Choose a ball remaining in the plane and collect it. Let (a, b) be the coordinates of this ball. If we collected a ball at coordinates (a - p, b - q) in the previous operation, the cost of this operation is 0. Otherwise, including when this is the first time to do this operation, the cost of this operation is 1.

Find the minimum total cost required to collect all the balls when we optimally choose p and q.

Constraints

1 \leq N \leq 50

|x_i|, |y_i| \leq 10^9

If i \neq j, x_i \neq x_j or y_i \neq y_j.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the minimum total cost required to collect all the balls.

Sample Input 1

2
1 1
2 2

Sample Output 1

1

If we choose p = 1, q = 1, we can collect all the balls at a cost of 1 by collecting them in the order (1, 1), (2, 2).

Sample Input 2

3
1 4
4 6
7 8

Sample Output 2

1

If we choose p = -3, q = -2, we can collect all the balls at a cost of 1 by collecting them in the order (7, 8), (4, 6), (1, 4).

Sample Input 3

4
1 1
1 2
2 1
2 2

Sample Output 3

2