let () =
    let main () =
        let n = int_of_string (read_line ()) in
        let xy = Array.make_matrix n n (-1) in
        for i = 0 to n - 1 do
            let a1 = int_of_string (read_line ()) in
            for j = 0 to a1 - 1 do
                Scanf.sscanf (read_line ()) "%d %d" (fun x y -> xy.(i).(x - 1) <- y)
            done
        done;
        let bits a =
            let rec loop a acc =
                if a = 0 then acc else loop (a lsr 1) (acc + (a land 1))
            in
            loop a 0
        in
        let judge i =
            let judge2 t =
                if i land (1 lsl t) = 0 then true else (
                    let rec loop2 k =
                        if k = n then true else (
                            if xy.(t).(k) < 0 then loop2 (k + 1) else (
                                if (xy.(t).(k) = 0 && (i land (1 lsl k) = 0)) ||
                                   (xy.(t).(k) = 1 && (i land (1 lsl k) != 0)) then loop2 (k + 1)
                                else false
                            )
                        )
                    in
                    loop2 0
                )
            in
            let rec loop s =
                if s = n then true else (
                    if judge2 s then loop (s + 1) else false
                )
            in
            loop 0
        in
        let maxn = 1 lsl n in
        let rec loop i acc =
            if i = maxn then acc else
                let acc = if judge i then max acc (bits i) else acc in
                loop (i + 1) acc
        in
        let r = loop 0 0 in
        Printf.printf "%d\n" r
    in
    main ()

Score : 300 points

Problem Statement

There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.

Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.

How many honest persons can be among those N people at most?

Constraints

All values in input are integers.

1 \leq N \leq 15

0 \leq A_i \leq N - 1

1 \leq x_{ij} \leq N

x_{ij} \neq i

x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)

y_{ij} = 0, 1

Input

Input is given from Standard Input in the following format:

N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

Output

Print the maximum possible number of honest persons among the N people.

Sample Input 1

3
1
2 1
1
1 1
1
2 0

Sample Output 1

2

If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.

Sample Input 2

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

Sample Output 2

0

Assuming that one or more of them are honest immediately leads to a contradiction.

Sample Input 3

2
1
2 0
1
1 0

Sample Output 3

1


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

let () =
    let main () =
        let h, w = Scanf.scanf "%d %d" (fun h w -> h, w) in
        let a = Array.init h (fun _ -> Array.init w (fun _ -> Scanf.scanf " %d" (fun n -> n))) in
        let b = Array.init h (fun _ -> Array.init w (fun _ -> Scanf.scanf " %d" (fun n -> n))) in
        let ar = Array.make_matrix (h + 1) (w + 1) (S.singleton 0) in
        let merge s1 s2 v1 v2 =
            let s = S.fold (fun v acc -> S.add (v + v2 - v1) (S.add (v + v1 - v2) acc)) s1 S.empty in
                    S.fold (fun v acc -> S.add (v + v2 - v1) (S.add (v + v1 - v2) acc)) s2 s
        in
        for y = 1 to h do
            for x = 1 to w do
                ar.(y).(x) <- merge ar.(y - 1).(x) ar.(y).(x - 1) a.(y - 1).(x - 1) b.(y - 1).(x - 1)
            done
        done;
        let s = S.fold (fun v acc -> min (abs v) acc) ar.(h).(w) max_int in
        Printf.printf "%d\n" s
    in
    main ()

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

Score : 500 points

Problem Statement

We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.

The square (i, j) has two numbers A_{ij} and B_{ij} written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square (1, 1) to the square (H, W). In one move, he can move from a square (i, j) to the square (i+1, j) or the square (i, j+1). He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares (1, 1) and (H, W).

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

2 \leq H \leq 80

2 \leq W \leq 80

0 \leq A_{ij} \leq 80

0 \leq B_{ij} \leq 80

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W
A_{11} A_{12} \ldots A_{1W}
:
A_{H1} A_{H2} \ldots A_{HW}
B_{11} B_{12} \ldots B_{1W}
:
B_{H1} B_{H2} \ldots B_{HW}

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are 3+3+1=7 and 1+2+4=7, respectively, for the unbalancedness of 0.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2

Submitted source-code file size, in bytes.

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

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


let m1 = Scanf.sscanf (read_line()) "%d %d" (fun a b -> a)
let m2 = Scanf.sscanf (read_line()) "%d %d" (fun a b -> a)
let _ = if m1 != m2 then print_endline "1" else print_endline "0"

Score: 100 points

Problem Statement

In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019.

Integers M_1, D_1, M_2, and D_2 will be given as input.

It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1.

Determine whether the date 2019-M_1-D_1 is the last day of a month.

Constraints

Both 2019-M_1-D_1 and 2019-M_2-D_2 are valid dates in the Gregorian calendar.

The date 2019-M_2-D_2 follows 2019-M_1-D_1.

Input

Input is given from Standard Input in the following format:

M_1 D_1
M_2 D_2

Output

If the date 2019-M_1-D_1 is the last day of a month, print 1; otherwise, print 0.

Sample Input 1

11 16
11 17

Sample Output 1

0

November 16 is not the last day of a month.

Sample Input 2

11 30
12 1

Sample Output 2

1

November 30 is the last day of November.


let () =
  let n = read_int () in
  let ans = n * 100 / 108 in
  let rec check x =
    if x > 46300 then print_endline ":("
    else if x * 108 / 100 = n then print_int ans
    else check (x+1) in
  check 1

Score: 200 points

Problem Statement

Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.

The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).

Takahashi forgot the price of his apple pie before tax, X, and wants to know it again. Write a program that takes N as input and finds X. We assume X is an integer.

If there are multiple possible values for X, find any one of them. Also, Takahashi's memory of N, the amount he paid, may be incorrect. If no value could be X, report that fact.

Constraints

1 \leq N \leq 50000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If there are values that could be X, the price of the apple pie before tax, print any one of them.

If there are multiple such values, printing any one of them will be accepted.

If no value could be X, print :(.

Sample Input 1

432

Sample Output 1

400

If the apple pie is priced at 400 yen before tax, you have to pay 400 \times 1.08 = 432 yen to buy one.

Otherwise, the amount you have to pay will not be 432 yen.

Sample Input 2

1079

Sample Output 2

:(

There is no possible price before tax for which you have to pay 1079 yen with tax.

Sample Input 3

1001

Sample Output 3

927

If the apple pie is priced 927 yen before tax, by rounding down 927 \times 1.08 = 1001.16, you have to pay 1001 yen.


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

let () =
        Scanf.sscanf (read_line ()) "%f" (
        fun n ->
                let a = n /. 1.08 in
                let fa = truncate ((floor a) *. 1.08) in
                let ca = truncate ((ceil a) *. 1.08) in
                        if fa = int_of_float n then
                                string_of_int (truncate (floor a))
                        else if ca = int_of_float n then
                                string_of_int (truncate (ceil a))
                        else
                                ":("
        ) |> Printf.printf "%s\n"


let () =
  let n = read_int () in
  let ans = ref (-1) in
  for i = 0 to n do
    let x = float_of_int i *. 1.08 |> int_of_float in
    if x = n then ans := i else ()
  done;
  if !ans >= 0 then print_int !ans else print_string ":(";
  print_newline ()


let () = Scanf.scanf "%d" @@ fun n ->
  try
    Printf.printf "%d\n" @@
    List.find (fun i -> i * 108 / 100 = n) @@
    Array.to_list @@
    Array.init (n + 1) @@ fun i -> i
  with Not_found -> print_endline ":("


Scanf.scanf "%d" (fun x -> if x mod 100 > x / 100 * 5 then "0" else "1")
|> print_endline

Score: 300 points

Problem Statement

AtCoder Mart sells 1000000 of each of the six items below:

Riceballs, priced at 100 yen (the currency of Japan) each

Sandwiches, priced at 101 yen each

Cookies, priced at 102 yen each

Cakes, priced at 103 yen each

Candies, priced at 104 yen each

Computers, priced at 105 yen each

Takahashi wants to buy some of them that cost exactly X yen in total.
Determine whether this is possible.

(Ignore consumption tax.)

Constraints

1 \leq X \leq 100000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

If it is possible to buy some set of items that cost exactly X yen in total, print 1; otherwise, print 0.

Sample Input 1

615

Sample Output 1

1

For example, we can buy one of each kind of item, which will cost 100+101+102+103+104+105=615 yen in total.

Sample Input 2

217

Sample Output 2

0

No set of items costs 217 yen in total.


open Batteries

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

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

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

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

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

let n = scan "%d" identity
let s = scan "%s" identity

let () =
  Enum.Labels.map (0 --^ 1000)
    ~f:(fun i ->
        let d = String.to_list @@ Printf.sprintf "%03d" i in
        let (result, _) = List.Labels.fold_left d
            ~init:(true, 0) ~f:(fun (b, i) c ->
                if b then
                  let e = String.of_char c in
                  match String.Exceptionless.find_from s i e with
                  | Some i -> (true, i+1)
                  | None -> (false, i)
                else (false, i))
        in
        if result then 1 else 0)
  |> Enum.sum
  |> Printf.printf "%d\n"

Score: 400 points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.

The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a 0.

Constraints

4 \leq N \leq 30000

S is a string of length N consisting of digits.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of S and set 224.

Erase the second digit of S and set 024.

Erase the third digit of S and set 024.

Erase the fourth digit of S and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329


let m_1e9 = int_of_float 1e9 + 7
let ( *^ ) x y = ((x mod m_1e9) * (y mod m_1e9)) mod m_1e9
let split_string ?(pattern=" ") = Str.split @@ Str.regexp pattern

let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n
let a = read_line () |> split_string |> List.map int_of_string

let rec loop ans arr = function
  | [] -> Printf.printf "%d\n" @@ ans
  | x :: xs ->
      let t = Array.fold_left (fun s i -> s + if i = x then 1 else 0) 0 arr in
      let i = if arr.(0) = x then 0 else if arr.(1) = x then 1 else 2 in
      arr.(i) <- arr.(i) + 1;
      loop (ans *^ t) arr xs

let () = loop 1 (Array.make 3 0) a

Score: 500 points

Problem Statement

N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green.

The person numbered i says:

"In front of me, exactly A_i people are wearing hats with the same color as mine."

Assuming that all these statements are correct, find the number of possible combinations of colors of the N people's hats.

Since the count can be enormous, compute it modulo 1000000007.

Constraints

1 \leq N \leq 100000

0 \leq A_i \leq N-1

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print the number of possible combinations of colors of the N people's hats, modulo 1000000007.

Sample Input 1

6
0 1 2 3 4 5

Sample Output 1

3

We have three possible combinations, as follows:

Red, Red, Red, Red, Red, Red

Blue, Blue, Blue, Blue, Blue, Blue

Green, Green, Green, Green, Green, Green

Sample Input 2

3
0 0 0

Sample Output 2

6

Sample Input 3

54
0 0 1 0 1 2 1 2 3 2 3 3 4 4 5 4 6 5 7 8 5 6 6 7 7 8 8 9 9 10 10 11 9 12 10 13 14 11 11 12 12 13 13 14 14 15 15 15 16 16 16 17 17 17

Sample Output 3

115295190


let rec solve t1 t2 a1 a2 b1 b2 =
  let la, lb = a1*t1 + a2*t2, b1*t1 + b2*t2 in
  if la = lb then "infinity"
  else if la > lb then solve t1 t2 b1 b2 a1 a2
  else if a1 < b1 then "0"
  else
    let d = lb - la in
    let x = (a1-b1) * t1 in
    string_of_int @@ x / d * 2 + (x mod d + d - 1) / d
let () = Scanf.scanf "%d %d %d %d %d %d" solve |> print_endline

Score: 600 points

Problem Statement

Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east.

They start simultaneously at the same point and moves as follows towards the east:

Takahashi runs A_1 meters per minute for the first T_1 minutes, then runs at A_2 meters per minute for the subsequent T_2 minutes, and alternates between these two modes forever.

Aoki runs B_1 meters per minute for the first T_1 minutes, then runs at B_2 meters per minute for the subsequent T_2 minutes, and alternates between these two modes forever.

How many times will Takahashi and Aoki meet each other, that is, come to the same point? We do not count the start of the run. If they meet infinitely many times, report that fact.

Constraints

1 \leq T_i \leq 100000

1 \leq A_i \leq 10^{10}

1 \leq B_i \leq 10^{10}

A_1 \neq B_1

A_2 \neq B_2

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T_1 T_2
A_1 A_2
B_1 B_2

Output

Print the number of times Takahashi and Aoki will meet each other.

If they meet infinitely many times, print infinity instead.

Sample Input 1

1 2
10 10
12 4

Sample Output 1

1

They will meet just once, \frac{4}{3} minutes after they start, at \frac{40}{3} meters from where they start.

Sample Input 2

100 1
101 101
102 1

Sample Output 2

infinity

They will meet 101, 202, 303, 404, 505, 606, ... minutes after they start, that is, they will meet infinitely many times.

Sample Input 3

12000 15700
3390000000 3810000000
5550000000 2130000000

Sample Output 3

113

The values in input may not fit into a 32-bit integer type.


let sunday week =
    if week = "MON" then 6
    else if week = "TUE" then 5
    else if week = "WED" then 4
    else if week = "THU" then 3
    else if week = "FRI" then 2
    else if week = "SAT" then 1
    else 7

let ans = sunday (read_line ())

let () = print_endline @@ string_of_int ans

Score : 100 points

Problem Statement

Given is a string S representing the day of the week today.

S is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.

After how many days is the next Sunday (tomorrow or later)?

Constraints

S is SUN, MON, TUE, WED, THU, FRI, or SAT.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of days before the next Sunday.

Sample Input 1

SAT

Sample Output 1

1

It is Saturday today, and tomorrow will be Sunday.

Sample Input 2

SUN

Sample Output 2

7

It is Sunday today, and seven days later, it will be Sunday again.


(* 基本 *)
(* ocamlc str.cma main.ml でコンパイルできる *)
let () =
  let l = [("SUN",7);("MON",6);("TUE",5);("WED",4);("THU",3);("FRI",2);("SAT",1)] in
  let s = Scanf.sscanf (input_line stdin) "%s" (fun a -> a) in
  let ans = List.assoc s l in
  print_int ans;
  print_newline ()


let () = Scanf.scanf "%d\n" @@ fun n ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- (b - 1, i) :: es.(a - 1);
      es.(b - 1) <- (a - 1, i) :: es.(b - 1)
  done;
  let colours = Array.make (n - 1) 0 in
  let visited = Array.make n false in
  let rec solve s v =
    visited.(v) <- true;
    ignore
      (List.fold_left (fun colour (u, i) ->
        let rec skip colour =
          if List.mem colour s then skip (colour + 1) else colour in
        let colour = skip colour in
        if visited.(u)
        then colour
        else begin
          colours.(i) <- colour;
          solve [colour] u;
          colour + 1
        end) 1 es.(v)) in
  solve [] 0;
  Printf.printf "%d\n" (Array.fold_left max min_int colours);
  Array.iter (Printf.printf "%d\n") colours

Score : 400 points

Problem Statement

Given is a tree G with N vertices.
The vertices are numbered 1 through N, and the i-th edge connects Vertex a_i and Vertex b_i.

Consider painting the edges in G with some number of colors.
We want to paint them so that, for each vertex, the colors of the edges incident to that vertex are all different.

Among the colorings satisfying the condition above, construct one that uses the minimum number of colors.

Constraints

2 \le N \le 10^5

1 \le a_i \lt b_i \le N

All values in input are integers.

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

Print N lines.

The first line should contain K, the number of colors used.

The (i+1)-th line (1 \le i \le N-1) should contain c_i, the integer representing the color of the i-th edge, where 1 \le c_i \le K must hold.

If there are multiple colorings with the minimum number of colors that satisfy the condition, printing any of them will be accepted.

Sample Input 1

3
1 2
2 3

Sample Output 1

2
1
2

Sample Input 2

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

Sample Output 2

4
1
2
3
4
1
1
2

Sample Input 3

6
1 2
1 3
1 4
1 5
1 6

Sample Output 3

5
1
2
3
4
5


module Mi = Map.Make(struct type t = int let compare = (-) end)
let rec fix f x = f (fix f) x
let () =
  Scanf.scanf "%d %d" @@ fun n k ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" pred) in
  (1, Mi.singleton 0 0, Mi.singleton 0 1, 0) |> fix (fun f (i, sa, cm, ans) ->
    if i > n then ans else
    let si = (Mi.find (i-1) sa + a.(i-1)) mod k in
    let cm =
      if i < k then cm else
        let idx = Mi.find (i-k) sa in
        Mi.add idx (Mi.find idx cm - 1) cm in
    let ans = ans + try Mi.find si cm with _ -> 0 in
    let sa = Mi.add i si sa in
    let cm = Mi.add si (1 + try Mi.find si cm with _ -> 0) cm in
    f (i+1, sa, cm, ans))
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

Given are a sequence of N positive integers A_1, A_2, \ldots, A_N, and a positive integer K.

Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from different positions, even if they are equal sequences.

Constraints

All values in input are integers.

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

1 \leq K \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 \cdots A_N

Output

Print the number of subsequences that satisfy the condition.

Sample Input 1

5 4
1 4 2 3 5

Sample Output 1

4

Four sequences satisfy the condition: (1), (4,2), (1,4,2), and (5).

Sample Input 2

8 4
4 2 4 2 4 2 4 2

Sample Output 2

7

(4,2) is counted four times, and (2,4) is counted three times.

Sample Input 3

10 7
14 15 92 65 35 89 79 32 38 46

Sample Output 3

8


(* 横一列のn個の整数の入力を、配列に格納する *)
let i_inp_array : 'a array -> int -> unit = fun a n ->
  let rec loop i =
    if i = n then ()
    else
      (a.(i) <- (Scanf.scanf " %d" (fun x -> x));
       loop (i + 1))
  in loop 0

let floop init_v init_i condition acc body =
  let rec loop i v =
    if condition i then loop (acc i) (body i v)
    else v
  in
  loop init_i init_v

(* ocamlc str.cma main.ml でコンパイルできる *)
let () =
  let n = Scanf.sscanf (input_line stdin) "%d" (fun a -> a) in
  let a = Array.make n 0 in
  let () = i_inp_array a n in
  let b = Array.make n 0 in
  let c = Array.make n 0 in
  let sum = floop 0 0 (fun i -> i < n) (fun i -> i + 1) (fun i v -> v + a.(i)) in
  for i = 0 to (n - 1) do
    if i = 0 then (b.(i) <- a.(i); c.(i) <- a.(i) - 1)
    else
      (b.(i) <- b.(i - 1) + a.(i) ; c.(i) <- c.(i - 1) + a.(i) - 1)
  done;

  let l = floop [] 0 (fun i -> i < n) (fun i -> i + 1) (fun i v -> let tmp = (abs (b.(i) - (sum - b.(i)))) in
                                                                   if tmp <= c.(i) then tmp :: v else 1000000 :: v) in
  let ans = List.fold_right min l 100000000 in
  print_int ans;
  print_newline ()

Score: 200 points

Problem Statement

Takahashi, who works at DISCO, is standing before an iron bar.
The bar has N-1 notches, which divide the bar into N sections. The i-th section from the left has a length of A_i millimeters.

Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length.
However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:

Choose one section and expand it, increasing its length by 1 millimeter. Doing this operation once costs 1 yen (the currency of Japan).

Choose one section of length at least 2 millimeters and shrink it, decreasing its length by 1 millimeter. Doing this operation once costs 1 yen.

Find the minimum amount of money needed before cutting the bar into two parts with the same length.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 2020202020

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 A_3 ... A_N

Output

Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.

Sample Input 1

3
2 4 3

Sample Output 1

3

The initial lengths of the sections are [2, 4, 3] (in millimeters). Takahashi can cut the bar equally after doing the following operations for 3 yen:

Shrink the second section from the left. The lengths of the sections are now [2, 3, 3].

Shrink the first section from the left. The lengths of the sections are now [1, 3, 3].

Shrink the second section from the left. The lengths of the sections are now [1, 2, 3], and we can cut the bar at the second notch from the left into two parts of length 3 each.

Sample Input 2

12
100 104 102 105 103 103 101 105 104 102 104 101

Sample Output 2

0


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) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let rec proc left right acc = function
        | [_] -> acc
        | [] -> acc
        | hd :: tl ->
                let left = left + hd in
                let right = right - hd in
                let acc = min acc (max left right - min left right) in
                proc left right acc tl
    in

    let main () =
        let _ = int_of_string (read_line ()) in
        let a = split (read_line ()) in
        let s = List.fold_left (+) 0 a in
        let r = match a with
        | hd :: tl -> proc hd (s - hd) (max hd (s - hd) - min hd (s - hd)) tl
        | _ -> 0
        in
        Printf.printf "%d\n" r
    in
    main ()


let () =
    let calc1 d c =
        let restv = Array.make 10 (-1) in
        let accv  = Array.make 10 (-1) in
        let rec loop v rest acc =
            if rest = 0 then v, acc else
                if restv.(v) >= 0 then (
                    let cycle = restv.(v) - rest in
                    let acyc  = acc - accv.(v) in
                    restv.(v) <- -1;
                    accv.(v) <- -1;
                    let count = rest / cycle in
                    let rest = rest - count * cycle in
                    let acc =  acc  + count * acyc in
                    loop v rest acc
                ) else (
                    restv.(v) <- rest;
                    accv.(v) <- acc;
                    let v = v + d in
                    if v >= 10 then loop ((v / 10) + (v mod 10)) (rest - 1) (acc + 2) else
                                    loop v (rest - 1) (acc + 1)
                )
        in
        if c = 1 then d, 0 else
            let v = d * 2 in
            if v >= 10 then loop ((v / 10) + (v mod 10)) (c - 2) 2 else loop v (c - 2) 1
    in
    let calc2 dc =
        let rec loop cur acc = function
            | [] -> acc
            | (v, s) :: tl ->
                    let v = v + cur in
                    if v >= 10 then loop ((v / 10) + (v mod 10)) (acc + s + 2) tl else loop v (acc + s + 1) tl
        in
        loop 0 (-1)dc
    in
    let main () =
        let m = int_of_string (read_line ()) in
        let dc = Array.init m (fun _ -> Scanf.sscanf (read_line ()) "%d %d" calc1) in
        let r = calc2 (Array.to_list dc) in
        Printf.printf "%d\n" r
    in
    main ()

Score: 500 points

Problem Statement

N programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most 9 contestants can participate in the finals.

The preliminary stage consists of several rounds, which will take place as follows:

All the N contestants will participate in the first round.

When X contestants participate in some round, the number of contestants advancing to the next round will be decided as follows:

The organizer will choose two consecutive digits in the decimal notation of X, and replace them with the sum of these digits. The number resulted will be the number of contestants advancing to the next round.

For example, when X = 2378, the number of contestants advancing to the next round will be 578 (if 2 and 3 are chosen), 2108 (if 3 and 7 are chosen), or 2315 (if 7 and 8 are chosen).

When X = 100, the number of contestants advancing to the next round will be 10, no matter which two digits are chosen.

The preliminary stage ends when 9 or fewer contestants remain.

Ringo, the chief organizer, wants to hold as many rounds as possible.
Find the maximum possible number of rounds in the preliminary stage.

Since the number of contestants, N, can be enormous, it is given to you as two integer sequences d_1, \ldots, d_M and c_1, \ldots, c_M, which means the following: the decimal notation of N consists of c_1 + c_2 + \ldots + c_M digits, whose first c_1 digits are all d_1, the following c_2 digits are all d_2, \ldots, and the last c_M digits are all d_M.

Constraints

1 \leq M \leq 200000

0 \leq d_i \leq 9

d_1 \neq 0

d_i \neq d_{i+1}

c_i \geq 1

2 \leq c_1 + \ldots + c_M \leq 10^{15}

Input

Input is given from Standard Input in the following format:

M
d_1 c_1
d_2 c_2
:
d_M c_M

Output

Print the maximum possible number of rounds in the preliminary stage.

Sample Input 1

2
2 2
9 1

Sample Output 1

3

In this case, N = 229 contestants will participate in the first round. One possible progression of the preliminary stage is as follows:

229 contestants participate in Round 1, 49 contestants participate in Round 2, 13 contestants participate in Round 3, and 4 contestants advance to the finals.

Here, three rounds take place in the preliminary stage, which is the maximum possible number.

Sample Input 2

3
1 1
0 8
7 1

Sample Output 2

9

In this case, 1000000007 will participate in the first round.


let () =
    let calc1 d c =
        let rec loop v rest acc =
            if rest = 0 then v, acc else
                let v = v + d in
                if v >= 10 then loop ((v / 10) + (v mod 10)) (rest - 1) (acc + 2) else
                                loop v (rest - 1) (acc + 1)
        in
        if c = 1 then d, 0 else
            let v = d * 2 in
            if v >= 10 then loop ((v / 10) + (v mod 10)) (c - 2) 2 else loop v (c - 2) 1
    in
    let calc2 dc =
        let rec loop cur acc = function
            | [] -> acc
            | (v, s) :: tl ->
                    let v = v + cur in
                    if v >= 10 then loop ((v / 10) + (v mod 10)) (acc + s + 2) tl else loop v (acc + s + 1) tl
        in
        loop 0 (-1)dc
    in
    let main () =
        let m = int_of_string (read_line ()) in
        let dc = Array.init m (fun _ -> Scanf.sscanf (read_line ()) "%d %d" calc1) in
        let r = calc2 (Array.to_list dc) in
        Printf.printf "%d\n" r
    in
    main ()


Score : 100 points

Problem Statement

Given is an integer r.

How many times is the area of a circle of radius r larger than the area of a circle of radius 1?

It can be proved that the answer is always an integer under the constraints given.

Constraints

1 \leq r \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r

Output

Print the area of a circle of radius r, divided by the area of a circle of radius 1, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius 2 is 4 times larger than the area of a circle of radius 1.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000


let () =
  let rec charlist_of_string str n i =
    if i = n then [] else str.[i] :: charlist_of_string str n (i+1) in
  Scanf.scanf "%d\n%s\n" @@ fun n s ->
  let former = charlist_of_string (String.sub s 0 (n/2)) (n/2) 0 in
  let later = charlist_of_string (String.sub s (n/2) (n/2)) (n/2) 0 in
  let ans = List.fold_left2
      (fun ans x y -> if x=y then ans && true else false) true former later in
  Printf.printf "%s\n" (if ans && n mod 2 = 0 then "Yes" else "No")

Score : 200 points

Problem Statement

Given are a positive integer N and a string S of length N consisting of lowercase English letters.

Determine whether the string is a concatenation of two copies of some string.
That is, determine whether there is a string T such that S = T + T.

Constraints

1 \leq N \leq 100

S consists of lowercase English letters.

|S| = N

Input

Input is given from Standard Input in the following format:

N
S

Output

If S is a concatenation of two copies of some string, print Yes; otherwise, print No.

Sample Input 1

6
abcabc

Sample Output 1

Yes

Let T = abc, and S = T + T.

Sample Input 2

6
abcadc

Sample Output 2

No

Sample Input 3

1
z

Sample Output 3

No


open Batteries
(* 前からst文字を消す *)
let cut st str = String.init (String.length str - st) (fun a -> String.get str (a+st))
(* 後ろからed文字を消す *)
let back_cut ed str = String.init (String.length str - ed) (String.get str)
let n = read_int ()
let s = read_line ()
let l = String.length s / 2
let _ =
  (if n mod 2 = 1 then "No" else
  if cut l s = back_cut l s then "Yes" else "No") |> print_endline


let scan_int () = Scanf.scanf " %d" (fun x -> x)
let scan_string () = Scanf.scanf " %s" (fun x -> x)

let rec judge s i h =
  if i = h then true
  else if s.[i] = s.[i+h] then judge s (i+1) h
  else false

let () =
  let n = scan_int() in
  let s = scan_string() in
  if n mod 2 = 0 && judge s 0 (n/2) then Printf.printf "Yes\n"
  else Printf.printf "No\n"


let explode s =
  let rec exp i l =
    if i < 0 then l else exp (i - 1) (s.[i] :: l) in
  exp (String.length s - 1) []

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

let rec drop n l =
  match l with
    [] -> []
  | x :: xs ->
    if n = 0 then
      l
    else drop (n - 1) xs

let () =
  let n = Scanf.sscanf (input_line stdin) "%d" (fun a -> a) in
  let s = Scanf.sscanf (input_line stdin) "%s" (fun a -> a) in
  let judge cs =
    let mae = take (n/2) cs in
    let ushiro = drop (n/2) cs in
    List.for_all2 (fun a b -> a = b) mae ushiro in
  let ans = if n mod 2 = 1 then "No" else if judge (explode s) then "Yes" else "no"
  in
  print_string ans;
  print_newline ()


let () = Scanf.scanf "%d\n%s" @@ fun n s ->
  print_endline @@
  if
    Array.fold_left ( && ) (n mod 2 = 0) @@
    Array.init (n / 2) @@ fun i -> s.[i] = s.[i + n / 2]
  then "Yes"
  else "No"


let () =
    let extgcd x y =
        let rec eg r0 r1 a0 a1 b0 b1 =
            if r1 = 0 then a0 else
                let q1 = r0 / r1 in
                eg r1 (r0 mod r1) a1 (a0 - q1 * a1) b1 (b0 - q1 * b1)
        in
        eg x y 1 0 0 1
    in
    let inv x y = (* 1/x in mod y *)
        let c = extgcd x y in
        if c < 0 then c + y else c
    in
    let z = 1_000_000_000 + 7 in
    (*
    let () =
        for i = 0 to z - 1 do
            let c = inv i z in
            if c < 0 then Printf.printf "%d %d!!\n%!" i c
        done
    in
    *)
    let ( *@) a b = ((a mod z) * (b mod z)) mod z in
    let binomial a b =
        let rec loop i j acc =
            if j > b then acc else
                let acc = acc *@ i *@ inv j z in
                loop (i - 1) (j + 1) acc
        in
        loop a 1 1
    in
    let main () =
        let x, y = Scanf.sscanf (read_line ()) "%d %d" (fun x y -> x, y) in
        let ans = if (2*y - x) mod 3 <> 0 ||
           (2*x - y) mod 3 <> 0 then 0 else (
               let m = (2 * y - x) / 3 in
               let n = (2 * x - y) / 3 in
               if m < 0 || n < 0 then 0 else
                binomial (m + n) m
        )
        in
        Printf.printf "%d\n" ans
    in
    main ()

Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.


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

Score : 100 points

Problem Statement

How many ways are there to choose two distinct positive integers totaling N, disregarding the order?

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

4

Sample Output 1

1

There is only one way to choose two distinct integers totaling 4: to choose 1 and 3. (Choosing 3 and 1 is not considered different from this.)

Sample Input 2

999999

Sample Output 2

499999


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


Scanf.scanf "%s" (fun s ->
    let n = String.length s in
    let b = Array.make (n + 1) (-1) in

    (*     0 1 2 3 4 5 n = 6
     * s:  > > > < < <
     * b: 3 2 1 0 1 2 3
     *    0 1 2 3 4 5 6
     *)

    let fill start =
        let rec left i cur =
            if b.(i) < cur then (
                b.(i) <- cur;
                if i > 0 && s.[i - 1] = '>' then (
                    left (i - 1) (cur + 1)
                )
            )
        in
        let rec right i cur =
            b.(i) <- cur;
            if i < n && s.[i] ='<' then (
                right (i + 1) (cur + 1)
            ) else i
        in
        left start 0;
        right start 0
    in

    let rec loop i =
        if i = n then (if b.(i) < 0 then fill i else 0) else
            if s.[i] = '>' then loop (i + 1) else
                loop (fill i)
    in
    let _ = loop 0 in
    Array.fold_left (+) 0 b |> Printf.printf "%d\n"
)

(*
   .         .           .
 0 1 2 3 4 5 6 7 8 9 A B C D E F
 < > > > < < > < < < < < > > > <
0 3 2 1 0 1 2 0 1 2 3 4 5 2 1 0 0
0 1 2 3 4 5 6 7 8 9 A B C D E F 0
*)

Score : 300 points

Problem Statement

Given is a string S of length N-1.
Each character in S is < or >.

A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1):

If S_i= <: a_i<a_{i+1}

If S_i= >: a_i>a_{i+1}

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Constraints

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

S is a string of length N-1 consisting of < and >.

Input

Input is given from Standard Input in the following format:

S

Output

Find the minimum possible sum of the elements of a good sequence of N non-negative integers.

Sample Input 1

<>>

Sample Output 1

3

a=(0,2,1,0) is a good sequence whose sum is 3.
There is no good sequence whose sum is less than 3.

Sample Input 2

<>>><<><<<<<>>><

Sample Output 2

28


Scanf.scanf "%d" (fun n ->
    let l = Array.make n 0 in
    let r = Array.make n 0 in
    for i = 0 to n - 1 do
        Scanf.scanf " %d %d" (fun a b -> l.(i) <- a; r.(i) <- b + 1)
    done;

    let rec loop i p q =
        if i = n then p, q else
            let p = if l.(i) > l.(p) then i else p in
            let q = if r.(i) < r.(q) then i else q in
            loop (i + 1) p q
    in
    let p, q = loop 0 0 0 in

    let result1 =
        let rec loop j acc =
            if j = n then acc + max (r.(q) - l.(p)) 0 else
            if j = p || j = q then loop (j + 1) acc else
                loop (j + 1) (max acc (r.(j) - l.(j)))
        in
        loop 0 0
    in

    Printf.printf "%d\n" @@ (
        let work = Array.init n (fun i -> max (r.(i) - l.(p)) 0, max (r.(q) - l.(i)) 0) in
        Array.sort (fun (a0, b0) (a1, b1) -> compare (a0, -b0) (a1, -b1)) work;
        let s = Array.make (n + 1) (r.(q) - l.(q)) in
        let t = Array.make (n + 1) (r.(p) - l.(p)) in
        for i = 1     to     n do t.(i) <- min t.(i - 1) (snd work.(i - 1)); done;
        for i = n - 1 downto 0 do s.(i) <- min s.(i + 1) (fst work.(i    )); done;

        let rec loop i acc =
            if i = n + 1 then acc else loop (i + 1) (max acc (s.(i) + t.(i)))
        in
        loop 0 result1
    )
)

Score : 600 points

Problem Statement

10^9 contestants, numbered 1 to 10^9, will compete in a competition.
There will be two contests in this competition.

The organizer prepared N problems, numbered 1 to N, to use in these contests.
When Problem i is presented in a contest, it will be solved by all contestants from Contestant L_i to Contestant R_i (inclusive), and will not be solved by any other contestants.

The organizer will use these N problems in the two contests.
Each problem must be used in exactly one of the contests, and each contest must have at least one problem.

The joyfulness of each contest is the number of contestants who will solve all the problems in the contest.
Find the maximum possible total joyfulness of the two contests.

Constraints

2 \leq N \leq 10^5

1 \leq L_i \leq R_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 R_1
L_2 R_2
\vdots
L_N R_N

Output

Print the maximum possible total joyfulness of the two contests.

Sample Input 1

4
4 7
1 4
5 8
2 5

Sample Output 1

6

The optimal choice is:

Use Problem 1 and 3 in the first contest. Contestant 5, 6, and 7 will solve both of them, so the joyfulness of this contest is 3.

Use Problem 2 and 4 in the second contest. Contestant 2, 3, and 4 will solve both of them, so the joyfulness of this contest is 3.

The total joyfulness of these two contests is 6. We cannot make the total joyfulness greater than 6.

Sample Input 2

4
1 20
2 19
3 18
4 17

Sample Output 2

34

Sample Input 3

10
457835016 996058008
456475528 529149798
455108441 512701454
455817105 523506955
457368248 814532746
455073228 459494089
456651538 774276744
457667152 974637457
457293701 800549465
456580262 636471526

Sample Output 3

540049931


Scanf.scanf "%d" (fun n ->
    let lr = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun l r -> l, r)) in
    let lp = Array.fold_left (fun acc (l, r) -> max acc l) 0       lr in
    let rq = Array.fold_left (fun acc (l, r) -> min acc r) max_int lr in
    let ab = Array.init n (fun i ->
        let l, r = lr.(i) in
        max (r + 1 - lp) 0, - max (rq + 1 - l) 0, i)
    in
    Array.sort compare ab;
    let s = Array.make (n - 1) 0 in
    let rec loop i l r =
        if i = n - 1 then () else
            let (_, _, j) = ab.(i) in
            let ll, rr = lr.(j) in
            let l = max ll l in
            let r = min rr r in
            let () = s.(i) <- max 0 (r - l + 1) in
            loop (i + 1) l r
    in
    loop 0 0 max_int;

    let rec loop i l r =
        if i = 0 then () else
            let (_, _, j) = ab.(i) in
            let ll, rr = lr.(j) in
            let l = max ll l in
            let r = min rr r in
            let () = s.(i - 1) <- s.(i - 1) + max 0 (r - l + 1) in
            loop (i - 1) l r
    in
    loop (n - 1) 0 max_int;

    Array.fold_left max 0 s |> Printf.printf "%d\n"
)


let divisible n =
    let rec loop_i i =
        if i > 9 then false else
            if n mod i = 0 && n / i < 10 then true else loop_i (i + 1)
    in
    loop_i 1
;;
Scanf.sscanf (read_line ()) "%d" (fun n -> Printf.printf "%s\n" (if divisible n then "Yes" else "No"))

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


open Scanf ;;
open Printf ;;

let divisors n =
  let rec f i =
    if i * i > n then []
    else if n mod i = 0 then i :: f (i + 1)
    else f (i + 1)
  in
  f 1
  ;;

let min_list a = List.fold_left min max_int a ;;

let () =
  let n = scanf "%d" (fun x -> x) in
  let ans = divisors n |> List.map (fun x -> x + n / x - 2) |> min_list in
  printf "%d\n" ans
  ;;

Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


let n, i, ans = read_int (), ref 1, ref max_int
let _ = while !i * !i <= n do if n mod !i = 0 then ans := min !ans @@ !i + n / !i - 2; incr i done; Printf.printf "%d\n" @@ !ans


let pi = atan 1. *. 4.
let (a, b, x) = Scanf.sscanf (read_line ()) "%f %f %f" @@ fun a b x -> (a, b, x /. a)

let s = a *. b /. 2.

let r1 = atan (2. *. x /. (b *. b))

let r2 = atan ((2. *. (a *. b -. x) /. (a *. a)))

let angle_of_rad r = r *. 180. /. pi

let () = Printf.printf "%f\n" @@
  if s = x then angle_of_rad @@ atan (a /. b)
  else if s > x then 90. -. angle_of_rad r1
  else angle_of_rad r2

Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


let a, b, x = Scanf.scanf " %f %f %f" @@ fun a b c -> a, b, c
let f r = 180. *. r /. acos (-1.) |> Printf.printf "%.10f\n"
let _ = f @@ if x <= b *. a *. a /. 2. then let d = 2. *. x /. (a *. b) in let k = sqrt (b *. b +. d *. d) in acos @@ 2. *. x /. (a *. k) /. b
  else let s = a *. b -. x /. a in let l = 2. *. s /. a in acos @@ a /. sqrt (a *. a +. l *. l)


let () = Scanf.scanf "%d %d %d" @@ fun a b x ->
  Printf.printf "%.12f\n" @@
  if x <= a * a * b / 2
  then 90. -. 45. *. atan2 (2. *. float_of_int x) (float_of_int (a * b * b)) /. atan 1.
  else 90. -. 45. *. atan2 (float_of_int (a * a * a)) (2. *. float_of_int (a * a * b - x)) /. atan 1.


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

(* 辺の入力 *)
let input_edge edges m =
  for i = 0 to m-1 do
    let s = scan_int() and t = scan_int() in
    edges.(s-1) <- (t-1) :: edges.(s-1)
  done

(* 頂点vからの期待値の計算 *)
let calc_expected_value n edges =
  let expected = Array.make n 0.0 in
  let prop expect p u v = expect.(u) <- expect.(u) +. (expect.(v) +. 1.0) *. p in
  let rec rev_calc curr edges ret =
    if curr < 0 then ret
    else
      let p = 1.0 /. (float (List.length edges.(curr))) in
      let _ = List.iter (prop ret p curr) edges.(curr) in
      rev_calc (curr-1) edges ret in
  rev_calc (n-1) edges expected

(* 頂点vを通る確率の計算 *)
let calc_probability n edges =
  let probability = Array.make n 0.0 in
  let _ = probability.(0) <- 1.0 in
  let prop prob p u v = prob.(v) <- prob.(v) +. prob.(u) *. p in
  let rec calc curr edges ret =
    if curr = n then ret
    else
      let p = 1.0 /. (float (List.length edges.(curr))) in
      let _ = List.iter (prop ret p curr) edges.(curr) in
      calc (curr+1) edges ret in
  calc 0 edges probability

let solve n edges expected probability =
  let ans = ref expected.(0) in
  let p = expected.(0) in
  let _ =
    for u = 0 to n-1 do
      let l = List.length edges.(u) in
      if l <= 1 then ()
      else
        let add_prob = 1.0 /. (float (l-1)) -. 1.0 /. (float l) in
        let fold_func p v = p +. add_prob *. expected.(v) *. probability.(u) in
        let ref_value = List.fold_left fold_func p edges.(u) in
        let sub_prob = 1.0 /. (float (l-1)) in
        let calc_func v =
          let result = ref_value -. sub_prob *. expected.(v) *. probability.(u) in
          ans := min !ans result in
        List.iter calc_func edges.(u)
    done in
  print_float !ans

let () =
  let n = scan_int() and m = scan_int() in
  let edges = Array.make n [] in
  let _ = input_edge edges m in
  let expected = calc_expected_value n edges in
  let probability = calc_probability n edges in
  solve n edges expected probability

Score : 600 points

Problem Statement

There is a cave consisting of N rooms and M one-directional passages. The rooms are numbered 1 through N.

Takahashi is now in Room 1, and Room N has the exit. The i-th passage connects Room s_i and Room t_i (s_i < t_i) and can only be traversed in the direction from Room s_i to Room t_i. It is known that, for each room except Room N, there is at least one passage going from that room.

Takahashi will escape from the cave. Each time he reaches a room (assume that he has reached Room 1 at the beginning), he will choose a passage uniformly at random from the ones going from that room and take that passage.

Aoki, a friend of Takahashi's, can block one of the passages (or do nothing) before Takahashi leaves Room 1. However, it is not allowed to block a passage so that Takahashi is potentially unable to reach Room N.

Let E be the expected number of passages Takahashi takes before he reaches Room N. Find the value of E when Aoki makes a choice that minimizes E.

Constraints

2 \leq N \leq 600

N-1 \leq M \leq \frac{N(N-1)}{2}

s_i < t_i

If i != j, (s_i, t_i) \neq (s_j, t_j). (Added 21:23 JST)

For every v = 1, 2, ..., N-1, there exists i such that v = s_i.

Input

Input is given from Standard Input in the following format:

N M
s_1 t_1
:
s_M t_M

Output

Print the value of E when Aoki makes a choice that minimizes E.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4 6
1 4
2 3
1 3
1 2
3 4
2 4

Sample Output 1

1.5000000000

If Aoki blocks the passage from Room 1 to Room 2, Takahashi will go along the path 1 → 3 → 4 with probability \frac{1}{2} and 1 → 4 with probability \frac{1}{2}. E = 1.5 here, and this is the minimum possible value of E.

Sample Input 2

3 2
1 2
2 3

Sample Output 2

2.0000000000

Blocking any one passage makes Takahashi unable to reach Room N, so Aoki cannot block a passage.

Sample Input 3

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

Sample Output 3

3.0133333333


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

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


let a, b = Scanf.scanf "%d %d\n" @@ fun a b -> a, b
let ans = if a <= b * 2 then 0 else a - b * 2
let () = print_int ans


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) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let main () =
        let n = int_of_string (read_line ()) in
        let d = split (read_line ()) in
        let s1 = List.fold_left (+) 0 d in
        let s2 = List.fold_left (fun acc v -> acc + v * v) 0 d in
        Printf.printf "%d\n" (((s1 * s1) - s2) / 2)
    in
    main ()

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312


let () =
  Scanf.scanf "%d\n%s\n" @@ fun n s ->
  let ans, bfr = ref 1, ref s.[0] in
  String.iter (fun c -> if c <> !bfr then ans := !ans + 1; bfr := c) s;
  Printf.printf "%d\n" !ans

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


let ans, k, n = ref 0, ref 0, Scanf.scanf " %d" (+) 0
let ss, ls = Array.(make (n * (n - 1) / 2) 0, init n @@ fun _ -> Scanf.scanf " %d" (+) 0)
let g i k a = a.(i) > k
let f k a = let l, r = ref @@ -1, ref @@ Array.length a in while !r - !l > 1 do let m = !l + (!r - !l) / 2 in if g m k a then r := m else l := m done; !r
let _ = for i = 0 to n - 1 do for j = i + 1 to n - 1 do ss.(!k) <- ls.(i) + ls.(j); incr k done done;
  Array.(sort (-) ss; sort (fun x y -> y - x) ls; iteri (fun i l -> ans := !ans + max 0 ((n - i - 1) * (n - i - 2) / 2 - f l ss)) ls); Printf.printf "%d\n" !ans

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

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

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


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 rec binary_search left right array value =
  if right - left <= 1 then right
  else
    let mid = (left + right) / 2 in
    if array.(mid) < value then binary_search mid right array value
    else binary_search left mid array value

let () =
  let n = scan_int() in
  let l = scan_array n scan_int in
  let _ = Array.fast_sort compare l in
  let ans = ref 0 in
  let _ =
    for i = 0 to n-2 do
      for j = i+1 to n-1 do
        let sum = l.(i) + l.(j) in
        let k = binary_search j n l sum in
        ans := !ans + (k-j-1)
      done
    done in
  print_int !ans


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

let rec solve i n k ret =
  if i = n then ret
  else
    let a = scan_int() in
    if a < k then solve (i+1) n k ret
    else solve (i+1) n k (ret+1)

let () =
  let n = scan_int() and k = scan_int() in
  print_int (solve 0 n k 0)

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


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


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

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

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

let lst2 = List.map2 (fun i elmnt -> (i, elmnt)) (List.range 1 `To n) lst
           |> List.fast_sort (fun (ai, ae) (bi, be) -> compare ae be)
           |> List.map (fun (i, e) -> i)

let () =
        List.iter (fun elmnt -> Printf.printf "%d " elmnt) lst2;
        Printf.printf "\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


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

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

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

let lst2 = List.map2 (fun i elmnt -> (i, elmnt)) (List.range 1 `To n) lst
           |> List.fast_sort (fun (ai, ae) (bi, be) -> compare ae be)
           |> List.map (fun (i, e) -> i)

let () =
        List.iter (fun elmnt ->
                Printf.printf "%d " elmnt
        ) lst2;
        Printf.printf "\n"


let filter n =
  match n with
  | 1 ->
      true
  | 2 ->
      true
  | n ->
      if n < 2 || n mod 2 = 0 then false
      else
        let rec f i =
          if float_of_int i > sqrt (float_of_int n) then true
          else if n mod i = 0 then false
          else f (i + 2)
        in
        f 3

let common_div a b =
  let sml = min a b and lrg = max a b in
  let num = Array.init sml (fun i -> i + 1) and acc = ref [] in
  for i = 0 to sml - 1 do
    if sml mod num.(i) = 0 && lrg mod num.(i) = 0 then acc := num.(i) :: !acc
  done ;
  Array.of_list @@ List.rev !acc

let () =
  let a, b = Scanf.scanf "%d %d\n" (fun a b -> (a, b)) in
  let divs = common_div a b in
  let c = ref 0 in
  Array.iter (fun n -> if filter n = true then c := !c + 1) divs ;
  print_int !c

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


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 rec calc_bit i n ret =
  if i = n then ret
  else
    let c = scan_int() in
    calc_bit (i+1) n (ret lor (1 lsl (c-1)))

let rec input i n arr =
  if i = n then arr
  else
    let a = scan_int() and b = scan_int() in
    let c = calc_bit 0 b 0 in
    let _ = arr.(i) <- (a, c) in
    input (i+1) n arr

let rec dp table i n m arr =
  if i = m then table.((1 lsl n) - 1)
  else
    let a, c = arr.(i) in
    let rec update_dp_table j n a c =
      if j = n then ()
      else
        let _ = table.(j lor c) <- min table.(j lor c) (table.(j) + a) in
        update_dp_table (j+1) n a c in
    let _ = update_dp_table 0 (1 lsl n) a c in
    dp table (i+1) n m arr

let max_cost = int_of_float 1e15

let () =
  let n = scan_int() and m = scan_int() in
  let arr = Array.make m (0, 0) and dp_table = Array.make (1 lsl n) max_cost in
  let _ = dp_table.(0) <- 0 in
  let _ = input 0 m arr in
  let ret = dp dp_table 0 n m arr in
  if ret = max_cost then print_int (-1)
  else print_int ret

Score : 500 points

Problem Statement

We have N locked treasure boxes, numbered 1 to N.

A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.

Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.

Constraints

All values in input are integers.

1 \leq N \leq 12

1 \leq M \leq 10^3

1 \leq a_i \leq 10^5

1 \leq b_i \leq N

1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}

Output

Print the minimum cost required to unlock all the treasure boxes.
If it is impossible to unlock all of them, print -1.

Sample Input 1

2 3
10 1
1
15 1
2
30 2
1 2

Sample Output 1

25

We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.

Sample Input 2

12 1
100000 1
2

Sample Output 2

-1

We cannot unlock all the boxes.

Sample Input 3

4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3

Sample Output 3

69942


let rec drop n xs =
  if n = 0
  then xs
  else drop (n - 1) (List.tl xs)

exception Exit of int list

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let es = Array.make n [] in
  for i = 0 to m - 1 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- b - 1 :: es.(a - 1)
  done;
  let trace = Array.make n None in
  let visited = Array.make n false in
  let rec visit vs v =
    match trace.(v) with
    | Some us -> raise (Exit (drop (List.length us) (List.rev vs)))
    | None ->
        visited.(v) <- true;
        trace.(v) <- Some vs;
        List.iter (fun u -> visit (v :: vs) u) es.(v);
        trace.(v) <- None in
  try
    for v = 0 to n - 1 do
      if not visited.(v) then visit [] v
    done;
    print_endline "-1"
  with Exit vs ->
    Printf.printf "%d\n" (List.length vs);
    List.iter (fun v -> Printf.printf "%d\n" @@ v + 1) vs

Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5


let () = Scanf.scanf "%d %d %d %d" @@ fun h w a b ->
  for i = 0 to h - 1 do
    for j = 0 to w - 1 do
      print_char @@
      if (i < b) = (j < a)
      then '0'
      else '1'
    done;
    print_newline ()
  done

Score : 300 points

Problem Statement

We have a square grid with H rows and W columns.
Snuke wants to write 0 or 1 in each of the squares.
Here, all of the following conditions have to be satisfied:

For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers are equal, “the smaller” should be read as “either”.)

For every column, the smaller of the following is B: the number of 0s contained in the column, and the number of 1s contained in the column.

Determine if these conditions can be satisfied by writing 0 or 1 in each of the squares. If the answer is yes, show one way to fill the squares so that the conditions are satisfied.

Constraints

1 \leq H,W \leq 1000

0 \leq A

2 \times A \leq W

0 \leq B

2 \times B \leq H

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H W A B

Output

If the conditions cannot be satisfied by writing 0 or 1 in each of the squares, print -1.

If the conditions can be satisfied, print one way to fill the squares so that the conditions are satisfied, in the following format:

s_{11}s_{12}\cdots s_{1W}
s_{21}s_{22}\cdots s_{2W}
\vdots
s_{H1}s_{H2}\cdots s_{HW}

Here s_{ij} is the digit written in the square at the i-th row from the top and the j-th column from the left in the grid.

If multiple solutions exist, printing any of them will be accepted.

Sample Input 1

3 3 1 1

Sample Output 1

100
010
001

Every row contains two 0s and one 1, so the first condition is satisfied.
Also, every column contains two 0s and one 1, so the second condition is satisfied.

Sample Input 2

1 5 2 0

Sample Output 2

01010


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 grp = Array.make n 0 in

    let rec loop i prev cur =
        if i = n then () else
            let cur = if p.(i) > prev then cur else cur + 1 in
            let () = grp.(i) <- cur in
            loop (i + 1) p.(i) cur
    in
    loop 1 p.(0) 0;

    let par = Array.init (n - k + 2) (fun i -> i) in
    let rec root x =
        if x = par.(x) then x else
            let r = root par.(x) in
            let () = par.(x) <- r in
            r
    in
    let merge a b =
        if root a <> root b then par.(par.(b)) <- par.(a)
    in

    let e = n - k + 1 in

    let rec loop i set =
        if grp.(i) = grp.(i + k - 1) then merge i e;
        if i + k = n then () else
            let cmi = S.min_elt set in
            let cmx = S.max_elt set in
            let set = S.remove p.(i) set in
            let set = S.add p.(i + k) set in
            let nmi = S.min_elt set in
            let nmx = S.max_elt set in

            if grp.(i) <> grp.(i + k - 1) && cmi = nmi && cmx = nmx then merge i (i + 1);
            loop (i + 1) set
    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
    loop 0 init;
    let rec loop i set =
        if i + k > n then S.cardinal set else
            loop (i + 1) (S.add (root i) set)
    in
    loop 0 S.empty |> Printf.printf "%d\n"
)

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


print_endline @@ match read_line () with "Sunny" -> "Cloudy" | "Cloudy" -> "Rainy" | _ -> "Sunny"

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


let () =
  print_endline @@
  match read_line () with
  | "Sunny" -> "Cloudy"
  | "Cloudy" -> "Rainy"
  | "Rainy" -> "Sunny"


(* Vicfred
 * https://atcoder.jp/contests/abc141/tasks/abc141_b
 * implementation
 * *)
Scanf.scanf "%s\n" (fun s ->
    if
      Array.fold_left ( && ) true @@
      Array.init (String.length s) @@ fun i ->
        if i mod 2 = 0 && s.[i] = 'L' then false
        else if i mod 2 = 1 && s.[i] = 'R' then false
        else true
    then "Yes"
    else "No"
) |> Printf.printf "%s\n"

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 arr = Array.init q @@ fun _ -> Scanf.scanf "%d\n" @@ fun d -> d in
  let points = Array.make n k in
  let change n =
    Array.iteri (fun i x -> if i <> n then points.(i) <- points.(i) - 1) points in
  Array.iter (fun a -> change (a-1)) arr;
  Array.iter (fun p -> if p > 0 then print_endline "Yes" else print_endline "No") points

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


(* Vicfred
 * https://atcoder.jp/contests/abc140/tasks/abc140_a
 * math
 * *)
Scanf.scanf "%d" ( fun n ->
    n * n * n
) |> Printf.printf "%d\n"

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 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 () =
  let n = Scanf.sscanf (input_line stdin) "%d" (fun a -> a) in
  let ans = n ** 3 in
  print_int ans;
  print_newline ()


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let arr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let brr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun b -> b in
  let crr = Array.init (n-1) @@ fun _ -> Scanf.scanf "%d " @@ fun c -> c in
  let ans = ref 0 in
  let bfr = ref arr.(0) in
  for i = 0 to n - 1 do
    ans := !ans + brr.(arr.(i)-1);
    if i <> 0 && arr.(i) - !bfr = 1 then ans := !ans + crr.(!bfr-1);
    bfr := arr.(i)
  done;
  Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let blst = Array.to_list
      (Array.init (n-1) @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d) in
  let (_,ans) = List.fold_left
      (fun (bfr,ans) x -> (x,ans + (min bfr x)))
      (List.hd blst, 0) blst in
  Printf.printf "%d\n" (ans + (List.hd (List.rev blst)))

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


let () =
    let main () =
        let n, k = Scanf.sscanf (read_line ()) "%d %d" (fun n k -> n, k) in
        let s = read_line () in
        let rec loop i prev acc =
            if i = n then acc else
                if prev = s.[i] then loop (i + 1) s.[i] acc else
                        loop (i + 1) s.[i] (acc + 1)
        in
        let a = loop 1 s.[0] 0 in
        let rest_k = k - min (a / 2) k in
        let rest_a = a - 2 * (k - rest_k) in
        let rest_a = if rest_a = 1 && rest_k > 0 then rest_a - 1 else rest_a in

        let r = n - (rest_a + 1) in
        Printf.printf "%d\n" r
    in
    main ()

Score : 400 points

Problem Statement

There are N people standing in a queue from west to east.

Given is a string S of length N representing the directions of the people.
The i-th person from the west is facing west if the i-th character of S is L, and east if that character of S is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

You can perform the following operation any number of times between 0 and K (inclusive):

Operation: Choose integers l and r such that 1 \leq l \leq r \leq N, and rotate by 180 degrees the part of the queue: the l-th, (l+1)-th, ..., r-th persons. That is, for each i = 0, 1, ..., r-l, the (l + i)-th person from the west will stand the (r - i)-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

|S| = N

Each character of S is L or R.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of happy people after at most K operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose (l, r) = (2, 5), we have LLLRLL, where the 2-nd, 3-rd, and 6-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7


module M = Map.Make (struct type t = int let compare (a:int) (b:int) = compare a b end)

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) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let m = 1 lsl 20 in
    let main () =
        let n = int_of_string (read_line ()) in
        let p = Array.of_list (split (read_line ())) in
        let rec loop i map acc =
            if i = n then acc else
                let next = M.fold (fun org v next ->
                    let first = org / m in
                    let second = org mod m in
                    let key = if p.(i) > first then p.(i) * m + first else
                        if p.(i) > second then first * m + p.(i) else org
                    in
                    M.add key (v + try M.find key next with _ -> 0) next) map M.empty
                in
                let acc = acc + M.fold (fun org v acc -> (org mod m) * v + acc) next 0 in
                loop (i + 1) (M.add (p.(i) * m) 1 next) acc
        in
        let r = loop 1 (M.singleton (p.(0) * m) 1) 0 in
        Printf.printf "%d\n" r
    in
    main ()

Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136


(* unihernandez22
 * https://atcoder.jp/contests/abc139/tasks/abc139_a
 * implementation
 * *)

let rec count_eq s t i c =
    if i == String.length s then c
    else if s.[i] == t.[i] then count_eq s t (i+1) (c+1)
    else count_eq s t (i+1) c;;

Printf.printf "%d\n" @@
Scanf.scanf "%s\n%s\n" @@ fun s t ->
    count_eq s t 0 0;;

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


open Batteries
let s = String.explode (read_line ())
let t = String.explode (read_line ())
let ans = List.fold_left2 (fun a b c -> if b = c then a + 1 else a) 0 s t
let () = print_int ans


let () = Scanf.scanf "%s\n%s" @@ fun s t ->
  Printf.printf "%d\n" @@
  Array.fold_left ( + ) 0 @@
  Array.init 3 @@ fun i -> if s.[i] = t.[i] then 1 else 0


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

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 () =
    let main () =
        let a, b = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> a, b) in
        Printf.printf "%d\n" (((b - 1) + a - 2) / (a - 1))
    in
    main ()


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 () =
  let n = scan_int() in
  let h = scan_array n scan_int in
  let ans =
    let rec loop i curr ret =
      if i = n then ret
      else
        if h.(i-1) >= h.(i) then loop (i+1) (curr+1) (max ret (curr+1))
        else loop (i+1) 0 ret in
    loop 1 0 0 in
  print_int ans

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right.

The height of the i-th square from the left is H_i.

You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.

Find the maximum number of times you can move.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the maximum number of times you can move.

Sample Input 1

5
10 4 8 7 3

Sample Output 1

2

By landing on the third square from the left, you can move to the right twice.

Sample Input 2

7
4 4 5 6 6 5 5

Sample Output 2

3

By landing on the fourth square from the left, you can move to the right three times.

Sample Input 3

4
1 2 3 4

Sample Output 3

0


open Printf
open Scanf

let read_intlist: unit -> int list = fun () ->
  let sl = Str.split (Str.regexp " ") @@ read_line () in
  List.map (fun s -> sscanf s "%d" (fun x -> x)) sl

let n = sscanf (read_line ()) "%d" (fun x -> x)
let a: int array array = Array.make (n+1) [|0|]
let () = for y = 1 to n do
           a.(y) <- 0 :: (read_intlist ()) @ [0] |> Array.of_list
         done

(*  *)
let ans = ref 0
let inds = Array.make (n+1) 1

let () =
  let bflag = ref true in
  while !bflag do
    let dp = Array.make (n+1) false in
    let flag = ref true in

    for i = 1 to n do
      let x = inds.(i) in
      if not dp.(i) && x < n then begin
          let target = a.(i).(x) in
          let targeti = inds.(target) in
          if not dp.(target) && targeti < n && a.(target).(targeti) = i then begin
              dp.(i) <- true;
              dp.(target) <- true;

              inds.(i) <- inds.(i) + 1;
              inds.(target) <- inds.(target) + 1;

              if !flag then
                flag := false
            end
        end;
    done;

    if !flag then
      let hoge = List.tl (Array.to_list inds)
                 |> List.for_all (fun e -> e = n) in
      if hoge then
        bflag := false
      else begin
          ans := -1;
          bflag := false
        end
    else
      incr ans
  done

let () = print_endline @@ string_of_int !ans

Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


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 rec loop i s cx cy acc =
        if i = n then (
            if s = n then float acc |> sqrt else
                let (x, y) = xy.(s) in
                let bx = cx - x in
                let by = cy - y in
                let b = bx * bx + by * by in
                loop i (s + 1) bx by (max b acc)
        ) else
            let c = cx * cx + cy * cy in
            let (x, y) = xy.(i) in
            let bx = cx + x in
            let by = cy + y in
            let b = bx * bx + by * by in
            if b >= c then loop (i + 1) s bx by (max b acc) else
                let (x, y) = xy.(s) in
                let bx = cx - x in
                let by = cy - y in
                let b = bx * bx + by * by in
                loop i (s + 1) bx by (max b acc)
    in
    loop 0 0 0 0 0 |> Printf.printf "%.10f\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