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

Score : 200 points

Problem Statement

It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.

There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses.

Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.

Constraints

1 ≤ N ≤ 100

0 ≤ a_i ≤ 1000

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum distance to be traveled.

Sample Input 1

4
2 3 7 9

Sample Output 1

7

The travel distance of 7 can be achieved by starting at coordinate 9 and traveling straight to coordinate 2.

It is not possible to do with a travel distance of less than 7, and thus 7 is the minimum distance to be traveled.

Sample Input 2

8
3 1 4 1 5 9 2 6

Sample Output 2

8

There may be more than one house at a position.


let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let () = Array.fast_sort compare a in
  let rec f i sum =
    if i = n then sum else f (i + 1) (sum + a.(i) - a.(i - 1))
  in f 1 0
     |> Printf.printf "%d\n"

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

Submitted source-code file size, in bytes.

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

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


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let cs = Array.make 9 0
let f i = cs.(i) <- cs.(i) + 1
let mi = Array.(iter (fun a -> f @@ min 8 @@ a / 400) a_s; fold_left (fun s c -> s + if c > 0 then 1 else 0) 0 cs - min 1 cs.(8))
let _ = Printf.printf "%d %d\n" (max 1 mi) @@ if mi = 0 then max 1 @@ cs.(8) - 1 else mi + max 0 cs.(8)

Score : 300 points

Problem Statement

In AtCoder, a person who has participated in a contest receives a color, which corresponds to the person's rating as follows:

Rating 1-399 : gray

Rating 400-799 : brown

Rating 800-1199 : green

Rating 1200-1599 : cyan

Rating 1600-1999 : blue

Rating 2000-2399 : yellow

Rating 2400-2799 : orange

Rating 2800-3199 : red

Other than the above, a person whose rating is 3200 or higher can freely pick his/her color, which can be one of the eight colors above or not.

Currently, there are N users who have participated in a contest in AtCoder, and the i-th user has a rating of a_i.

Find the minimum and maximum possible numbers of different colors of the users.

Constraints

1 ≤ N ≤ 100

1 ≤ a_i ≤ 4800

a_i is an integer.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum possible number of different colors of the users, and the maximum possible number of different colors, with a space in between.

Sample Input 1

4
2100 2500 2700 2700

Sample Output 1

2 2

The user with rating 2100 is "yellow", and the others are "orange". There are two different colors.

Sample Input 2

5
1100 1900 2800 3200 3200

Sample Output 2

3 5

The user with rating 1100 is "green", the user with rating 1900 is blue and the user with rating 2800 is "red".

If the fourth user picks "red", and the fifth user picks "blue", there are three different colors. This is one possible scenario for the minimum number of colors.

If the fourth user picks "purple", and the fifth user picks "black", there are five different colors. This is one possible scenario for the maximum number of colors.

Sample Input 3

20
800 810 820 830 840 850 860 870 880 890 900 910 920 930 940 950 960 970 980 990

Sample Output 3

1 1

All the users are "green", and thus there is one color.


open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
end open MyInt64

let f v =
	[v<400L;v<800L;v<1200L;v<1600L;v<2000L;v<2400L;v<2800L;v<3200L;v>=3200L]
	|> List.rev
	|> List.mapi (fun i v -> i,v)
	|> List.fold_left (fun u (i,v) -> if v then 8-$i else u) 0
	|> Int64.of_int
let (<+) a (i,v) = a<@(i,(a@i)+v)
let () =
	let n = get_i64 0 in
	let a = input_i64_array n in
	let count = Array.make 9 0L in
	Array.iter (fun v ->
		count<+(f v,1L);
	) a;
	let p,q = repm 0L 8L 0L (fun u i ->
		let v = count@i in `Ok (u + if i<>8L && v>0L then 1L else 0L)
	), count@8L
	in
	(* a person whose rating is 3200 or higher can freely pick his/her color,
	****which can be one of the eight colors above or not****. *)
	printf "%Ld %Ld\n" (max p 1L) (*min 8L *)(p+q)(**)


let n = Scanf.scanf "%d" (fun x -> x)
let xs = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x / 400)) |> Array.to_list
let () =
  let colors = xs |> List.filter ((>) 8) |> List.sort_uniq (-) |> List.length in
  let num_reds = xs |> List.filter ((<=) 8) |> List.length in
  let min_colors, max_colors = max 1 colors, min 7 (colors + num_reds) in
  Printf.printf "%d %d\n" min_colors max_colors


let () = Scanf.scanf "%d\n%s\n" @@ fun n s ->
  Array.init n (String.get s)
  |> Array.fold_left (fun (minimum, h) -> function
    | '(' -> (minimum, h + 1)
    | ')' -> (min minimum (h - 1), h - 1)) (0, 0)
  |> (fun (minimum, h) ->
      let d = max 0 (~- minimum) in
      Printf.printf "%s%s%s\n" (String.make d '(') s (String.make (max 0 (d + h)) ')'))

Score : 400 points

Problem Statement

You are given a string S of length N consisting of ( and ). Your task is to insert some number of ( and ) into S to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

If X is a correct bracket sequence, the concatenation of (, X and ) in this order is also a correct bracket sequence.

If X and Y are correct bracket sequences, the concatenation of X and Y in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

The length of S is N.

1 ≤ N ≤ 100

S consists of ( and ).

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into S.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))


let id x = x
let n = Scanf.scanf "%d\n" id
let string = Scanf.scanf "%s\n" id

let rec makestr str n =
  if n = String.length str - 1 then str else
    if str = "()" then "" else
      if str.[n] = '(' && str.[n+1] = ')' then
        makestr ((String.sub str 0 n) ^ (String.sub str (n+2) ((String.length str) - (n+2)))) 0 else makestr str (n+1)

let str = makestr string 0

let rec count x y str n =
  if n = String.length str then (x,y) else
  match str.[n] with
  | '(' -> count (x+1) y str (n+1)
  | ')' -> count x (y+1) str (n+1)

let (x,y) = count 0 0 str 0

let xlist = String.make x ')'
let ylist = String.make y '('

let () =
  Printf.printf "%s\n" (ylist ^ string ^ xlist)


let _ = Scanf.sscanf (read_line ()) "%d %d" (fun a b ->
  match a with
  | a when a + b >= 10 -> print_endline "error"
  | _ -> Printf.printf "%d\n" (a + b)
)

Score : 100 points

Problem Statement

You are given two integers A and B as the input. Output the value of A + B.

However, if A + B is 10 or greater, output error instead.

Constraints

A and B are integers.

1 ≤ A, B ≤ 9

Input

Input is given from Standard Input in the following format:

A B

Output

If A + B is 10 or greater, print the string error (case-sensitive); otherwise, print the value of A + B.

Sample Input 1

6 3

Sample Output 1

9

Sample Input 2

6 4

Sample Output 2

error


open Printf
open Scanf

let () =
  let solve a b =
    let x = a + b in
    if x >= 10 then "error" else x |> string_of_int in
  scanf "%d %d\n" solve |> printf "%s\n"


let n = read_int ()

let ss =
  let rec read i ls =
    if i = n then ls else read (i + 1) (read_int () :: ls)
  in
  read 0 []

let rec find_min tmp = function
  | [] -> tmp
  | h :: tl ->
    if h mod 10 = 0 then find_min tmp tl else find_min (min tmp h) tl

let () =
  let sum = List.fold_left ( + ) 0 ss in
  ( if sum mod 10 <> 0 then sum
    else
      let new_sum = sum - find_min max_int ss in
      if new_sum mod 10 <> 0 then new_sum else 0 )
  |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are taking a computer-based examination. The examination consists of N questions, and the score allocated to the i-th question is s_i. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of 10, the system displays 0 as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

1 ≤ N ≤ 100

1 ≤ s_i ≤ 100

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be 25 if the 10-point and 15-point questions are answered correctly and the 5-point question is not, and this grade will be displayed correctly. Your grade will become 30 if the 5-point question is also answered correctly, but this grade will be incorrectly displayed as 0.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be 35 if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of 10 and displayed as 0.


let id x = x
let n = Scanf.scanf "%d\n" id

let array = Array.init n (fun _ -> Scanf.scanf "%d\n" id)
let l = Array.length array
let list' = Array.to_list array
let list = List.sort compare list'

let rec pl i =
  if i = l then 0 else
    (List.nth list i) + pl (i+1)

let max = pl 0

let rec func i =
  if i = l then 0 else
    if ((List.nth list i) mod 10) <> 0 then max - (List.nth list i) else
      func (i+1)

let ans = if max mod 10 <> 0 then max else func 0

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


let group1 = [1;3;5;7;8;10;12]
let group2 = [4;6;9;11]
let group3 = [2]

let _ = Scanf.sscanf (read_line()) "%d %d" (fun x y ->
  if x = y then "Yes" else
  if List.exists (fun a -> a = x) group1 && List.exists (fun a -> a = y) group1 then "Yes" else
  if List.exists (fun a -> a = x) group2 && List.exists (fun a -> a = y) group2 then "Yes" else
  if List.exists (fun a -> a = x) group3 && List.exists (fun a -> a = y) group3 then "Yes" else "No"
) |> print_endline

Score : 100 points

Problem Statement

Based on some criterion, Snuke divided the integers from 1 through 12 into three groups as shown in the figure below.
Given two integers x and y (1 ≤ x < y ≤ 12), determine whether they belong to the same group.

Constraints

x and y are integers.

1 ≤ x < y ≤ 12

Input

Input is given from Standard Input in the following format:

x y

Output

If x and y belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No


let h, w = Scanf.scanf " %d %d" @@ fun a b -> a, b
let a_ss = Array.init h @@ fun _ -> Scanf.scanf " %s" @@ fun s -> s
let s = String.make (w + 2) '#'
let _ =
  print_endline s;
  for i = 0 to h - 1 do print_char '#'; print_string a_ss.(i); print_endline "#" done;
  print_endline s

Score : 200 points

Problem Statement

You are given a image with a height of H pixels and a width of W pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the i-th row from the top and j-th column from the left is a_{ij}.

Put a box around this image and output the result. The box should consist of # and have a thickness of 1.

Constraints

1 ≤ H, W ≤ 100

a_{ij} is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

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

Output

Print the image surrounded by a box that consists of # and has a thickness of 1.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###


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

let repeat f n=
    let rec loop acc =function
        | 0->List.rev acc
        | n -> loop (f ():: acc)(n -1) in
    loop [] n

let list' = repeat (fun () -> Scanf.scanf "%s\n" id) (h+1)

let list = List.tl list'

let rec makeshstr w str =
               if w = 0 then str else makeshstr (w-1) ("#" ^ str)

let shstr = makeshstr w "##"

let () =
  let rec pri list =
    match list with
    | [] -> Printf.printf "%s\n" shstr
    | ans :: rest -> (Printf.printf "#%s#\n" ans) ; pri rest
  in Printf.printf "%s\n" shstr; pri list


module DirectedGraph
  (* 道の表現 *)
  (Path : sig
    type t
    (* 辺の名前 *)
    type edge
    (* 長さ0の道 *)
    val nil : t
    (* 道の後ろに辺を付け足した道 *)
    val snoc : t -> edge -> t
  end) :
sig
  (* BFSにより，重みのないグラフの最短経路を求める *)
  val bfs :
    (* 頂点数（Hashtblを用いるので目安程度） *)
    int ->
    (* 辺の名前が付いた隣接リスト *)
    ('v -> ('v * Path.edge) list) ->
    (* 始点 *)
    'v ->
    (* 最短経路を返す関数 辿り着けなければNoneを返す） *)
    ('v -> Path.t option)
end = struct
  let rec bfs_aux es d frontier t =
    try Some (Hashtbl.find d t) with
    | Not_found ->
        match !frontier with
        | [] -> None
        | _ :: _ ->
            frontier := List.fold_right (fun u ->
              List.fold_right (fun (v, e) frontier ->
                if Hashtbl.mem d v
                then frontier
                else (Hashtbl.add d v (Path.snoc (Hashtbl.find d u) e); v :: frontier))
              (es u)) !frontier [];
            bfs_aux es d frontier t

  (*
   * 終点に辿り着いた時点で探索を切り上げるが，
   * 戻り値の関数を覚えておくと，途中まで探索した結果が再利用される
   * （#trace bfs_aux すると分かりやすい）
   *)
  let bfs n es s =
    let d = Hashtbl.create n in
    Hashtbl.add d s Path.nil;
    let frontier = ref [s] in
    bfs_aux es d frontier
end

module FlowNetwork
  (* 流量 *)
  (Flow : sig
    type t
    val inf : t
    val zero : t
    val ( + ) : t -> t -> t
    val ( - ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  val max_flow :
    (* 頂点の数（Hashtblを用いるので目安程度） *)
    int ->
    (* 各辺とその逆辺の容量 *)
    ('v * 'v * Flow.t * Flow.t) list ->
    (* 始点 *)
    'v ->
    (* 終点 *)
    'v ->
    (* 最大フロー *)
    Flow.t
end =
struct
  module G = DirectedGraph (struct
    type t = int
    type edge = unit
    let nil = 0
    let snoc t _ = t + 1
  end)

  (* 増加パスをDFSで探し，流せるだけ流していく *)
  let rec dfs capacity add_edge iter level v t f =
    if v = t then f
    else begin
      let rec find () =
        match Hashtbl.find iter v with
        | exception Not_found -> Flow.zero
        | (u, i) ->
            Hashtbl.remove iter v;
            (* capacity i <= 0 *)
            if Flow.compare (capacity i) Flow.zero <= 0 || level u <= level v then find ()
            else begin
              let d = dfs capacity add_edge iter level u t @@
                (* min f (capacity i) *)
                if Flow.compare f (capacity i) <= 0 then f else capacity i in
              (* d <= 0 *)
              if Flow.compare d Flow.zero <= 0 then find ()
              else (add_edge i d; d)
            end in find ()
    end

  let max_flow n es s t =
    assert (s <> t);
    (* 各辺に流せる流量 *)
    let capacity = Array.make (2 * List.length es) Flow.zero in
    (* 逆辺を張りつつ，隣接リスト形式に変換 *)
    let adj = Hashtbl.create n in
    List.iteri (fun i (u, v, c, c') ->
      (* 各辺は番号で管理する *)
      Hashtbl.add adj u (v, 2 * i);
      (* 容量はcapacityを見てほしい *)
      capacity.(2 * i) <- c;
      (* 逆辺 *)
      Hashtbl.add adj v (u, 2 * i + 1);
      capacity.(2 * i + 1) <- c') es;
    (* 番号iの辺にcだけフローを流す *)
    let add_edge i c =
      let open Flow in
      capacity.(i) <- capacity.(i) - c;
      (* 逆辺 *)
      capacity.(i lxor 1) <- capacity.(i lxor 1) + c in
    let rec outer flow =
      let level = G.bfs n (fun v ->
        List.concat @@ List.map (fun (u, i) ->
          if Flow.compare capacity.(i) Flow.zero <= 0 then []
          else [(u, ())]) @@ Hashtbl.find_all adj v) s in
      if level t = None then flow
      else
        let iter = Hashtbl.copy adj in
        let rec inner flow =
          let f = dfs (fun i -> capacity.(i)) add_edge iter level s t Flow.inf in
          if Flow.compare f Flow.zero <= 0 then flow
          else inner (Flow.( + ) flow f) in
        outer @@ inner flow in
    outer Flow.zero
end

module G = FlowNetwork (struct
  include Pervasives
  type t = int
  let zero = 0
  let inf = max_int
end)

let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ass = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let yxs =
    List.concat @@ Array.to_list @@ Array.init h @@ fun y ->
      Array.to_list @@ Array.init w @@ fun x -> y, x in
  let [(sy, sx); (ty, tx)] =
    List.map (fun c ->
      List.find (fun (y, x) -> ass.(y).[x] = c) yxs) ['S'; 'T'] in
  Printf.printf "%d\n" @@
  if sy = ty || sx = tx then -1
  else G.max_flow (2 + h + w)
    (List.concat @@ List.map (fun (y, x) ->
      match ass.(y).[x] with
      | '.' -> []
      | 'S' -> [(`Source, `Col x, max_int, 0); (`Source, `Row y, max_int, 0)]
      | 'T' -> [(`Sink, `Col x, 0, max_int); (`Sink, `Row y, 0, max_int)]
      | 'o' -> [(`Col x, `Row y, 1, 1)]) yxs) `Source `Sink

Score : 800 points

Problem Statement

There is a pond with a rectangular shape.
The pond is divided into a grid with H rows and W columns of squares.
We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).

Some of the squares in the pond contains a lotus leaf floating on the water.
On one of those leaves, S, there is a frog trying to get to another leaf T.
The state of square (i,\ j) is given to you by a character a_{ij}, as follows:

. : A square without a leaf.

o : A square with a leaf floating on the water.

S : A square with the leaf S.

T : A square with the leaf T.

The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."

Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T.
Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.

Constraints

2 ≤ H, W ≤ 100

a_{ij} is ., o, S or T.

There is exactly one S among a_{ij}.

There is exactly one T among a_{ij}.

Input

Input is given from Standard Input in the following format:

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

Output

If the objective is achievable, print the minimum necessary number of leaves to remove.
Otherwise, print -1 instead.

Sample Input 1

3 3
S.o
.o.
o.T

Sample Output 1

2

Remove the upper-right and lower-left leaves.

Sample Input 2

3 4
S...
.oo.
...T

Sample Output 2

0

Sample Input 3

4 3
.S.
.o.
.o.
.T.

Sample Output 3

-1

Sample Input 4

10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo

Sample Output 4

5


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

Score : 100 points

Problem Statement

You are given three integers A, B and C.
Determine whether C is not less than A and not greater than B.

Constraints

-100≤A,B,C≤100

A, B and C are all integers.

Input

Input is given from Standard Input in the following format:

A B C

Output

If the condition is satisfied, print Yes; otherwise, print No.

Sample Input 1

1 3 2

Sample Output 1

Yes

C=2 is not less than A=1 and not greater than B=3, and thus the output should be Yes.

Sample Input 2

6 5 4

Sample Output 2

No

C=4 is less than A=6, and thus the output should be No.

Sample Input 3

2 2 2

Sample Output 3

Yes


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


open Batteries
module Mymap = Map.Make(Int)
let () =
  let n = Scanf.scanf "%d " (fun a -> a) in
  let m = Scanf.scanf "%d " (fun a -> a) in
  let pair_lst = Array.to_list @@ Array.init m (fun _ -> Scanf.scanf "%d %d " (fun a b -> a,b)) in

  let amap = List.fold_left (fun accum (x,y) ->
      Mymap.modify_opt x (fun v_opt -> match v_opt with
            Some v -> Some (v + 1)
          | None -> Some 1
        ) accum |>
      Mymap.modify_opt y (fun v_opt -> match v_opt with
            Some v -> Some (v + 1)
          | None -> Some 1
        )
    ) (Mymap.empty) pair_lst
  in

  let pair_lst = Mymap.bindings amap in
  let pair_lst = List.sort compare pair_lst in
  List.iter (fun (x,y) -> Printf.printf "%d\n" y) pair_lst

Score : 200 points

Problem Statement

There are N cities and M roads.
The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

2≤N,M≤50

1≤a_i,b_i≤N

a_i ≠ b_i

All input values are integers.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print the answer in N lines.
In the i-th line (1≤i≤N), print the number of roads connected to city i.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City 1 is connected to the 1-st and 3-rd roads.

City 2 is connected to the 1-st and 2-nd roads.

City 3 is connected to the 2-nd road.

City 4 is connected to the 3-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
    let a =
        Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun a b -> (a, b) in
    Array.sort (fun (x, _) (y, _) -> x - y) a;
    let rec f acc i =
        if (snd a.(i)) + acc >= k then fst a.(i) else f ((snd a.(i)) + acc) (i+1)
    in f 0 0 |> Printf.printf "%d"

Score : 300 points

Problem Statement

There is an empty array.
The following N operations will be performed to insert integers into the array.
In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array.
Find the K-th smallest integer in the array after the N operations.
For example, the 4-th smallest integer in the array \{1,2,2,3,3,3\} is 3.

Constraints

1≤N≤10^5

1≤a_i,b_i≤10^5

1≤K≤b_1…+…b_n

All input values are integers.

Input

Input is given from Standard Input in the following format:

N K
a_1 b_1
:
a_N b_N

Output

Print the K-th smallest integer in the array after the N operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t
    val zero : t
    val neg_inf : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    d.(s) <- Weight.zero;
    for i = 1 to n - 1 do
      es.fold (fun (u, v, c) () ->
        let open Weight in
        (* c は u から v への辺の重さ *)
        (* d.(u) + c < d.(v) *)
        if 0 < Weight.compare d.(v) (d.(u) + c) then
          d.(v) <- d.(u) + c) ()
    done;
    (* 手動ループアンローリング *)
    for i = n to 2 * n do
      es.fold (fun (u, v, c) () ->
        let open Weight in
        if 0 < Weight.compare d.(v) (d.(u) + c) then
          (* n 回目以降に変更が起こった場合，v までの経路に負閉路が含まれている *)
          (d.(v) <- d.(u) + c; neg.(v) <- true)) ()
    done;
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let inf = -123456789012345678
  let zero = 0
  let neg_inf = 123456789012345678
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let abcs = Array.init m @@ fun _ -> Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abcs } 0 (n - 1) in
  if 123456789012345678 <= d
  then print_endline "inf"
  else Printf.printf "%d\n" d

Score : 400 points

Problem Statement

There is a directed graph with N vertices and M edges.
The i-th edge (1≤i≤M) points from vertex a_i to vertex b_i, and has a weight c_i.
We will play the following single-player game using this graph and a piece.

Initially, the piece is placed at vertex 1, and the score of the player is set to 0.
The player can move the piece as follows:

When the piece is placed at vertex a_i, move the piece along the i-th edge to vertex b_i. After this move, the score of the player is increased by c_i.

The player can end the game only when the piece is placed at vertex N.
The given graph guarantees that it is possible to traverse from vertex 1 to vertex N.

When the player acts optimally to maximize the score at the end of the game, what will the score be?
If it is possible to increase the score indefinitely, print inf.

Constraints

2≤N≤1000

1≤M≤min(N(N-1),2000)

1≤a_i,b_i≤N (1≤i≤M)

a_i≠b_i (1≤i≤M)

a_i≠a_j or b_i≠b_j (1≤i<j≤M)

-10^9≤c_i≤10^9 (1≤i≤M)

c_i is an integer.

In the given graph, there exists a path from vertex 1 to vertex N.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible score at the end of the game, if it is finite. If it is possible to increase the score indefinitely, print inf.

Sample Input 1

3 3
1 2 4
2 3 3
1 3 5

Sample Output 1

7

There are two ways to move the piece to vertex N=3:

vertex 1 → vertex 2 → vertex 3 : score 4+3=7

vertex 1 → vertex 3 : score 5

Thus, the maximum possible score at the end of the game is 7.

Sample Input 2

2 2
1 2 1
2 1 1

Sample Output 2

inf

It is possible to increase the score indefinitely by alternating between vertex 1 and 2.

Sample Input 3

6 5
1 2 -1000000000
2 3 -1000000000
3 4 -1000000000
4 5 -1000000000
5 6 -1000000000

Sample Output 3

-5000000000


let rec fold_n n f v = if n <= 0 then v else fold_n (n-1) f (f v)
let inf = 10101010101010

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

  let reach = begin
    let g = Array.init n (fun _ -> []) in
    a |> Array.iter (fun (u,v,_) -> g.(v) <- u :: g.(v));
    let vis = Array.make n false in
    let rec f u =
      vis.(u) <- true;
      List.iter (fun v -> if not vis.(v) then f v) g.(u)
    in f (n-1);
    vis
  end in

  let sc = Array.make n (-inf) in sc.(0) <- 0;
  let mem = Array.make n false in
  let has_loop = true |> fold_n n (fun upd ->
    if not upd then false else begin
      Array.fill mem 0 n false;
      Array.fold_left (fun b (u,v,c) ->
        let b' = sc.(u) + c > sc.(v) in
        if b' then (mem.(v) <- true; sc.(v) <- sc.(u) + c);
        b || b'
        ) false a
    end)
  in
  let inf_loop = has_loop && begin
    Array.init n (fun i -> reach.(i) && mem.(i)) |> Array.fold_left (||) false
  end in

  if inf_loop then
    print_endline "inf"
  else
    Printf.printf "%d\n" sc.(n-1)


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

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

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

module WeightedDirectedGraph
  (Vertex : sig
    type t
    val compare : t -> t -> int
  end)
  (Weight : sig
    type t
    val zero : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  (* 配列版の実装 *)
  val raw_bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト *)
    (* 頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) list ->
    (* 始点 *)
    int ->
    (int -> [ `Weight of Weight.t | `Inf | `NegInf ])

  (* 座標圧縮により様々な型を使えるようにしたバージョン *)
  val bellman_ford :
    (* 辺のリスト *)
    (Vertex.t * Vertex.t * Weight.t) list ->
    (* 始点 *)
    Vertex.t ->
    (Vertex.t -> [ `Weight of Weight.t | `Inf | `NegInf ])
end =
struct
  module CC = CoordComp (Vertex)
  module Weight' = WithInf (Weight)

  let raw_bellman_ford n es s =
    (* 距離を覚えるやつ *)
    (* Noneで無限を表す *)
    let d = Array.make n None in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    d.(s) <- Some Weight.zero;
    for i = 0 to 2 * n - 1 do
      List.iter (fun (u, v, c) ->
        let open Weight' in
        (* c は u から v への辺の重さ *)
        (* d.(u) + c < d.(v) *)
        if 0 < compare d.(v) (d.(u) + Some c) then begin
          d.(v) <- d.(u) + Some c;
          if n - 1 <= i then
            (* n 回目以降に変更が起こった場合，v までの経路に負閉路が含まれている *)
            neg.(v) <- true
        end) es
    done;
    fun v ->
      if neg.(v) then `NegInf
      else
        match d.(v) with
        | None -> `Inf
        | Some d -> `Weight d

  let bellman_ford es s =
    let (n, comp, _) =
      CC.compress @@
        List.concat @@
          List.map (fun (u, v, _) -> [u; v]) es in
    match
      raw_bellman_ford n
        (List.map (fun (u, v, c) -> (comp u, comp v, c)) es) (comp s)
    with
    | exception Not_found -> (* 頂点から延びる辺がない *)
        fun _ -> `Inf
    | d ->
        fun v -> try d (comp v) with Not_found -> `Inf
end

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

module G = WeightedDirectedGraph (Int) (Int)

let () = Scanf.scanf "%d %d\n" (fun n m ->
  let abcs = Array.init m (fun _ -> Scanf.scanf "%d %d %d\n" (fun a b c -> a - 1, b - 1, c)) in
  match G.bellman_ford (Array.to_list abcs) 0 (n - 1) with
  | `NegInf -> print_endline "inf"
  | `Weight c -> Printf.printf "%d\n" c)


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

let i = ref 0

let rec f a b c =
        if a mod 2 = 1 && b mod 2 = 1 && c mod 2 = 1 then
                0
        else if a = b && a = c && b = c then
                -1
        else if a mod 2 = 1 || b mod 2 = 1 || c mod 2 = 1 then
                !i
        else
                let na = (b + c) / 2 in
                let nb = (a + c) / 2 in
                let nc = (a + b) / 2 in
                        incr i;
                        f na nb nc

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

Score : 300 points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

1 ≤ A,B,C ≤ 10^9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.

After the second action, they have 10, 12 and 14.

After the third action, they have 13, 12 and 11.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1


let a, b, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let f a b c = a mod 2 = 1 || b mod 2 = 1 || c mod 2 = 1
let rec g n a b c = if f a b c then n else g (n + 1) (b / 2 + c / 2) (c / 2 + a / 2) (a / 2 + b / 2)
let _ = Printf.printf "%d\n" @@ if not @@ f a b c && a = b && b = c then -1 else g 0 a b c


let (n, m) = Scanf.sscanf (read_line ()) "%d %d" @@ fun n m -> (n, m)
let ab = Array.init m @@ fun _ -> Scanf.sscanf (read_line ()) "%d %d" @@ fun a b -> (a, b)

let cnt = Array.make 100_001 0

let () =
  Array.iter (fun (a, b) ->
    cnt.(a) <- cnt.(a) + 1;
    cnt.(b) <- cnt.(b) + 1
  ) ab;
  print_endline @@ if Array.for_all (fun cnt -> cnt mod 2 = 0) cnt then "YES" else "NO"

Score : 500 points

Problem Statement

Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.

First, Takahashi created a tree with N vertices numbered 1 through N, and wrote 0 at each edge.

Then, Aoki gave him M queries. The i-th of them is as follows:

Increment the number written at each edge along the path connecting vertices a_i and b_i, by one.

After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number.
However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries.

Determine whether there exists a tree that has the property mentioned by Takahashi.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

1 ≤ a_i,b_i ≤ N

a_i ≠ b_i

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_M b_M

Output

Print YES if there exists a tree that has the property mentioned by Takahashi; print NO otherwise.

Sample Input 1

4 4
1 2
2 4
1 3
3 4

Sample Output 1

YES

For example, Takahashi's graph has the property mentioned by him if it has the following edges: 1-2, 1-3 and 1-4.
In this case, the number written at every edge will become 2.

Sample Input 2

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

Sample Output 2

NO


module S = String

let solve a b c = if a.[(S.length a) - 1] == b.[0] && b.[(S.length b) - 1] == c.[0] then "YES" else "NO"

let () = Printf.printf "%s\n" (Scanf.scanf "%s %s %s" solve)

Score : 100 points

Problem Statement

You are given three strings A, B and C. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in A and the initial character in B are the same.

The last character in B and the initial character in C are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

A, B and C are all composed of lowercase English letters (a - z).

1 ≤ |A|, |B|, |C| ≤ 10, where |A|, |B| and |C| are the lengths of A, B and C, respectively.

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

A and B form a word chain, but B and C do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO


open Printf
open Scanf

let () =
  let shiritori a b c =
    if a.[String.length a - 1] = b.[0] && b.[String.length b - 1] = c.[0] then "YES" else "NO" in
  let a, b, c = scanf "%s %s %s\n" (fun x y z -> (x, y, z)) in
  shiritori a b c |> printf "%s\n"


let a, b, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = for i = 1 to b do if i * a mod b = c then (print_endline "YES"; exit 0) done; print_endline "NO"

Score : 200 points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of A, and you need to select at least one integer.

Your objective is to make the sum congruent to C modulo B.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

1 ≤ A ≤ 100

1 ≤ B ≤ 100

0 ≤ C < B

Input

Input is given from Standard Input in the following format:

A B C

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select 7 and 14, the sum 21 is congruent to 1 modulo 5.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select 97, since you may select multiples of 1, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO


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

let () = Scanf.scanf "%d %d\n" @@ fun n wmax ->
  let wvs = Array.init n @@ fun _ ->
    Scanf.scanf "%d %d\n" @@ fun w v -> w, v in
  Array.fold_left (fun m (w, v) ->
    IntMap.fold (fun w' v' m ->
      if wmax < w + w' then m
      else IntMap.add (w + w') (max (v + v') @@
        try IntMap.find (w + w') m with Not_found -> min_int) m) m m) (IntMap.singleton 0 0) wvs
  |> (fun m -> IntMap.fold (fun _ -> max) m min_int)
  |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

You have N items and a bag of strength W.
The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

1 ≤ N ≤ 100

1 ≤ W ≤ 10^9

1 ≤ w_i ≤ 10^9

For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.

1 ≤ v_i ≤ 10^7

W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.


let rec solve acc rmax rmin bmax bmin xys =
  if acc <= (rmax - rmin) * (bmax - bmin) then acc
  else
    match xys with
    | [] -> (rmax - rmin) * (bmax - bmin)
    | (x, y) :: rest ->
        solve
          (solve acc
            (max x rmax) (min x rmin)
            (max y bmax) (min y bmin) rest)
          (max y rmax) (min y rmin)
          (max x bmax) (min x bmin) rest

let () = Scanf.scanf "%d\n" @@ fun n ->
  let xys = Array.to_list @@ Array.init n @@ fun _ ->
    Scanf.scanf "%d %d\n" @@ fun x y -> x, y in
  Printf.printf "%d\n" @@ solve max_int 1 1000000000 1 1000000000 xys

Score : 700 points

Problem Statement

There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively.

For each of these bags, you will paint one of the balls red, and paint the other blue.

Afterwards, the 2N balls will be classified according to color.

Then, we will define the following:

R_{max}: the maximum integer written on a ball painted in red

R_{min}: the minimum integer written on a ball painted in red

B_{max}: the maximum integer written on a ball painted in blue

B_{min}: the minimum integer written on a ball painted in blue

Find the minimum possible value of (R_{max} - R_{min}) \times (B_{max} - B_{min}).

Constraints

1 ≤ N ≤ 200,000

1 ≤ x_i, y_i ≤ 10^9

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 minimum possible value.

Sample Input 1

3
1 2
3 4
5 6

Sample Output 1

15

The optimal solution is to paint the balls with x_1, x_2, y_3 red, and paint the balls with y_1, y_2, x_3 blue.

Sample Input 2

3
1010 10
1000 1
20 1020

Sample Output 2

380

Sample Input 3

2
1 1
1000000000 1000000000

Sample Output 3

999999998000000001


Scanf.scanf "%s %s %s" (fun s1 s2 s3 ->
    let c s = String.capitalize (String.sub s 0 1) in
    Printf.printf "%s%s%s\n" (c s1) (c s2) (c s3)
)

Score : 100 points

Problem Statement

You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between.
Print the acronym formed from the uppercased initial letters of the words.

Constraints

s_1, s_2 and s_3 are composed of lowercase English letters.

1 ≤ |s_i| ≤ 10 (1≤i≤3)

Input

Input is given from Standard Input in the following format:

s_1 s_2 s_3

Output

Print the answer.

Sample Input 1

atcoder beginner contest

Sample Output 1

ABC

The initial letters of atcoder, beginner and contest are a, b and c. Uppercase and concatenate them to obtain ABC.

Sample Input 2

resident register number

Sample Output 2

RRN

Sample Input 3

k nearest neighbor

Sample Output 3

KNN

Sample Input 4

async layered coding

Sample Output 4

ALC


let up c = String.uppercase (Char.escaped c)
let () =
  Scanf.scanf "%s %s %s" (fun s1 s2 s3 ->
      (up s1.[0]) ^ (up s2.[0]) ^ (up s3.[0]))
  |> print_endline


let e = "EQUAL" and g = "GREATER" and l = "LESS"

let f s1 s2 =
  let rec aux i =
    if i = String.length s1 then e
    else if s1.[i] > s2.[i] then g
    else if s1.[i] < s2.[i] then l
    else aux (i + i)
  in
  aux 0

let () =
  let a = read_line () and b = read_line () in
  ( if String.length a > String.length b then g
  else if String.length a < String.length b then l
  else f a b )
  |> print_endline

Score : 200 points

Problem Statement

You are given two positive integers A and B. Compare the magnitudes of these numbers.

Constraints

1 ≤ A, B ≤ 10^{100}

Neither A nor B begins with a 0.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print GREATER if A>B, LESS if A<B and EQUAL if A=B.

Sample Input 1

36
24

Sample Output 1

GREATER

Since 36>24, print GREATER.

Sample Input 2

850
3777

Sample Output 2

LESS

Sample Input 3

9720246
22516266

Sample Output 3

LESS

Sample Input 4

123456789012345678901234567890
234567890123456789012345678901

Sample Output 4

LESS


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

  let rec aux sum sign cnt l =
    match l with
    | [] -> cnt
    | hd :: tl -> match sign with
      | `Plus ->
        if sum + hd <= 0 then aux sum sign (cnt+1) (hd+1::tl) else aux (sum+hd) `Minus cnt tl
      | `Minus ->
        if sum + hd >= 0 then aux sum sign (cnt+1) (hd-1::tl) else aux (sum+hd) `Plus cnt tl
  in

  Printf.printf "%d\n" @@
  aux 0 (if List.hd a_lst > 0 then `Plus else `Minus) 0 a_lst

Score : 300 points

Problem Statement

You are given an integer sequence of length N. The i-th term in the sequence is a_i.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every i (1≤i≤n), the sum of the terms from the 1-st through i-th term is not zero.

For every i (1≤i≤n-1), the sign of the sum of the terms from the 1-st through i-th term, is different from the sign of the sum of the terms from the 1-st through (i+1)-th term.

Constraints

2 ≤ n ≤ 10^5

|a_i| ≤ 10^9

Each a_i is an integer.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into 1, -2, 2, -2 by four operations. The sums of the first one, two, three and four terms are 1, -1, 1 and -1, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8


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

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

Score : 300 points

Problem Statement

You are given an array A of length N.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide A into?

Constraints

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Each A_i is an integer.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible number of subarrays after division of A.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into [1,2,3] and [2,2,1].

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3


let rec remove value lst =
	let rec remove_sub rel value lst =
		match lst with
		| []      -> []
		| x :: xs ->
			if rel value x then remove_sub rel x xs
			else x :: xs
	in
	match lst with
	| []      -> []
	| x :: xs ->
		if value < x then remove_sub (<=) x xs
		else if value > x then remove_sub (>=) x xs
		else remove x xs

let rec solve count lst =
	match lst with
	| []      -> count
	| x :: xs -> solve (count + 1) (remove x xs)

let () =
	let n = read_int () in
	let a =
		read_line ()
		|> Str.split (Str.regexp " ")
		|> List.map int_of_string
	in
	solve 0 a
	|> print_int
	|> print_newline


open Batteries
open Tuple
module EnumL = Enum.Labels
module ListL = List.Labels

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

let (++) n m = List.range n `To m
let (++^) n m = List.range n `To (pred m)

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

let scan_lines n fmt f =
  if n = 0 then Enum.empty ()
  else
    List.map (fun _ -> scan fmt f) (List.range 1 `To n)
    |> List.enum

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

let scan_array = Array.of_list % scan_list

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (List.range 0 `To (pred n))
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

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

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

let (n,k) = scan "%d %d" Tuple2.make
let m = scan_array Int.of_string

let () =
  let sets = powerset (0 --^ n) in
  EnumL.map sets ~f:(fun set ->
      if Enum.count @@ Enum.clone set = k then
        let i = Enum.get_exn (Enum.clone set) in
        EnumL.fold set
          ~init:((try Array.max @@ Array.left m i with Invalid_argument _ -> 0), 0) ~f:(fun (h, acc) i ->
              if m.(i) > h then (m.(i), acc) else (h+1, acc+h+1 - m.(i)))
        |> Tuple2.second
      else
        Int.max_num)
  |> Enum.reduce min
  |> Printf.printf "%d\n"

Max Score: 350 Points

Problem Statement

There are N buildings along the line. The i-th building from the left is colored in color i, and its height is currently a_i meters.

Chokudai is a mayor of the city, and he loves colorful thigs. And now he wants to see at least K buildings from the left.

You can increase height of buildings, but it costs 1 yens to increase 1 meters. It means you cannot make building that height is not integer.

You cannot decrease height of buildings.

Calculate the minimum cost of satisfying Chokudai's objective.

Note: "Building i can see from the left" means there are no j exists that (height of building j) ≥ (height of building i) and j < i.

Input Format

N K
a_1 a_2 a_3 ... a_N

Output Format

Print the minimum cost in one line. In the end put a line break.

Constraints

1 ≤ K ≤ N ≤ 15

1 ≤ a_i ≤ 10^9

Scoring

Subtask 1 [120 points]

N = K

Subtask 2 [90 points]

N ≤ 5

a_i ≤ 7

Subtask 3 [140 points]

There are no additional constraints.

Sample Input 1

5 5
3949 3774 3598 3469 3424

Sample Output 1

1541

The optimal solution is (height of buildings from the left) = [3949, 3950, 3951, 3952, 3953].

Sample Input 2

5 3
7 4 2 6 4

Sample Output 2

7

The optimal solution is (height of buildings from the left) = [7, 8, 2, 9, 4].


open Scanf
open Printf

let () = scanf "%d %d %d" (fun a b c->
  if b - a = c - b then "YES" else "NO"
  ) |> printf "%s\n"

Score : 100 points

Problem Statement

Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right.
We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b.

Determine whether the arrangement of the poles is beautiful.

Constraints

1 \leq a,b,c \leq 100

a, b and c are integers.

Input

Input is given from Standard Input in the following format:

a b c

Output

Print YES if the arrangement of the poles is beautiful; print NO otherwise.

Sample Input 1

2 4 6

Sample Output 1

YES

Since 4-2 = 6-4, this arrangement of poles is beautiful.

Sample Input 2

2 5 6

Sample Output 2

NO

Since 5-2 \neq 6-5, this arrangement of poles is not beautiful.

Sample Input 3

3 2 1

Sample Output 3

YES

Since 1-2 = 2-3, this arrangement of poles is beautiful.


let () =
  let o = read_line () in
  let e = read_line () in
  print_endline @@ String.init (String.length o + String.length e) @@ fun i ->
    if i mod 2 = 0 then o.[i / 2] else e.[i / 2]

Score : 200 points

Problem Statement

Snuke signed up for a new website which holds programming competitions.
He worried that he might forget his password, and he took notes of it.
Since directly recording his password would cause him trouble if stolen,
he took two notes: one contains the characters at the odd-numbered positions, and the other contains the characters at the even-numbered positions.

You are given two strings O and E. O contains the characters at the odd-numbered positions retaining their relative order, and E contains the characters at the even-numbered positions retaining their relative order.
Restore the original password.

Constraints

O and E consists of lowercase English letters (a - z).

1 \leq |O|,|E| \leq 50

|O| - |E| is either 0 or 1.

Input

Input is given from Standard Input in the following format:

O
E

Output

Print the original password.

Sample Input 1

xyz
abc

Sample Output 1

xaybzc

The original password is xaybzc. Extracting the characters at the odd-numbered positions results in xyz, and extracting the characters at the even-numbered positions results in abc.

Sample Input 2

atcoderbeginnercontest
atcoderregularcontest

Sample Output 2

aattccooddeerrbreeggiunlnaerrccoonntteesstt


let () =
  let o,e = Scanf.scanf "%s %s " (fun a b -> a,b) in
  let o = Batteries.String.to_list o in
  let e = Batteries.String.to_list e in

  let rec aux l1 l2 res =
    match l1,l2 with
    | (hd1 :: tl1), (hd2 :: tl2) -> aux tl1 tl2 (res @ [hd1;hd2])
    | (hd1 :: tl1), [] -> res @ [hd1]
    | [], [] -> res
  in

  Printf.printf "%s\n" @@
  Batteries.String.of_list (aux o e [])


let base = 1000000007

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

let calc a n = List.fold_left (fun x y -> (x + y) mod base) 0 (List.mapi (fun i x -> (x * (n - 1 - 2 * i)) mod base) a)

let () =
    let (n, m) = Scanf.scanf "%d %d" (fun x y -> x, y) in
    let xs = input n in
    let ys = input m in
    let x_combi = calc xs n in
    let y_combi = calc ys m in
    print_int ((x_combi * y_combi) mod base);
    print_newline ();;

Score : 500 points

Problem Statement

On a two-dimensional plane, there are m lines drawn parallel to the x axis, and n lines drawn parallel to the y axis.
Among the lines parallel to the x axis, the i-th from the bottom is represented by y = y_i.
Similarly, among the lines parallel to the y axis, the i-th from the left is represented by x = x_i.

For every rectangle that is formed by these lines, find its area, and print the total area modulo 10^9+7.

That is, for every quadruple (i,j,k,l) satisfying 1\leq i < j\leq n and 1\leq k < l\leq m, find the area of the rectangle formed by the lines x=x_i, x=x_j, y=y_k and y=y_l, and print the sum of these areas modulo 10^9+7.

Constraints

2 \leq n,m \leq 10^5

-10^9 \leq x_1 < ... < x_n \leq 10^9

-10^9 \leq y_1 < ... < y_m \leq 10^9

x_i and y_i are integers.

Input

Input is given from Standard Input in the following format:

n m
x_1 x_2 ... x_n
y_1 y_2 ... y_m

Output

Print the total area of the rectangles, modulo 10^9+7.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is 60.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060


let comp x y =
    if x = y then 0
    else if x < y then 1
    else -1

let rec input xs n =
    if n = 0 then
        xs
    else
        let a = Scanf.scanf "%d " (fun a -> a) in
        input (a :: xs) (n-1)

let rec solve xs n res
    = if n = 0 then
          Printf.printf "%d\n" res
      else
          solve xs (n-1) (res + (List.nth xs (1 + (n-1)*2)))

let _ =
    let xs = Scanf.scanf "%d " (fun n -> 3 * n) |> input [] |> List.sort comp in
    solve xs ((List.length xs) / 3) 0

Score : 300 points

Problem Statement

There are 3N participants in AtCoder Group Contest.
The strength of the i-th participant is represented by an integer a_i.
They will form N teams, each consisting of three participants.
No participant may belong to multiple teams.

The strength of a team is defined as the second largest strength among its members.
For example, a team of participants of strength 1, 5, 2 has a strength 2, and a team of three participants of strength 3, 2, 3 has a strength 3.

Find the maximum possible sum of the strengths of N teams.

Constraints

1 ≤ N ≤ 10^5

1 ≤ a_i ≤ 10^{9}

a_i are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_{3N}

Output

Print the answer.

Sample Input 1

2
5 2 8 5 1 5

Sample Output 1

10

The following is one formation of teams that maximizes the sum of the strengths of teams:

Team 1: consists of the first, fourth and fifth participants.

Team 2: consists of the second, third and sixth participants.

Sample Input 2

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 2

10000000000

The sum of the strengths can be quite large.


let fst3 (a,b,c) = a
let () = Scanf.scanf "%d %d" @@ fun n m ->
  let es = Array.init m (fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a-1, b-1) in
  Scanf.scanf " %d" @@ fun q ->

  let qa =
    let t = Array.init 11 (fun _ -> []) in
    for i = 0 to q-1 do
      Scanf.scanf " %d %d %d" @@ fun v d c ->
      t.(10-d) <- (i, v-1, c) :: t.(10-d)
    done;
    Array.map List.rev t
  in

  let color = Array.make n (-1, 0, -1) in
  qa.(0) |> List.iter (fun (i, v, c) -> color.(v) <- i, c, 0);
  for r = 1 to 10 do
    Array.sort (fun (a,b) (c,d) ->
      min (fst3 color.(a)) (fst3 color.(b)) - min (fst3 color.(c)) (fst3 color.(d))) es;
    Array.iter (fun (u, v) ->
      let iu, cu, ru = color.(u) in
      let iv, cv, rv = color.(v) in
      if iu > iv && ru < r then color.(v) <- (iu, cu, ru+1);
      if iv > iu && rv < r then color.(u) <- (iv, cv, rv+1);
    ) es;
    qa.(r) |> List.iter (fun (i, v, c) ->
      let ia, _, _ = color.(v) in
      if i > ia then color.(v) <- (i, c, r));
  done;

  Array.iter (fun (_, c, _) -> Printf.printf "%d\n" c) color

Score : 700 points

Problem Statement

Squid loves painting vertices in graphs.

There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges.
Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1.

Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i.

Find the color of each vertex after the Q operations.

Constraints

1 ≤ N,M,Q ≤ 10^5

1 ≤ a_i,b_i,v_i ≤ N

a_i ≠ b_i

0 ≤ d_i ≤ 10

1 ≤ c_i ≤10^5

d_i and c_i are all integers.

There are no self-loops or multiple edges in the given graph.

Partial Score

200 points will be awarded for passing the testset satisfying 1 ≤ N,M,Q ≤ 2{,}000.

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
:
a_{M} b_{M}
Q
v_1 d_1 c_1
:
v_{Q} d_{Q} c_{Q}

Output

Print the answer in N lines.
In the i-th line, print the color of vertex i after the Q operations.

Sample Input 1

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

Sample Output 1

2
2
2
2
2
1
0

Initially, each vertex is painted in color 0.
In the first operation, vertices 5 and 6 are repainted in color 1.
In the second operation, vertices 1, 2, 3, 4 and 5 are repainted in color 2.

Sample Input 2

14 10
1 4
5 7
7 11
4 10
14 7
14 3
6 14
8 11
5 13
8 3
8
8 6 2
9 7 85
6 9 3
6 7 5
10 3 1
12 9 4
9 6 6
8 2 3

Sample Output 2

1
0
3
1
5
5
3
3
6
1
3
4
5
3

The given graph may not be connected.


Scanf.scanf "%d %d" @@ fun n m ->
  let es = Array.init m (fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a-1, b-1) in
  Scanf.scanf " %d" @@ fun q ->

  let qa = Array.init 11 (fun _ -> []) in
  for i = 0 to q-1 do
    Scanf.scanf " %d %d %d" @@ fun v d c ->
    qa.(10-d) <- (i, v-1, c) :: qa.(10-d)
  done;
  Array.iteri (fun i s -> qa.(i) <- List.rev s) qa;

  let cl = Array.make n (0, 0, 0) in
  qa.(0) |> List.iter (fun (i, v, c) -> cl.(v) <- i, c, 0);
  for r = 1 to 10 do
    Array.iter (fun (u, v) ->
      let iu, cu, ru = cl.(u) in
      let iv, cv, rv = cl.(v) in
      if ru > -r then cl.(v) <- max cl.(v) (iu, cu, ru-1);
      if rv > -r then cl.(u) <- max cl.(u) (iv, cv, rv-1);
    ) es;
    qa.(r) |> List.iter (fun (i, v, c) -> cl.(v) <- max cl.(v) (i, c, -r));
  done;

  Array.iter (fun (_, v, _) -> Printf.printf "%d\n" v) cl


Scanf.scanf "%d %d" @@ fun n m ->
  let es = Array.init m (fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a-1, b-1) in
  Scanf.scanf " %d" @@ fun q ->

  let qa = Array.init 11 (fun _ -> []) in
  for i = 0 to q-1 do
    Scanf.scanf " %d %d %d" @@ fun v d c ->
    qa.(10-d) <- (i, v-1, c) :: qa.(10-d)
  done;
  Array.iteri (fun i s -> qa.(i) <- List.rev s) qa;

  let cl = Array.make n (0, 0, 0) in
  qa.(0) |> List.iter (fun (i, v, c) -> cl.(v) <- i, c, 0);
  for r = 1 to 10 do
    Array.iter (fun (u, v) ->
      let iu, cu, ru = cl.(u) in
      let iv, cv, rv = cl.(v) in
      if ru < r then cl.(v) <- max cl.(v) (iu, cu, ru+1);
      if rv < r then cl.(u) <- max cl.(u) (iv, cv, rv+1);
    ) es;
    qa.(r) |> List.iter (fun (i, v, c) -> cl.(v) <- max cl.(v) (i, c, r));
  done;

  Array.iter (fun (_, v, _) -> Printf.printf "%d\n" v) cl


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

Score : 100 points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, 9:00 p.m. is referred to as "21 o'clock".

The current time is A o'clock, and a contest will begin in exactly B hours.
When will the contest begin? Answer in 24-hour time.

Constraints

0 \leq A,B \leq 23

A and B are integers.

Input

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

A B

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is 9 o'clock, and 12 hours later it will be 21 o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at 1 o'clock the next day.


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


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

  Printf.printf "%d\n" @@
    (a + b) mod 24


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


let n, m = Scanf.scanf " %d %d" @@ fun a b -> a, b
let ab_s = Array.init n @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let cds = Array.init m @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let f (a, b) = let m = ref (max_int, -1) in Array.iteri (fun i (c, d) -> m := min !m @@ (abs (a - c) + abs (b - d), i + 1)) cds; Printf.printf "%d\n" @@ snd !m
let _ = Array.iter f ab_s

Score : 200 points

Problem Statement

There are N students and M checkpoints on the xy-plane.

The coordinates of the i-th student (1 \leq i \leq N) is (a_i,b_i), and the coordinates of the checkpoint numbered j (1 \leq j \leq M) is (c_j,d_j).

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points (x_1,y_1) and (x_2,y_2) is |x_1-x_2|+|y_1-y_2|.

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

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

1 \leq N,M \leq 50

-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8

All input values are integers.

Input

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

N M
a_1 b_1
:
a_N b_N
c_1 d_1
:
c_M d_M

Output

Print N lines.

The i-th line (1 \leq i \leq N) should contain the index of the checkpoint for the i-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint 1: |2-(-1)|+|0-0|=3

For checkpoint 2: |2-1|+|0-0|=1

The nearest checkpoint is checkpoint 2. Thus, the first line in the output should contain 2.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint 1: |0-(-1)|+|0-0|=1

For checkpoint 2: |0-1|+|0-0|=1

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain 1.

Sample Input 2

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

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1


let digits n =
  let rec aux m ans =
    if m < 1 then ans else aux (m / 10) (succ ans)
  in
  aux n 0

let solve n =
  let b = sqrt n |> int_of_float in
  let intn = int_of_float n in
  let rec aux b' =
    if intn mod b' = 0 then max (digits b') (digits (intn / b'))
    else aux (pred b')
  in
  aux b

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

Score : 300 points

Problem Statement

You are given an integer N.

For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B.

For example, F(3,11) = 2 since 3 has one digit and 11 has two digits.

Find the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Constraints

1 \leq N \leq 10^{10}

N is an integer.

Input

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

N

Output

Print the minimum value of F(A,B) as (A,B) ranges over all pairs of positive integers such that N = A \times B.

Sample Input 1

10000

Sample Output 1

3

F(A,B) has a minimum value of 3 at (A,B)=(100,100).

Sample Input 2

1000003

Sample Output 2

7

There are two pairs (A,B) that satisfy the condition: (1,1000003) and (1000003,1). For these pairs, F(1,1000003)=F(1000003,1)=7.

Sample Input 3

9876543210

Sample Output 3

6


let dp = Array.make_matrix (50 + 1) (50 + 1) ~-1
let rec c n k = if dp.(n).(k) > -1 then dp.(n).(k) else (dp.(n).(k) <- if n < k then 0 else if n = k then 1 else if k = 0 then 1 else c (n - 1) (k - 1) + c (n - 1) k; dp.(n).(k))
let n, a, b = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b - 1, c - 1
let vs = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let m = Array.(sort (fun x y -> y - x) vs; vs.(0))
let j, k = ref ~-1, ref (b + 1)
let _ = Array.(iteri (fun i v -> if a <= i && i < !k && v < m then k := i; if i > 0 && i <= b && v <> vs.(i - 1) then j := i) vs; if a < !k then decr k; let t = fold_left (fun c v -> if v = vs.(!k) then c + 1 else c) 0 vs in
  Printf.printf "%.6f\n%d\n" (float (sub vs 0 (!k + 1) |> fold_left (+) 0) /. (float !k +. 1.)) @@ if vs.(!k) = m then let s = ref 0 in for i = a + 1 to b + 1 do s := !s + c t i done; !s else c t (!k - !j + 1))

Score : 400 points

Problem Statement

You are given N items.

The value of the i-th item (1 \leq i \leq N) is v_i.

Your have to select at least A and at most B of these items.

Under this condition, find the maximum possible arithmetic mean of the values of selected items.

Additionally, find the number of ways to select items so that the mean of the values of selected items is maximized.

Constraints

1 \leq N \leq 50

1 \leq A,B \leq N

1 \leq v_i \leq 10^{15}

Each v_i is an integer.

Input

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

N A B
v_1
v_2
...
v_N

Output

Print two lines.

The first line should contain the maximum possible arithmetic mean of the values of selected items. The output should be considered correct if the absolute or relative error is at most 10^{-6}.

The second line should contain the number of ways to select items so that the mean of the values of selected items is maximized.

Sample Input 1

5 2 2
1 2 3 4 5

Sample Output 1

4.500000
1

The mean of the values of selected items will be maximized when selecting the fourth and fifth items. Hence, the first line of the output should contain 4.5.

There is no other way to select items so that the mean of the values will be 4.5, and thus the second line of the output should contain 1.

Sample Input 2

4 2 3
10 20 10 10

Sample Output 2

15.000000
3

There can be multiple ways to select items so that the mean of the values will be maximized.

Sample Input 3

5 1 5
1000000000000000 999999999999999 999999999999998 999999999999997 999999999999996

Sample Output 3

1000000000000000.000000
1


let dp = Array.make_matrix (50 + 1) (50 + 1) ~-1
let rec c n k = if dp.(n).(k) > -1 then dp.(n).(k) else (dp.(n).(k) <- if n < k then 0 else if n = k then 1 else if k = 0 then 1 else c (n - 1) (k - 1) + c (n - 1) k; dp.(n).(k))
let n, a, b = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b - 1, c - 1
let vs = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let m = Array.(sort (fun x y -> y - x) vs; vs.(0))
let j, k = ref ~-1, ref (b + 1)
let _ = Array.(iteri (fun i v -> if a <= i && i < !k && v < m then k := i; if i > 0 && i <= b && v <> vs.(i - 1) then j := i) vs; if a < !k then decr k;
  Printf.printf "%.6f\n%d\n" (float (sub vs 0 (!k + 1) |> fold_left (+) 0) /. (float !k +. 1.)) @@ if vs.(!k) = m then 1 lsl (!k + 1) - 1 else c (fold_left (fun c v -> if v = vs.(!k) then c + 1 else c) 0 vs) (!k - !j + 1))


let a, b = Scanf.scanf "%s %s\n" @@ fun a b -> a, b
let ans = if a = "H" then b else if b = "H" then  "D" else "H"
let () = print_endline ans

Score : 100 points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters a and b as the input. Each of them is either H or D, and carries the following information:

If a=H, AtCoDeer is honest; if a=D, AtCoDeer is dishonest.
If b=H, AtCoDeer is saying that TopCoDeer is honest; if b=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

a=H or a=D.

b=H or b=D.

Input

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

a b

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H


let () =
  Scanf.scanf "%c %c" (fun a b ->
      if a = 'H' then b else match b with 'H' -> 'D' | _ -> 'H' )
  |> Printf.printf "%c\n"


let () = Scanf.scanf "%d %d %d" @@ fun w a b ->
  Printf.printf "%d\n" @@
  if a <= b
  then max 0 (b - a - w)
  else max 0 (a - b - w)

Score : 200 points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height 1 and width W.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of [0,1] and the horizontal range of [a,a+W], and the second rectangle covers the vertical range of [1,2] and the horizontal range of [b,b+W], as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

1≤W≤10^5

1≤a,b≤10^5

Input

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

W a b

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of 1.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4


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

  let t = if a < b then
      b-a-w
    else if a > b then
      a-b-w
    else 0
  in
  Printf.printf "%d\n" @@
    if t <= 0 then 0 else t


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


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

Score : 200 points

Problem Statement

There is a kangaroo at coordinate 0 on an infinite number line that runs from left to right, at time 0.
During the period between time i-1 and time i, the kangaroo can either stay at his position, or perform a jump of length exactly i to the left or to the right.
That is, if his coordinate at time i-1 is x, he can be at coordinate x-i, x or x+i at time i.
The kangaroo's nest is at coordinate X, and he wants to travel to coordinate X as fast as possible.
Find the earliest possible time to reach coordinate X.

Constraints

X is an integer.

1≤X≤10^9

Input

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

X

Output

Print the earliest possible time for the kangaroo to reach coordinate X.

Sample Input 1

6

Sample Output 1

3

The kangaroo can reach his nest at time 3 by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2

He can reach his nest at time 2 by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5


let f x = int_of_float (ceil ((-1. +. sqrt (1. +. 8. *. x)) /. 2.))

let () = Scanf.scanf "%f" (fun x -> print_int (f x))


let x = read_int ()
let i = ref 1
let _ = while !i * (!i + 1) / 2 < x do incr i done; Printf.printf "%d\n" @@ !i


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

  let rec aux i res =
    if res >= x then i-1
    else aux (i+1) (res+i)
  in

  Printf.printf "%d\n" @@
  aux 1 0


let () = Scanf.scanf "%d\n" @@ fun n ->
  let lrs = Array.init n @@ fun _ -> Scanf.scanf "%d %d\n" @@ fun l r -> l, r in
  let f x = Array.fold_right (fun (l, r) -> ( + ) @@
    if x < l then l - x
    else if r < x then x - r
    else 0) lrs 0 in
  let l = Array.fold_right (fun (l, _) -> min l) lrs max_int in
  let r = Array.fold_right (fun (_, r) -> max r) lrs min_int in
  Printf.printf "%d\n" @@
  Array.fold_left min max_int @@
  Array.init (r - l + 1) @@ fun i -> f @@ i + l

Score : 1000 points

Problem Statement

AtCoDeer the deer found N rectangle lying on the table, each with height 1.
If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure:

AtCoDeer will move these rectangles horizontally so that all the rectangles are connected.
For each rectangle, the cost to move it horizontally by a distance of x, is x.
Find the minimum cost to achieve connectivity.
It can be proved that this value is always an integer under the constraints of the problem.

Constraints

All input values are integers.

1≤N≤10^5

1≤l_i<r_i≤10^9

Partial Score

300 points will be awarded for passing the test set satisfying 1≤N≤400 and 1≤l_i<r_i≤400.

Input

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

N
l_1 r_1
l_2 r_2
:
l_N r_N

Output

Print the minimum cost to achieve connectivity.

Sample Input 1

3
1 3
5 7
1 3

Sample Output 1

2

The second rectangle should be moved to the left by a distance of 2.

Sample Input 2

3
2 5
4 6
1 4

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5
999999999 1000000000
1 2
314 315
500000 500001
999999999 1000000000

Sample Output 3

1999999680

Sample Input 4

5
123456 789012
123 456
12 345678901
123456 789012
1 23

Sample Output 4

246433

Sample Input 5

1
1 400

Sample Output 5

0


let n, c, k = Scanf.scanf "%d %d %d" (fun n c k -> n, c, k)
let t = Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i))

let rec f i t' p b =
  if i = n then b
  else if t' < t.(i) || p = c then f (i + 1) (t.(i) + k) 1 (b + 1)
  else f (i + 1) t' (p + 1) b

let () =
  Array.sort (fun x y -> x - y) t;
  let ans = f 0 0 0 0 in
  Printf.printf "%d\n" ans

Score : 300 points

Problem Statement

Every day, N passengers arrive at Takahashi Airport.
The i-th passenger arrives at time T_i.

Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers.
Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport.
Also, a passenger will get angry if he/she is still unable to take a bus K units of time after the arrival of the airplane.
For that reason, it is necessary to arrange buses so that the i-th passenger can take a bus departing at time between T_i and T_i + K (inclusive).

When setting the departure times for buses under this condition, find the minimum required number of buses.
Here, the departure time for each bus does not need to be an integer, and there may be multiple buses that depart at the same time.

Constraints

2 \leq N \leq 100000

1 \leq C \leq 10^9

1 \leq K \leq 10^9

1 \leq T_i \leq 10^9

C, K and T_i are integers.

Input

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

N C K
T_1
T_2
:
T_N

Output

Print the minimum required number of buses.

Sample Input 1

5 3 5
1
2
3
6
12

Sample Output 1

3

For example, the following three buses are enough:

A bus departing at time 4.5, that carries the passengers arriving at time 2 and 3.

A bus departing at time 6, that carries the passengers arriving at time 1 and 6.

A bus departing at time 12, that carries the passenger arriving at time 12.

Sample Input 2

6 3 3
7
6
2
8
10
6

Sample Output 2

3


(* O(n log n) *)
let n, c, k = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let ts = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let rec loop acc i r m =
  if i >= n then acc
  else if m >= c || r < ts.(i) then loop (acc + 1) (i + 1) (ts.(i) + k) 1
  else loop acc (i + 1) r (m + 1)
let _ =
  Array.sort (-) ts;
  loop 1 1 (ts.(0) + k) 1 |> Printf.printf "%d\n"


let id x = x

let (n,c,k) = Scanf.scanf "%d %d %d\n" (fun n c k -> (n,c,k))

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n-1) in
  loop []

let t = repeat (fun () -> Scanf.scanf "%d\n" id) n

let rec partition n a b = function
  [] -> (a, b)
| x::xs -> if x < n then partition n (x::a) b xs
              else partition n a (x::b) xs

let rec quick_sort = function
  [] -> []
| x::xs ->
    let (m, n) = partition x [] [] xs in
    quick_sort m @ (x :: quick_sort n)

let tlist = quick_sort t

let check' tlist c k =
let rec check tlist ans t' d cnt =
  match tlist with
  | [] -> ans
  | hd :: rest -> if hd > t' then check tlist ans hd d cnt else
     match cnt with
     | 0 -> check rest ans t' (hd+k) (cnt+1)
     | _ -> if t' > d || cnt = c then check tlist (ans + 1) t' d 0
             else check rest ans t' d (cnt+1)
in check tlist 1 1 0 0

let ans = check' tlist c k

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


let split_string ?(pattern=" ") = Str.split @@ Str.regexp pattern

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

let () =
  Array.sort (fun a b -> a - b) a;
  let sum = ref a.(0) in
  for i = 1 to n - 1 do
    if !sum * 2 < a.(i) then begin
      Printf.printf "%d\n" (n - i);
      exit 0;
    end;
    sum := !sum + a.(i)
  done;
  Printf.printf "%d\n" n

Score : 400 points

Problem Statement

Snuke found N strange creatures.
Each creature has a fixed color and size. The color and size of the i-th creature are represented by i and A_i, respectively.

Every creature can absorb another creature whose size is at most twice the size of itself.
When a creature of size A and color B absorbs another creature of size C and color D (C \leq 2 \times A), they will merge into one creature of size A+C and color B.
Here, depending on the sizes of two creatures, it is possible that both of them can absorb the other.

Snuke has been watching these creatures merge over and over and ultimately become one creature.
Find the number of the possible colors of this creature.

Constraints

2 \leq N \leq 100000

1 \leq A_i \leq 10^9

A_i is an integer.

Input

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

N
A_1 A_2 … A_N

Output

Print the number of the possible colors of the last remaining creature after the N creatures repeatedly merge and ultimately become one creature.

Sample Input 1

3
3 1 4

Sample Output 1

2

The possible colors of the last remaining creature are colors 1 and 3.
For example, when the creature of color 3 absorbs the creature of color 2, then the creature of color 1 absorbs the creature of color 3, the color of the last remaining creature will be color 1.

Sample Input 2

5
1 1 1 1 1

Sample Output 2

5

There may be multiple creatures of the same size.

Sample Input 3

6
40 1 30 2 7 20

Sample Output 3

4


Scanf.scanf "%d" (fun n ->
    Printf.printf "%d\n" @@ (n * 800 - (n / 15) * 200)
)

Score : 100 points

Problem Statement

Snuke has a favorite restaurant.

The price of any meal served at the restaurant is 800 yen (the currency of Japan), and each time a customer orders 15 meals, the restaurant pays 200 yen back to the customer.

So far, Snuke has ordered N meals at the restaurant.
Let the amount of money Snuke has paid to the restaurant be x yen, and let the amount of money the restaurant has paid back to Snuke be y yen.
Find x-y.

Constraints

1 ≤ N ≤ 100

Input

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

N

Output

Print the answer.

Sample Input 1

20

Sample Output 1

15800

So far, Snuke has paid 16000 yen, and the restaurant has paid back 200 yen. Thus, the answer is 15800.

Sample Input 2

60

Sample Output 2

47200

Snuke has paid 48000 yen for 60 meals, and the restaurant has paid back 800 yen.


let n = read_int ()
let _ = Printf.printf "%d\n" @@ 800 * n - n / 15 * 200


let () = Scanf.scanf "%d" @@ fun n ->
  Printf.printf "%d\n" @@ 800 * n - n / 15 * 200


let n = read_int () in
let p = ref 1 in
for i = 1 to n do
  p := !p * i mod 1_000_000_007
done;
Printf.printf "%d\n" !p

Score : 200 points

Problem Statement

Snuke loves working out. He is now exercising N times.

Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.

Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.

Constraints

1 ≤ N ≤ 10^{5}

Input

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

N

Output

Print the answer modulo 10^{9}+7.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by 1 and becomes 1.

After Snuke exercises for the second time, his power gets multiplied by 2 and becomes 2.

After Snuke exercises for the third time, his power gets multiplied by 3 and becomes 6.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo 10^{9}+7.


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

  let rec fact n res =
    if n=1 then res
    else fact (n-1) ((n*res) mod 1000000007)
  in

  Printf.printf "%d\n" @@
    (fact n 1)


let f n =
  let m = 1000000007 in
  let rec aux i tmp =
    if i >= n then tmp
    else aux (succ i) ((tmp * (i + 1)) mod m)
  in
  aux 1 1

let () =
  f @@ read_int () |> Printf.printf "%d\n"


let get_2_ints () = Scanf.scanf "%d %d " (fun u v -> u,v)

let () =
  let (n,m) = get_2_ints ()
  in
  let scc,c_left = n,m-n*2
  in let s_new = c_left / 4
  in
  let scc = scc + s_new
  in
  scc |> string_of_int |> print_endline

Score : 300 points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has N S-shaped pieces and M c-shaped pieces.

Constraints

1 ≤ N,M ≤ 10^{12}

Input

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

N M

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897


let first_some f =
  List.fold_left (fun v e -> match v with None -> f e | _ -> v) None

let nb a b r =
  let f b = if b then 1 else 0 in
  [|'W';'S'|].((f (b = 'S') + f (r = 'o') + f (a = 'S')) mod 2)

let () =
  Scanf.scanf "%d %s" @@ fun n s ->
  [('S','S'); ('S','W'); ('W','S'); ('W','W')]
  |> first_some (fun (h0, h1) ->
      let h = Array.make n '0' in
      h.(0) <- h0; h.(1) <- h1;

      let t = String.init n (fun i ->
        if i < 2 then h.(i)
        else
          let v = nb h.(i-2) h.(i-1) s.[i-1] in
          h.(i) <- v; v)
      in

      if nb h.(n-2) h.(n-1) s.[n-1] = h.(0) && nb h.(n-1) h.(0) s.[0] = h.(1) then
        Some t
      else None)
  |> (function Some x -> x | _ -> "-1") |> print_endline

Score : 500 points

Problem Statement

Snuke, who loves animals, built a zoo.

There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle.
The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is o, the animal said that the two neighboring animals are of the same species, and if s_i is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

3 ≤ N ≤ 10^{5}

s is a string of length N consisting of o and x.

Input

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

N
s

Output

If there does not exist an valid assignment that is consistent with s, print -1.
Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.

t is a string of length N consisting of S and W.

If t_i is S, it indicates that the animal numbered i is a sheep. If t_i is W, it indicates that the animal numbered i is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered 1, 2, 3, 4, 5 and 6 are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS


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

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

let () =
	let n = get_int ()
	in let a =
		Array.init n (fun _ -> Scanf.scanf " %c" (fun v -> v))
	in let b = Array.make n 0
	in
	let f,i,e = ref true,ref 0,[|0,0;0,1;1,1;1,0|] in
	while !f && !i<4 do
		let e0,e1 = e.(!i) in
		b.(0) <- e0; b.(1) <- e1;
		for j=2 to n-1 do
			b.(j) <- match b.(j-1),a.(j-1) with
				| 0,'o' | 1,'x' -> b.(j-2)
				| 0,'x' | 1,'o' -> 1-b.(j-2)
				| _ -> failwith ""
		done;
		f := not (
			b.(0) = (
				match b.(n-1),a.(n-1) with
				| 0,'o' | 1,'x' -> b.(n-2)
				| 0,'x' | 1,'o' -> 1-b.(n-2)
				| _ -> failwith ""
			)
			&&
			b.(1) = match b.(0),a.(0) with
			| 0,'o' | 1,'x' -> b.(n-1)
			| 0,'x' | 1,'o' -> 1-b.(n-1)
			| _ -> failwith ""
		);
;		i := !i+1;
	done;
	if not !f then (
		Array.iter (fun v -> print_string @@ if v=0 then "S" else "W") b; print_newline ()
	) else printf "-1\n"


let string_to_list str =
  let rec loop i limit =
    if i = limit then []
    else (String.get str i) :: (loop (i + 1) limit)
  in
  loop 0 (String.length str)

let fwd arr_length n = if n = (arr_length - 1) then 0 else n+1
let prev arr_length n = if n = 0 then arr_length - 1 else n-1
let flip c = if c = 'S' then 'W' else 'S'
let print_chars arr = Array.iter (fun x -> Printf.printf "%c" x) arr; Printf.printf "\n"

let fill arr arr_length n by =
  arr.(fwd arr_length n) <-
    if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
      arr.(prev arr_length n)
    else
      flip arr.(prev arr_length n)

let rec extend answers ans_length cursor ret = match answers with
  | [] -> ret
  | x::rest ->
     fill ret ans_length cursor x;
     extend rest ans_length (cursor+1) ret

let check arr arr_length by n =
  if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
    arr.(fwd arr_length n) = arr.(prev arr_length n)
  else
    arr.(fwd arr_length n) <> arr.(prev arr_length n)

let make_list f t step =
  let rec make_list_inner c t lst =
    if c >= t then lst else make_list_inner (c+step) t (c::lst)
  in
  List.rev (make_list_inner f t [])

let check_all pos_ans length pairs =
  let checks = List.map (fun (x,y) -> check pos_ans length y x) pairs in
  List.fold_left (fun x y -> x && y) true checks

let array_make length a b =
  let ret = (Array.make length a) in
  ret.(length - 1) <- b;
  ret

let solve str =
  let str_list = (string_to_list str) in
  let length = List.length str_list in
  let pairs = List.combine (make_list 0 length 1) str_list in
  let pos_ans = extend str_list length 0 (array_make length 'S' 'S') in
  if check_all pos_ans length pairs then pos_ans else
    let pos_ans = extend str_list length 0 (array_make length 'S' 'W') in
    if check_all pos_ans length pairs then pos_ans else
      let pos_ans = extend str_list length 0 (array_make length 'W' 'W') in
      if check_all pos_ans length pairs then pos_ans else
        let pos_ans = extend str_list length 0 (array_make length 'W' 'S') in
        if check_all pos_ans length pairs then pos_ans else
          [||]

let () =
  let _ = read_int() in
  let str = read_line () in
  let ans = solve str in
  if ans = [||] then
    Printf.printf ("-1")
  else
    Array.iter (fun x -> Printf.printf "%c" x) ans;
  Printf.printf "\n"
;;


let string_to_list str =
  let rec loop i limit =
    if i = limit then []
    else (String.get str i) :: (loop (i + 1) limit)
  in
  loop 0 (String.length str)

let fwd arr_length n = if n = (arr_length - 1) then 0 else n+1
let prev arr_length n = if n = 0 then arr_length - 1 else n-1
let flip c = if c = 'S' then 'W' else 'S'
let print_chars arr = Array.iter (fun x -> Printf.printf "%c" x) arr; Printf.printf "\n"

let fill arr arr_length n by =
  if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
    begin
      arr.(fwd arr_length n) <- arr.(prev arr_length n);
    end
  else
    begin
      arr.(fwd arr_length n) <- flip arr.(prev arr_length n);
    end

let rec extend answers ans_length cursor ret = match answers with
  | [] -> ret
  | 'o'::rest ->
     fill ret ans_length cursor 'o';
     extend rest ans_length (cursor+1) ret
  | 'x'::rest ->
     fill ret ans_length cursor 'x';
     extend rest ans_length (cursor+1) ret
  | _ -> ret

let check arr arr_length by n =
  if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
    arr.(fwd arr_length n) = arr.(prev arr_length n)
  else
    arr.(fwd arr_length n) <> arr.(prev arr_length n)

let make_list f t step =
  let rec make_list_inner c t lst =
    if c >= t then lst else make_list_inner (c+step) t (c::lst)
  in
  List.rev (make_list_inner f t [])

let check_all pos_ans length pairs =
  let checks = List.map (fun (x,y) -> check pos_ans length y x) pairs in
  List.fold_left (fun x y -> x && y) true checks

let array_make length a b =
  let ret = (Array.make length a) in
  ret.(1) <- b;
  ret

let solve str =
  let str_list = (string_to_list str) in
  let length = List.length str_list in
  let pairs = List.combine (make_list 0 length 1) str_list in
  let pos_ans = extend str_list length 0 (array_make length 'S' 'S') in
  if check_all pos_ans length pairs then pos_ans else
    let pos_ans = extend str_list length 0 (array_make length 'S' 'W') in
    if check_all pos_ans length pairs then pos_ans else
      let pos_ans = extend str_list length 0 (array_make length 'W' 'W') in
      if check_all pos_ans length pairs then pos_ans else
        let pos_ans = extend str_list length 0 (array_make length 'W' 'S') in
        if check_all pos_ans length pairs then pos_ans else
          [||]

let () =
  let _ = read_int() in
  let str = read_line () in
  let ans = solve str in
  if ans = [||] then
    Printf.printf ("-1")
  else
    Array.iter (fun x -> Printf.printf "%c" x) ans;
  Printf.printf "\n"
;;


let string_to_list str =
  let rec loop i limit =
    if i = limit then []
    else (String.get str i) :: (loop (i + 1) limit)
  in
  loop 0 (String.length str)

let fwd arr_length n = if n = (arr_length - 1) then 0 else n+1
let prev arr_length n = if n = 0 then arr_length - 1 else n-1
let flip c = if c = 'S' then 'W' else 'S'
let print_chars arr = Array.iter (fun x -> Printf.printf "%c" x) arr; Printf.printf "\n"

let fill arr arr_length n by =
  if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
    begin
      arr.(fwd arr_length n) <- arr.(prev arr_length n);
    end
  else
    begin
      arr.(fwd arr_length n) <- flip arr.(prev arr_length n);
    end

let rec extend answers ans_length cursor ret = match answers with
  | [] -> ret
  | 'o'::rest ->
     fill ret ans_length cursor 'o';
     extend rest ans_length (cursor+1) ret
  | 'x'::rest ->
     fill ret ans_length cursor 'x';
     extend rest ans_length (cursor+1) ret
  | _ -> ret

let check arr arr_length by =
  let n = arr_length - 1 in
  if (arr.(n) == 'S' && by = 'o') || (arr.(n) == 'W' && by = 'x') then
    arr.(0) = arr.(n-2)
  else
    arr.(0) <> arr.(n-2)

let solve str =
  let str_list = (string_to_list str) in
  let length = List.length str_list in
  let pos_ans = extend str_list length 0 (Array.make length 'S') in
  if check pos_ans length (List.hd @@ List.rev str_list) then pos_ans else
    let pos_ans = extend str_list length 0 (Array.make length 'S') in
    if check pos_ans length (List.hd @@ List.rev str_list) then pos_ans else
      [||]

let () =
  let _ = read_int() in
  let str = read_line () in
  let ans = solve str in
  if ans = [||] then
    Printf.printf ("-1")
  else
    Array.iter (fun x -> Printf.printf "%c" x) ans;
  Printf.printf "\n"
;;