Scanf.scanf "%s" (fun s ->
    let n = String.length s in
    print_endline @@ if (n mod 2 = 1) = (s.[0] = s.[n - 1]) then "Second" else "First"
)

Score : 500 points

Problem Statement

There is a string s of length 3 or greater.
No two neighboring characters in s are equal.

Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:

Remove one of the characters in s, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in s.

The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.

Constraints

3 ≤ |s| ≤ 10^5

s consists of lowercase English letters.

No two neighboring characters in s are equal.

Input

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

s

Output

If Takahashi will win, print First. If Aoki will win, print Second.

Sample Input 1

aba

Sample Output 1

Second

Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of s, would result in s becoming aa, with two as neighboring.

Sample Input 2

abc

Sample Output 2

First

When Takahashi removes b from s, it becomes ac.
Then, Aoki cannot perform the operation, since there is no character in s, excluding both ends.

Sample Input 3

abcab

Sample Output 3

First


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

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d\n" @@ fun a -> a in
  Array.to_list as_
  |> List.map (fun a -> a lxor (a - 1))
  |> List.sort_uniq compare
  |> List.fold_left (fun m a ->
      IntMap.fold (fun x n m ->
        IntMap.add (x lxor a)
          (min (1 + n) @@
            try IntMap.find (x lxor a lxor (a - 1)) m
            with Not_found -> max_int) m) m m)
    (IntMap.singleton (Array.fold_left ( lxor ) 0 as_) 0)
  |> fun m ->
      Printf.printf "%d\n" @@
        try IntMap.find 0 m with Not_found -> -1

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

Score : 500 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

A cheetah and a cheater are going to play the game of Nim.
In this game they use N piles of stones.
Initially the i-th pile contains a_i stones.
The players take turns alternately, and the cheetah plays first.
In each turn, the player chooses one of the piles, and takes one or more stones from the pile.
The player who can't make a move loses.

However, before the game starts, the cheater wants to cheat a bit to make sure that he can win regardless of the moves by the cheetah.
From each pile, the cheater takes zero or one stone and eats it before the game.
In case there are multiple ways to guarantee his winning, he wants to minimize the number of stones he eats.

Compute the number of stones the cheater will eat.
In case there is no way for the cheater to win the game even with the cheating, print -1 instead.

Constraints

1 ≤ N ≤ 10^5

2 ≤ a_i ≤ 10^9

Input

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

N
a_1
:
a_N

Output

Print the answer.

Sample Input 1

3
2
3
4

Sample Output 1

3

The only way for the cheater to win the game is to take stones from all piles and eat them.

Sample Input 2

3
100
100
100

Sample Output 2

-1

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 s = read_line ()
let f s = String.(init (length s) @@ fun i -> s.[length s - i - 1])
let _ = print_endline @@ if s = String.map (function 'b' -> 'd' | 'd' -> 'b' | 'p' -> 'q' | 'q' -> 'p' | c -> c) @@ f s then "Yes" else "No"

Score : 100 points

Problem Statement

You are given a string S consisting of letters b, d, p and q.
Determine whether S is a mirror string.

Here, a mirror string is a string S such that the following sequence of operations on S results in the same string S:

Reverse the order of the characters in S.

Replace each occurrence of b by d, d by b, p by q, and q by p, simultaneously.

Constraints

1 \leq |S| \leq 10^5

S consists of letters b, d, p, and q.

Input

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

S

Output

If S is a mirror string, print Yes. Otherwise, print No.

Sample Input 1

pdbq

Sample Output 1

Yes

Sample Input 2

ppqb

Sample Output 2

No


Scanf.scanf "%d %d" (fun h w ->
    let rec loop i acc =
        let rec loop2 j acc =
            if j = w then acc else
            let acc = Scanf.scanf " %s" (fun s ->
                if s = "snuke" then Printf.sprintf "%c%d" "ABCDEFGHIJKLMNOPQRSTUVWXYZ".[j] i else acc)
            in
            loop2 (j + 1) acc
        in
        if i > h then acc else loop (i + 1) (loop2 0 acc)
    in
    print_endline @@ loop 1 ""
)

Score : 100 points

Problem Statement

There is a grid with H rows and W columns.

The square at the i-th row and j-th column contains a string S_{i,j} of length 5.

The rows are labeled with the numbers from 1 through H, and the columns are labeled with the uppercase English letters from A through the W-th letter of the alphabet.

Exactly one of the squares in the grid contains the string snuke. Find this square and report its location.

For example, the square at the 6-th row and 8-th column should be reported as H6.

Constraints

1≦H, W≦26

The length of S_{i,j} is 5.

S_{i,j} consists of lowercase English letters (a-z).

Exactly one of the given strings is equal to snuke.

Input

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

H W
S_{1,1} S_{1,2} ... S_{1,W}
S_{2,1} S_{2,2} ... S_{2,W}
:
S_{H,1} S_{H,2} ... S_{H,W}

Output

Print the labels of the row and the column of the square containing the string snuke, with no space inbetween.

Sample Input 1

15 10
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snuke snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake

Sample Output 1

H6

Sample Input 2

1 1
snuke

Sample Output 2

A1


Scanf.scanf "%d %d" (fun n m ->
    let link = Array.make m [] in
    for i = 0 to n - 1 do
        Scanf.scanf " %d" (fun k ->
            for j = 1 to k do
                Scanf.scanf " %d" (fun l ->
                    let l = l - 1 in
                    link.(l) <- i :: link.(l)
                )
            done
        )
    done;
    let par = Array.init n (fun i -> i) in
    let rec root x =
        if x = par.(x) then x else
            let r = root par.(x) in
            let () = par.(x) <- r in
            r
    in
    let merge a b =
        if root a <> root b then (
            par.(par.(b)) <- par.(a)
        )
    in
    Array.iter (fun l ->
        match l with
        | [] -> ()
        | hd :: tl -> List.iter (fun v -> merge hd v) tl
    ) link;
    let rec loop i =
        if i = n then "YES" else
            if root 0 = root i then loop (i + 1) else "NO"
    in
    print_endline @@ loop 0
)

Score : 400 points

Problem Statement

On a planet far, far away, M languages are spoken. They are conveniently numbered 1 through M.

For CODE FESTIVAL 20XX held on this planet, N participants gathered from all over the planet.

The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}.

Two participants A and B can communicate with each other if and only if one of the following conditions is satisfied:

There exists a language that both A and B can speak.

There exists a participant X that both A and B can communicate with.

Determine whether all N participants can communicate with all other participants.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦K_i≦M

(The sum of all K_i)≦10^5

1≦L_{i,j}≦M

L_{i,1}, L_{i,2}, ..., L_{i,{}K_i} are pairwise distinct.

Partial Score

200 points will be awarded for passing the test set satisfying the following: N≦1000, M≦1000 and (The sum of all K_i)≦1000.

Additional 200 points will be awarded for passing the test set without additional constraints.

Input

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

N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N}

Output

If all N participants can communicate with all other participants, print YES. Otherwise, print NO.

Sample Input 1

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

Sample Output 1

YES

Any two participants can communicate with each other, as follows:

Participants 1 and 2: both can speak language 2.

Participants 2 and 3: both can speak language 4.

Participants 1 and 3: both can communicate with participant 2.

Participants 3 and 4: both can speak language 6.

Participants 2 and 4: both can communicate with participant 3.

Participants 1 and 4: both can communicate with participant 2.

Note that there can be languages spoken by no participant.

Sample Input 2

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

Sample Output 2

NO

For example, participants 1 and 3 cannot communicate with each other.


Scanf.scanf "%d %d" (fun n m ->
    let hist = Array.make 100001 0 in
    let modgrp = Array.make m 0 in
    for i = 1 to n do
        Scanf.scanf " %d" (fun x ->
            hist.(x) <- hist.(x) + 1;
            modgrp.(x mod m) <- modgrp.(x mod m) + 1;
        )
    done;
    let calc1 i = modgrp.(i) / 2 in
    let calc2 i j =
        let i, j = if modgrp.(i) <= modgrp.(j) then i, j else j, i in
        let rest = modgrp.(j) - modgrp.(i) in

        let rec loop k acc =
            if k > 100000 then acc else
                let acc = acc + hist.(k) / 2 in
                if acc >= rest then rest else loop (k + m) acc
        in
        let acc1 = loop j 0 in
        acc1 + modgrp.(i)
    in
    let rec loop i acc =
        if i * 2 > m then acc else
            let acc = if i = 0 || i * 2 = m then acc + calc1 i
                                            else acc + calc2 i (m - i)
            in
            loop (i + 1) acc
    in
    loop 0 0 |> Printf.printf "%d\n"
)

Score : 700 points

Problem Statement

Takahashi is playing with N cards.

The i-th card has an integer X_i on it.

Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:

The integers on the two cards are the same.

The sum of the integers on the two cards is a multiple of M.

Find the maximum number of pairs that can be created.

Note that a card cannot be used in more than one pair.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦X_i≦10^5

Input

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

N M
X_1 X_2 ... X_N

Output

Print the maximum number of pairs that can be created.

Sample Input 1

7 5
3 1 4 1 5 9 2

Sample Output 1

3

Three pairs (3,2), (1,4) and (1,9) can be created.

It is possible to create pairs (3,2) and (1,1), but the number of pairs is not maximized with this.

Sample Input 2

15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99

Sample Output 2

6


(* 配列版素集合データ構造 *)
module RawUnionFind : sig
  type t
  type class_

  (* n要素の素集合データ構造を作る *)
  val make : int -> t
  (* 要素がどの集合に属するか調べる *)
  (* 要素は0からn-1の整数である必要がある *)
  val find : t -> int -> class_
  (* 与えられた要素が属する集合同士を合併する *)
  val unite : t -> int -> int -> unit

  val compare_class : class_ -> class_ -> int
end = struct
  type t = { rank : int array; parent : int array }
  type class_ = int

  let make n =
    { rank = Array.make n 0;
      parent = Array.init n (fun c -> c) }

  let rec find uf x =
    if x = uf.parent.(x) then x
    else begin
      let y = find uf uf.parent.(x) in
      uf.parent.(x) <- y; y
    end

  let unite uf i j =
    let x = find uf i in
    let y = find uf j in
    if x <> y then begin
      if uf.rank.(x) < uf.rank.(y) then uf.parent.(x) <- y
      else begin
        uf.parent.(y) <- x;
        if uf.rank.(x) = uf.rank.(y) then
          uf.rank.(x) <- 1 + uf.rank.(x)
      end
    end

  let compare_class = compare
end

let () = Scanf.scanf "%d %d\n" @@ fun n m ->
  let ls = Array.make m [] in
  for i = 0 to n - 1 do
    Scanf.scanf "%d " @@ fun k ->
      for j = 0 to k - 1 do
        Scanf.scanf "%d " @@ fun l ->
          ls.(l - 1) <- i :: ls.(l - 1)
      done
  done;
  let uf = RawUnionFind.make n in
  Array.iter (function
    | [] -> ()
    | x :: xs -> List.iter (RawUnionFind.unite uf x) xs) ls;
  print_endline @@
  if
    List.for_all (fun x ->
      RawUnionFind.compare_class
        (RawUnionFind.find uf 0)
        (RawUnionFind.find uf x) = 0) @@
    Array.to_list @@
    Array.init n @@ fun i -> i
  then "YES"
  else "NO"


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

    let rec loop x y f =
        let xf = x < w - 1 && a.(y).[x + 1] = '#' in
        let yf = y < h - 1 && a.(y + 1).[x] = '#' in
        let zf = x > 0     && a.(y).[x - 1] = '#' in
        let wf = y > 0     && a.(y - 1).[x] = '#' in
        if xf && yf then false else
            if f = 0 && wf then false else
            if f = 1 && zf then false else
            if xf then loop (x + 1) y 0 else
            if yf then loop x (y + 1) 1 else
            if x = w - 1 && y = h - 1 then true else
                false

    in
    print_endline @@ if loop 0 0 3 then "Possible" else "Impossible"
)

Score : 200 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

We have a grid of H rows and W columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).

You are given a matrix of characters a_{ij} (1 \leq i \leq H, 1 \leq j \leq W). After Shik completes all moving actions, a_{ij} is # if the stone had ever located at the i-th row and the j-th column during the process of moving. Otherwise, a_{ij} is .. Please determine whether it is possible that Shik only uses right and down moves in all steps.

Constraints

2 \leq H, W \leq 8

a_{i,j} is either # or ..

There exists a valid sequence of moves for Shik to generate the map a.

Input

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

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

Output

If it is possible that Shik only uses right and down moves, print Possible. Otherwise, print Impossible.

Sample Input 1

4 5
##...
.##..
..##.
...##

Sample Output 1

Possible

The matrix can be generated by a 7-move sequence: right, down, right, down, right, down, and right.

Sample Input 2

5 3
###
..#
###
#..
###

Sample Output 2

Impossible

Sample Input 3

4 5
##...
.###.
.###.
...##

Sample Output 3

Impossible


open Batteries
let () =
  let a,b,c = Scanf.scanf "%d %d %d " (fun a b c -> a,b,c) in
  let lst = List.sort compare [a;b;c] in
  Printf.printf "%s\n" @@
  if List.nth lst 2 = ((List.nth lst 0) + (List.nth lst 1)) then "Yes" else "No"

Score : 100 points

Problem Statement

Two students of AtCoder Kindergarten are fighting over candy packs.

There are three candy packs, each of which contains a, b, and c candies, respectively.

Teacher Evi is trying to distribute the packs between the two students so that each student gets the same number of candies. Determine whether it is possible.

Note that Evi cannot take candies out of the packs, and the whole contents of each pack must be given to one of the students.

Constraints

1 ≦ a, b, c ≦ 100

Input

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

a b c

Output

If it is possible to distribute the packs so that each student gets the same number of candies, print Yes. Otherwise, print No.

Sample Input 1

10 30 20

Sample Output 1

Yes

Give the pack with 30 candies to one student, and give the two packs with 10 and 20 candies to the other. Then, each gets 30 candies.

Sample Input 2

30 30 100

Sample Output 2

No

In this case, the student who gets the pack with 100 candies always has more candies than the other.

Note that every pack must be given to one of them.

Sample Input 3

56 25 31

Sample Output 3

Yes


let solve l =
  let sl = List.sort compare l in
  match sl with
    a :: b :: c :: _ -> if a + b = c then "Yes" else "No"
  | _ -> ""

let () =
  Printf.printf "%s\n" @@ Scanf.scanf "%d %d %d\n" (fun x y z -> solve [x;y;z])


Scanf.scanf "%d %s %s" (fun n s t ->
    let rec loop dup =
        if dup = 0 then dup else
            let rec loop2 a b =
                if b < 0 then dup else
                    if s.[a] = t.[b] then loop2 (a - 1) (b - 1)
                    else loop (dup - 1)
            in
            loop2 (n - 1) (dup - 1)
    in
    let dup = loop n in
    Printf.printf "%d\n" (n * 2 - dup)
)

Score : 200 points

Problem Statement

Snuke is interested in strings that satisfy the following conditions:

The length of the string is at least N.

The first N characters equal to the string s.

The last N characters equal to the string t.

Find the length of the shortest string that satisfies the conditions.

Constraints

1≤N≤100

The lengths of s and t are both N.

s and t consist of lowercase English letters.

Input

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

N
s
t

Output

Print the length of the shortest string that satisfies the conditions.

Sample Input 1

3
abc
cde

Sample Output 1

5

The shortest string is abcde.

Sample Input 2

1
a
z

Sample Output 2

2

The shortest string is az.

Sample Input 3

4
expr
expr

Sample Output 3

4

The shortest string is expr.


let () =
	let n = read_int () in
	let s = read_line () in
	let t = read_line () in
	let rec loop s t n =
		if n = 0 then 0
		else if Str.last_chars s n = Str.first_chars t n then n
		else loop s t (n - 1)
	in
	loop s t n
	|> ( - ) (n * 2)
	|> print_int
	|> print_newline


let () =
  let s = read_line () in
  print_endline @@
  match
    List.find (fun i -> s.[i] = 'C') @@
      Array.to_list @@
      Array.init (String.length s) @@
      fun i -> i
  with
  | exception Not_found -> "No"
  | i ->
      if
        List.exists (( = ) 'F') @@
          Array.to_list @@
          Array.init (String.length s - i - 1) @@
          fun j -> s.[i + j + 1]
      then "Yes"
      else "No"

Score : 100 points

Problem Statement

This contest is CODEFESTIVAL, which can be shortened to the string CF by deleting some characters.

Mr. Takahashi, full of curiosity, wondered if he could obtain CF from other strings in the same way.

You are given a string s consisting of uppercase English letters.
Determine whether the string CF can be obtained from the string s by deleting some characters.

Constraints

2 ≤ |s| ≤ 100

All characters in s are uppercase English letters (A-Z).

Input

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

s

Output

Print Yes if the string CF can be obtained from the string s by deleting some characters.
Otherwise print No.

Sample Input 1

CODEFESTIVAL

Sample Output 1

Yes

CF is obtained by deleting characters other than the first character C and the fifth character F.

Sample Input 2

FESTIVALCODE

Sample Output 2

No

FC can be obtained but CF cannot be obtained because you cannot change the order of the characters.

Sample Input 3

CF

Sample Output 3

Yes

It is also possible not to delete any characters.

Sample Input 4

FCF

Sample Output 4

Yes

CF is obtained by deleting the first character.


let k, t = Scanf.scanf " %d %d" @@ fun a b -> a, b
let a_s = Array.init t @@ fun _ -> Scanf.scanf " %d" (+) 0
let m, s = Array.(fold_left max a_s.(0) a_s, fold_left (+) 0 a_s)
let _ = Printf.printf "%d\n" @@ max 0 @@ 2 * m - s - 1

Score : 200 points

Problem Statement

There are K pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

1 ≤ K ≤ 10000

1 ≤ T ≤ 100

1 ≤ a_i ≤ 100

a_1 + a_2 + ... + a_T = K

Input

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

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of 2, 1, 2, 3, 1, 3, 1, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are 6 cakes.
For example, if Mr. Takahashi eats cakes in the order of 2, 3, 2, 2, 1, 2, he has to eat the same type of cake (i.e., type 2) as the previous day only on the fourth day.
Since this is the minimum number, the answer is 1.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.


let () = Scanf.scanf "%d %d %d" @@ fun a b c ->
  List.sort_uniq compare [a; b; c]
  |> List.length
  |> Printf.printf "%d\n"

Score : 100 points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c.
Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

1≦a,b,c≦100

Input

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

a b c

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: 1, 3, and 4.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: 3 and 33.


let () =
  let a,b,c = Scanf.scanf "%d %d %d " (fun a b c -> a,b,c) in
  Printf.printf "%d\n"
  ([a;b;c] |> List.sort_uniq compare |> List.length)


let rec p a n = if n <= 0 then 1 else a * p a (n-1)
let () = Scanf.scanf "%d %d" (fun n k -> k * p (k-1) (n-1)) |> Printf.printf "%d\n"

Score : 200 points

Problem Statement

There are N balls placed in a row.
AtCoDeer the deer is painting each of these in one of the K colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

1≦N≦1000

2≦K≦1000

The correct answer is at most 2^{31}-1.

Input

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

N K

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by 0 and 1. There are two possible ways: we can either paint the left ball in color 0 and the right ball in color 1, or paint the left in color 1 and the right in color 0.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.


let tas = Array.init (read_int ()) @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a, b
let x, y = Array.fold_left (fun (x, y) (t, a) -> let k = max ((x + t - 1) / t) ((y + a - 1) / a) in k * t, k * a) tas.(0) tas
let _ = Printf.printf "%d\n" @@ x + y

Score : 300 points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report N times, and when he checked it for the i-th (1≦i≦N) time, the ratio was T_i:A_i.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the N-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

1≦N≦1000

1≦T_i,A_i≦1000 (1≦i≦N)

T_i and A_i (1≦i≦N) are coprime.

It is guaranteed that the correct answer is at most 10^{18}.

Input

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

N
T_1 A_1
T_2 A_2
:
T_N A_N

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the N-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as 2,3 → 3,3 → 6,4, the total number of votes at the end is 10, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930


open Batteries

let solve (a, b) (x, y) =
  let ratio = max ((a-1) / x+1) ((b-1) / y+1) in
  (x*ratio, y*ratio)

let () =
  IO.lines_of stdin
  |> Enum.skip 1
  |> Enum.map (fun l -> Scanf.sscanf l "%d %d" (fun x y -> (x, y)))
  |> Enum.fold solve (1, 1)
  |> fun (x, y) -> Int.print stdout (x + y)


let list_of_str s = let rec f i = if i >= String.length s then [] else s.[i] :: f (i+1) in f 0
let f v c = if c = 'g' then v+1 else v-1
let () =
  let r = Scanf.scanf "%s" list_of_str |> List.fold_left f 0 in
  Printf.printf "%d\n" (r/2)

Score : 300 points

Problem Statement

AtCoDeer the deer and his friend TopCoDeer is playing a game.
The game consists of N turns.
In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:

(※) After each turn, (the number of times the player has played Paper)≦(the number of times the player has played Rock).

Each player's score is calculated by (the number of turns where the player wins) - (the number of turns where the player loses), where the outcome of each turn is determined by the rules of Rock-paper-scissors.

(For those who are not familiar with Rock-paper-scissors: If one player plays Rock and the other plays Paper, the latter player will win and the former player will lose. If both players play the same gesture, the round is a tie and neither player will win nor lose.)

With his supernatural power, AtCoDeer was able to foresee the gesture that TopCoDeer will play in each of the N turns, before the game starts.
Plan AtCoDeer's gesture in each turn to maximize AtCoDeer's score.

The gesture that TopCoDeer will play in each turn is given by a string s. If the i-th (1≦i≦N) character in s is g, TopCoDeer will play Rock in the i-th turn. Similarly, if the i-th (1≦i≦N) character of s in p, TopCoDeer will play Paper in the i-th turn.

Constraints

1≦N≦10^5

N=|s|

Each character in s is g or p.

The gestures represented by s satisfy the condition (※).

Input

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

s

Output

Print the AtCoDeer's maximum possible score.

Sample Input 1

gpg

Sample Output 1

0

Playing the same gesture as the opponent in each turn results in the score of 0, which is the maximum possible score.

Sample Input 2

ggppgggpgg

Sample Output 2

2

For example, consider playing gestures in the following order: Rock, Paper, Rock, Paper, Rock, Rock, Paper, Paper, Rock, Paper. This strategy earns three victories and suffers one defeat, resulting in the score of 2, which is the maximum possible score.


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

    let rec loop i t a =
        if i = n then Printf.printf "%d\n" (t + a) else
            let t1, a1 = ta.(i) in

            let t2 = (t + t1 - 1) / t1 * t1 in
            let a2 = t2 / t1 * a1 in

            let a3 = (a + a1 - 1) / a1 * a1 in
            let t3 = a3 / a1 * t1 in

            if t2 >= t && a2 >= a then (
                if t3 >= t && a3 >= a then (
                    if t2 < t3 then loop (i + 1) t2 a2
                               else loop (i + 1) t3 a3
                ) else loop (i + 1) t2 a2
            ) else loop (i + 1) t3 a3
    in
    loop 1 (fst ta.(0)) (snd ta.(0))
)


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

Score : 100 points

Problem Statement

CODE FESTIVAL 2016 is going to be held. For the occasion, Mr. Takahashi decided to make a signboard.

He intended to write CODEFESTIVAL2016 on it, but he mistakenly wrote a different string S. Fortunately, the string he wrote was the correct length.

So Mr. Takahashi decided to perform an operation that replaces a certain character with another in the minimum number of iterations, changing the string to CODEFESTIVAL2016.

Find the minimum number of iterations for the rewrite operation.

Constraints

S is 16 characters long.

S consists of uppercase and lowercase alphabet letters and numerals.

Input

Inputs are provided from Standard Input in the following form.

S

Output

Output an integer representing the minimum number of iterations needed for the rewrite operation.

Sample Input 1

C0DEFESTIVAL2O16

Sample Output 1

2

The second character 0 must be changed to O and the 14th character O changed to 0.

Sample Input 2

FESTIVAL2016CODE

Sample Output 2

16


module String = struct
  include String
  let to_list s =
    let rec loop acc = function
      | 0 -> acc
      | n -> loop (s.[n - 1] :: acc) (n - 1) in
    loop [] (String.length s)
end

let () =
  read_line ()
  |> String.to_list
  |> List.map2 ( <> ) (String.to_list "CODEFESTIVAL2016")
  |> List.filter (fun x -> x)
  |> List.length
  |> Printf.printf "%d\n"


Scanf.scanf "%d %d %d %s" (fun n a b s ->
    let rec loop i pass passb =
        if i = n then () else
        if pass < a + b && s.[i] <> 'c' then (
            if s.[i] = 'a' then (print_endline "Yes"; loop (i + 1) (pass + 1) passb) else
                if passb < b then (print_endline "Yes"; loop (i + 1) (pass + 1) (passb + 1))
                else (print_endline "No"; loop (i + 1) pass passb)
        ) else (print_endline "No"; loop (i + 1) pass passb)
    in
    loop 0 0 0
)

Score : 200 points

Problem Statement

There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than A+B and the student ranks B-th or above among all overseas students.

A string S is assigned indicating attributes of all participants. If the i-th character of string S is a, this means the participant ranked i-th in the Qualification contests is a Japanese student; b means the participant ranked i-th is an overseas student; and c means the participant ranked i-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

1≦N,A,B≦100000

A+B≦N

S is N characters long.

S consists only of the letters a, b and c.

Input

Inputs are provided from Standard Input in the following form.

N A B
S

Output

Output N lines. On the i-th line, output Yes if the i-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

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

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No


let n, a, b, s = Scanf.scanf " %d %d %d %s" @@ fun a b c d -> a, b, c, d
let p, r = ref 0, ref 0
let _ = String.iter (fun c -> print_endline @@ if !p < a + b then if c = 'a' then (incr p; "Yes") else if c = 'b' then (incr r; if !r <= b then (incr p; "Yes") else "No") else "No" else "No") s


let () = Scanf.scanf "%d %d\n" @@ fun w h ->
  begin
    Array.to_list (Array.init w (fun _ ->
      Scanf.scanf "%d\n" (fun p -> (p, 2)))) @
    Array.to_list (Array.init h (fun _ ->
      Scanf.scanf "%d\n" (fun q -> (q, 1))))
  end
  |> List.sort (fun (p, _) (q, _) -> compare p q)
  |> List.fold_left (fun (cost, (a, b)) -> function
    | (p, 2) ->
        (* p_i は，∀j. (i, j)と(i + 1, j)を結ぶコスト *)
        (cost + p * b, (a - 1, b))
    | (q, 1) ->
        (* q_j は，∀i. (i, j)と(i, j + 1)を結ぶコスト *)
        (cost + q * a, (a, b - 1))) (0, (w + 1, h + 1))
  |> fst
  |> Printf.printf "%d\n"

Score : 500 points

Problem Statement

On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers.

There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and the difference between the x coordinates is 1.

The cost of paving a road between houses on coordinates (i,j) and (i+1,j) is p_i for any value of j, while the cost of paving a road between houses on coordinates (i,j) and (i,j+1) is q_j for any value of i.

Mr. Takahashi wants to pave some of these roads and be able to travel between any two houses on paved roads only. Find the solution with the minimum total cost.

Constraints

1 ≦ W,H ≦ 10^5

1 ≦ p_i ≦ 10^8(0 ≦ i ≦ W-1)

1 ≦ q_j ≦ 10^8(0 ≦ j ≦ H-1)

p_i (0 ≦ i ≦ W−1) is an integer.

q_j (0 ≦ j ≦ H−1) is an integer.

Input

Inputs are provided from Standard Input in the following form.

W H
p_0
:
p_{W-1}
q_0
:
q_{H-1}

Output

Output an integer representing the minimum total cost.

Sample Input 1

2 2
3
5
2
7

Sample Output 1

29

It is enough to pave the following eight roads.

Road connecting houses at (0,0) and (0,1)

Road connecting houses at (0,1) and (1,1)

Road connecting houses at (0,2) and (1,2)

Road connecting houses at (1,0) and (1,1)

Road connecting houses at (1,0) and (2,0)

Road connecting houses at (1,1) and (1,2)

Road connecting houses at (1,2) and (2,2)

Road connecting houses at (2,0) and (2,1)

Sample Input 2

4 3
2
4
8
1
2
9
3

Sample Output 2

60


let () =
  let x = read_line () in
  Array.init (String.length x) (fun i -> x.[i])
  |> Array.fold_left (fun (h, m) -> function
    | 'S' -> (h + 1, m)
    | 'T' -> (h - 1, min m (h - 1))) (0, 0)
  |> (fun (h, m) ->
      let offset = min 0 m in
      let correct = h - offset in
      Printf.printf "%d\n" @@ correct - offset)

Score : 300 points

Problem Statement

We have a string X, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation 10^{10000} times:

Among the occurrences of ST in X as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of X.

Constraints

2 ≦ |X| ≦ 200,000

The length of X is even.

Half the characters in X are S, and the other half are T.

Partial Scores

In test cases worth 200 points, |X| ≦ 200.

Input

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

X

Output

Print the eventual length of X.

Sample Input 1

TSTTSS

Sample Output 1

4

In the 1-st operation, the 2-nd and 3-rd characters of TSTTSS are removed.
X becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining 10^{10000}-1 operations.
Thus, the answer is 4.

Sample Input 2

SSTTST

Sample Output 2

0

X will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

X will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.


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

let () =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let as_ = Array.init n @@ fun i -> Scanf.scanf "%d " @@ fun a -> i, a in
  Array.to_list as_
    |> List.sort (fun (_, a) (_, a') -> compare a a')
    |> List.fold_left (fun (acc, s) (j, a) ->
        let (lt, _, gt) = IntSet.split j s in
        let i = try IntSet.max_elt lt with Not_found -> -1 in
        let k = try IntSet.min_elt gt with Not_found -> n in
        (acc + (k - j) * (j - i) * a, IntSet.add j s)) (0, IntSet.empty)
    |> fst
    |> Printf.printf "%d\n"

Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

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

N
a_1 a_2 ... a_N

Output

Print the answer.

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

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85


let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let d = Array.fold_left max min_int as_ in
  let count_as = Array.make n 0 in
  Array.iter (fun a -> count_as.(a) <- 1 + count_as.(a)) as_;
  print_endline @@
  if
    Array.fold_right (fun n -> ( && ) (n = 0))
      (Array.sub count_as 0 ((d + 1) / 2)) true &&
    count_as.((d + 1) / 2) = 1 + d mod 2 &&
    Array.fold_right (fun n -> ( && ) (1 < n))
      (Array.sub count_as ((d + 1) / 2 + 1) (d / 2)) true
  then "Possible"
  else "Impossible"

Score : 700 points

Problem Statement

Aoki loves numerical sequences and trees.

One day, Takahashi gave him an integer sequence of length N, a_1, a_2, ..., a_N, which made him want to construct a tree.

Aoki wants to construct a tree with N vertices numbered 1 through N, such that for each i = 1,2,...,N, the distance between vertex i and the farthest vertex from it is a_i, assuming that the length of each edge is 1.

Determine whether such a tree exists.

Constraints

2 ≦ N ≦ 100

1 ≦ a_i ≦ N-1

Input

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

N
a_1 a_2 ... a_N

Output

If there exists a tree that satisfies the condition, print Possible. Otherwise, print Impossible.

Sample Input 1

5
3 2 2 3 3

Sample Output 1

Possible

The diagram above shows an example of a tree that satisfies the conditions. The red arrows show paths from each vertex to the farthest vertex from it.

Sample Input 2

3
1 1 2

Sample Output 2

Impossible

Sample Input 3

10
1 2 2 2 2 2 2 2 2 2

Sample Output 3

Possible

Sample Input 4

10
1 1 2 2 2 2 2 2 2 2

Sample Output 4

Impossible

Sample Input 5

6
1 1 1 1 1 5

Sample Output 5

Impossible

Sample Input 6

5
4 3 2 3 4

Sample Output 6

Possible


let () =
  let s = read_line () in
  Printf.printf "%s %s\n" (String.sub s 0 4) (String.sub s 4 8)

Score : 100 points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string s with 12 letters.
Output the string putting a single space between the first 4 letters and last 8 letters in the string s.

Constraints

s contains exactly 12 letters.

All letters in s are uppercase English letters.

Input

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

s

Output

Print the string putting a single space between the first 4 letters and last 8 letters in the string s.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first 4 letters and last 8 letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL


let n = Scanf.scanf " %d" (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" pred
let c = ref 0
let _ = for i = 0 to n - 1 do if a_s.(a_s.(i)) = i then incr c done; Printf.printf "%d\n" @@ !c / 2

Score : 200 points

Problem Statement

There are N rabbits, numbered 1 through N.

The i-th (1≤i≤N) rabbit likes rabbit a_i.
Note that no rabbit can like itself, that is, a_i≠i.

For a pair of rabbits i and j (i＜j), we call the pair (i，j) a friendly pair if the following condition is met.

Rabbit i likes rabbit j and rabbit j likes rabbit i.

Calculate the number of the friendly pairs.

Constraints

2≤N≤10^5

1≤a_i≤N

a_i≠i

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 friendly pairs.

Sample Input 1

4
2 1 4 3

Sample Output 1

2

There are two friendly pairs: (1，2) and (3，4).

Sample Input 2

3
2 3 1

Sample Output 2

0

There are no friendly pairs.

Sample Input 3

5
5 5 5 5 1

Sample Output 3

1

There is one friendly pair: (1，5).


let a = read_int ()
let b = read_int ()
let h = read_int ()
let _ = Printf.printf "%d\n" ((a+b)*h/2)

Score : 100 points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

1≦a≦100

1≦b≦100

1≦h≦100

All input values are integers.

h is even.

Input

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

a
b
h

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are 3, 4, and 2, respectively, the area of the trapezoid is (3+4)×2/2 = 7.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.


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


(* O(2^|s|) *)
let s = read_line ()
let ds = Array.to_list @@ Array.init (String.length s) @@ fun i -> Char.code s.[i] - 48
let rec f sum n = function
| [] -> sum + n
| d :: r -> f (sum + n) d r + f sum (10 * n + d) r
let _ = f 0 (List.hd ds) (List.tl ds) |> Printf.printf "%d\n"

Score : 300 points

Problem Statement

You are given a string S consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

1 \leq |S| \leq 10

All letters in S are digits between 1 and 9, inclusive.

Input

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

S

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are 4 formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

125

1+25=26

12+5=17

1+2+5=8

Thus, the sum is 125+26+17+8=176.

Sample Input 2

9999999999

Sample Output 2

12656242944


Scanf.scanf "%d %d %d" (fun h w n ->
    let f a b = a lsl 30 + b in
    let module M = Map.Make (struct type t = int let compare = compare end) in

    let hist = Array.make 10 0 in
    hist.(0) <- (h - 2) * (w - 2);

    let rec loop i map =
        if i = n then hist else
            let map = Scanf.scanf " %d %d" (fun a b ->
                List.fold_left (fun map (vx, vy) ->
                    let x = b + vx in
                    let y = a + vy in
                    if x > 1 && x < w && y > 1 && y < h then (
                        let key = f x y in
                        let v = try M.find key map with _ -> 0 in
                        hist.(v) <- hist.(v) - 1;
                        hist.(v + 1) <- hist.(v + 1) + 1;
                        M.add key (v + 1) map
                    ) else map
                ) map [ -1, -1; -1, 0; -1, 1; 0, -1; 0, 0; 0, 1; 1, -1; 1, 0; 1, 1 ]
            ) in
            loop (i + 1) map
    in
    Array.iter (Printf.printf "%d\n") @@ loop 0 M.empty
)

Score : 400 points

Problem Statement

We have a grid with H rows and W columns. At first, all cells were painted white.

Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.

Compute the following:

For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the grid contains exactly j black cells, after Snuke painted N cells?

Constraints

3 \leq H \leq 10^9

3 \leq W \leq 10^9

0 \leq N \leq min(10^5,H×W)

1 \leq a_i \leq H (1 \leq i \leq N)

1 \leq b_i \leq W (1 \leq i \leq N)

(a_i, b_i) \neq (a_j, b_j) (i \neq j)

Input

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

H W N
a_1 b_1
:
a_N b_N

Output

Print 10 lines.
The (j+1)-th ( 0 \leq j \leq 9 ) line should contain the number of the subrectangles of size 3×3 of the grid that contains exactly j black cells.

Sample Input 1

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

Sample Output 1

0
0
0
2
4
0
0
0
0
0

There are six subrectangles of size 3×3. Two of them contain three black cells each, and the remaining four contain four black cells each.

Sample Input 2

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

Sample Output 2

4
26
22
10
2
0
0
0
0
0

Sample Input 3

1000000000 1000000000 0

Sample Output 3

999999996000000004
0
0
0
0
0
0
0
0
0


let is_even n = (n mod 2 = 0)

let () =
	Scanf.scanf "%d %d %d\n" (fun a b c ->
		if List.exists is_even [a; b; c] then
			Printf.printf "0\n"
		else
			List.sort compare [a * b; b * c; c * a]
			|> List.hd
			|> Printf.printf "%d\n"
	)

Score : 200 points

Problem Statement

We have a rectangular parallelepiped of size A×B×C, built with blocks of size 1×1×1. Snuke will paint each of the A×B×C blocks either red or blue, so that:

There is at least one red block and at least one blue block.

The union of all red blocks forms a rectangular parallelepiped.

The union of all blue blocks forms a rectangular parallelepiped.

Snuke wants to minimize the difference between the number of red blocks and the number of blue blocks. Find the minimum possible difference.

Constraints

2≤A,B,C≤10^9

Input

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

A B C

Output

Print the minimum possible difference between the number of red blocks and the number of blue blocks.

Sample Input 1

3 3 3

Sample Output 1

9

For example, Snuke can paint the blocks as shown in the diagram below.
There are 9 red blocks and 18 blue blocks, thus the difference is 9.

Sample Input 2

2 2 4

Sample Output 2

0

For example, Snuke can paint the blocks as shown in the diagram below.
There are 8 red blocks and 8 blue blocks, thus the difference is 0.

Sample Input 3

5 3 5

Sample Output 3

15

For example, Snuke can paint the blocks as shown in the diagram below.
There are 45 red blocks and 30 blue blocks, thus the difference is 9.


let () =
	let n, k, x, y = Scanf.scanf "%d\n%d\n%d\n%d\n" (fun a b c d -> a,b,c,d) in
    Printf.printf "%d\n" ((if n<=k then 0 else (n-k)*y) + n*x)

Score : 100 points

Problem Statement

There is a hotel with the following accommodation fee:

X yen (the currency of Japan) per night, for the first K nights

Y yen per night, for the (K+1)-th and subsequent nights

Tak is staying at this hotel for N consecutive nights.
Find his total accommodation fee.

Constraints

1 \leq N, K \leq 10000

1 \leq Y < X \leq 10000

N,\,K,\,X,\,Y are integers.

Input

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

N
K
X
Y

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

10000 yen for the 1-st night

10000 yen for the 2-nd night

10000 yen for the 3-rd night

9000 yen for the 4-th night

9000 yen for the 5-th night

Thus, the total is 48000 yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000


let n, k, x, y = Scanf.scanf " %d %d %d %d" @@ fun a b c d -> a, b, c, d
let _ = Printf.printf "%d\n" @@ x * min n k + y * max 0 (n - k)


let w = read_line ()
let f s x = let n = ref 0 in String.iter (fun c -> if c = x then incr n) s; !n
let _ = String.iter (fun c -> if f w c mod 2 = 1 then (print_endline "No"; exit 0)) w; print_endline "Yes"

Score : 200 points

Problem Statement

Let w be a string consisting of lowercase letters.
We will call w beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in w.

You are given the string w. Determine if w is beautiful.

Constraints

1 \leq |w| \leq 100

w consists of lowercase letters (a-z).

Input

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

w

Output

Print Yes if w is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No


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

let dp = Array.make 26 0

let calc c =
  let ind = (int_of_char 'a') - 97 in
  dp.(ind) <- dp.(ind) + 1

let flag = ref true
let cl =
  read_line ()
  |> charl_of_string
  |> List.map calc

let () =
  for i = 0 to 25 do
    if dp.(i) mod 2 = 1 then flag := false
  done;
  if !flag then print_endline "Yes"
  else print_endline "No"


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 print_int_endline n = n |> string_of_int |> print_endline

module Int64 = struct
	include Int64
	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 (<|) p q =
		if Int64.compare p q < 0 then true
		else false
	let (>|) p q =
		if Int64.compare p q > 0 then true
		else false
	let (>=|) p q = not (p < q)
	let (<=|) p q = not (p > q)
	let labs p = if p <| 0L then -1L*|p else p
	let (~|) p = Int64.of_int p
end
open Int64

let () =
  let n,a = get_2_ints ()
  in let xl = input_int_array n |> Array.to_list
  in
  let rec f0 ls s c =
    let k = if c>0 && s = c*a then 1L else 0L in
    (* printf "%2d %2d -- %2Ld\n" s c k; *)
    match ls with
    | [] -> k
    | h::t -> (
      if c>0 && s=c*a then
        f0 t h 1 +| f0 t 0 0 +| 1L
      else
        f0 t (h+s) (c+1) +| f0 t s c
    )
  in f0 xl 0 0 |> printf "%Ld\n"

Score : 300 points

Problem Statement

Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i.
He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A.
In how many ways can he make his selection?

Constraints

1 \leq N \leq 50

1 \leq A \leq 50

1 \leq x_i \leq 50

N,\,A,\,x_i are integers.

Partial Score

200 points will be awarded for passing the test set satisfying 1 \leq N \leq 16.

Input

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

N A
x_1 x_2 ... x_N

Output

Print the number of ways to select cards such that the average of the written integers is exactly A.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the 5 ways to select cards such that the average is 8:

Select the 3-rd card.

Select the 1-st and 2-nd cards.

Select the 1-st and 4-th cards.

Select the 1-st, 2-nd and 3-rd cards.

Select the 1-st, 3-rd and 4-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a 32-bit integer.


Scanf.scanf "%d %d" (fun n aa ->
    let x = Array.init n (fun _ -> Scanf.scanf " %d" (fun x -> x - aa)) in
    let rec loop i a b c =
        if i = n then a, b, c else
        if x.(i) < 0 then loop (i + 1) (-x.(i) :: a) b c else
        if x.(i) > 0 then loop (i + 1) a b (x.(i) :: c) else
                          loop (i + 1) a (b * 2) c
    in
    let a, b, c = loop 0 [] 1 [] in
    let build l =
        let arr = Array.make 2501 0 in
        arr.(0) <- 1;
        let rec loop = function
            | [] -> arr
            | hd :: tl ->
                for j = 2500 - hd downto 0 do
                    arr.(hd + j) <- arr.(hd + j) + arr.(j)
                done;
                loop tl
        in
        loop l
    in
    let mi = build a in
    let pl = build c in
    let rec loop i acc =
        if i = 2501 then acc else
            loop (i + 1) (acc + mi.(i) * pl.(i) * b)
    in
    loop 0 (-1) |> Printf.printf "%d\n"
)


let rec f acc b = function
  | 0 -> acc
  | n -> f (n mod b + acc) b (n / b)
let f = f 0

let () = Scanf.scanf "%d %d" @@ fun n s ->
  let r = int_of_float @@ sqrt @@ float_of_int n in
  if n < s
  then print_endline "-1"
  else if n = s
  then Printf.printf "%d\n" (n + 1)
  else
    try
      Array.init r (( + ) 2)
      |> Array.to_list
      |> List.find (fun b -> f b n = s)
      |> Printf.printf "%d\n"
    with Not_found ->
      try
        Array.init ((n - s) / (r - 1)) (( + ) 1)
        |> Array.to_list
        |> List.rev_map (fun p -> (n - s) / p + 1)
        |> List.filter (( <= ) 2)
        |> List.find (fun b -> f b n = s)
        |> Printf.printf "%d\n"
      with _ -> print_endline "-1"

Score : 500 points

Problem Statement

For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:

f(b,n) = n, when n < b

f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b

Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b,
and n \ {\rm mod} \ b denotes the remainder of n divided by b.

Less formally, f(b,n) is equal to the sum of the digits of n written in base b.
For example, the following hold:

f(10,\,87654)=8+7+6+5+4=30

f(100,\,87654)=8+76+54=138

You are given integers n and s.
Determine if there exists an integer b (b \geq 2) such that f(b,n)=s.
If the answer is positive, also find the smallest such b.

Constraints

1 \leq n \leq 10^{11}

1 \leq s \leq 10^{11}

n,\,s are integers.

Input

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

n
s

Output

If there exists an integer b (b \geq 2) such that f(b,n)=s, print the smallest such b.
If such b does not exist, print -1 instead.

Sample Input 1

87654
30

Sample Output 1

10

Sample Input 2

87654
138

Sample Output 2

100

Sample Input 3

87654
45678

Sample Output 3

-1

Sample Input 4

31415926535
1

Sample Output 4

31415926535

Sample Input 5

1
31415926535

Sample Output 5

-1


let s = read_line ()
let f c = if String.contains s c then 1 else 0
let _ = print_endline @@ if abs (f 'N' - f 'S') + abs (f 'E' - f 'W') = 0 then "Yes" else "No"

Score : 200 points

Problem Statement

Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip.
At the beginning of Day 1, he is at home. His plan is described in a string S of length N.
On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction:

North if the i-th letter of S is N

West if the i-th letter of S is W

South if the i-th letter of S is S

East if the i-th letter of S is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day N.

Constraints

1 ≦ | S | ≦ 1000

S consists of the letters N, W, S, E.

Input

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

S

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day N. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of 1 on each day, he will be back at home at the end of day 4.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No


let encode = function
  |'N' -> 0x1
  |'S' -> 0x2
  |'E' -> 0x4
  |'W' -> 0x8
  | _ -> 0

let s = read_line ()

let rec solve acc i = if i = String.length s then acc else solve (acc lor encode s.[i]) (i+1)

let () = let r = solve 0 0 in
  let a = (r lxor (r lsr 1)) land 0x5 in
    print_string (if a = 0 then "Yes" else "No")


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

    let rec loop i carry acc =
        if i = n then acc else
            if a.(i) = 0 then loop (i + 1) 0 acc else
                let t = (carry + a.(i)) / 2 in
                let carry = (carry + a.(i)) mod 2 in
                loop (i + 1) carry (acc + t)
    in
    loop 0 0 0 |> Printf.printf "%d\n"
)

Score : 400 points

Problem Statement

Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it.
He has A_i cards with an integer i.

Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1.

Snuke wants to create the maximum number of pairs from his cards, on the condition that no card should be used in multiple pairs. Find the maximum number of pairs that he can create.

Constraints

1 ≦ N ≦ 10^5

0 ≦ A_i ≦ 10^9 (1 ≦ i ≦ N)

All input values are integers.

Input

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

N
A_1
:
A_N

Output

Print the maximum number of pairs that Snuke can create.

Sample Input 1

4
4
0
3
2

Sample Output 1

4

For example, Snuke can create the following four pairs: (1,1),(1,1),(3,4),(3,4).

Sample Input 2

8
2
0
1
6
0
8
2
1

Sample Output 2

9


let array_of_string s = Array.init (String.length s) (fun i -> s.[i])

let () =
  try
    read_line ()
    |> array_of_string
    |> (fun a ->
        Array.to_list (Array.init (Array.length a - 1) (fun i -> ((i + 1, i + 2), a.(i) = a.(i + 1)))) @
        Array.to_list (Array.init (Array.length a - 2) (fun i -> ((i + 1, i + 3), a.(i) = a.(i + 2)))))
    |> List.find (fun (_, b) -> b)
    |> (fun ((i, j), _) -> Printf.printf "%d %d\n" i j)
  with Not_found -> print_endline "-1 -1"

Score : 400 points

Problem Statement

Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both voodoo and melee are unbalanced, while neither noon nor a is.

You are given a string s consisting of lowercase letters. Determine if there exists a (contiguous) substring of s that is unbalanced. If the answer is positive, show a position where such a substring occurs in s.

Constraints

2 ≦ |s| ≦ 10^5

s consists of lowercase letters.

Partial Score

200 points will be awarded for passing the test set satisfying 2 ≦ N ≦ 100.

Input

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

s

Output

If there exists no unbalanced substring of s, print -1 -1.

If there exists an unbalanced substring of s, let one such substring be s_a s_{a+1} ... s_{b} (1 ≦ a < b ≦ |s|), and print a b. If there exists more than one such substring, any of them will be accepted.

Sample Input 1

needed

Sample Output 1

2 5

The string s_2 s_3 s_4 s_5 = eede is unbalanced. There are also other unbalanced substrings. For example, the output 2 6 will also be accepted.

Sample Input 2

atcoder

Sample Output 2

-1 -1

The string atcoder contains no unbalanced substring.


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

Score : 100 points

Problem Statement

There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?

Constraints

1≦N≦100

Input

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

N

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is 1+2+3=6.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from 1 to 10 is 55.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is 1 in this case.


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

  let rec aux n res =
    if n = 0 then res else
      aux (n-1) (res+n)
  in

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


let solve n =
  n * (n+1) / 2

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


let rec upper_bound l r p =
  if r <= 1 + l
  then l
  else let m = (l + r) / 2 in
       if p m
       then upper_bound m r p
       else upper_bound l m p

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ ->
    Scanf.scanf "%d " @@ fun a -> a in
  let cost x =
    Array.fold_left ( + ) 0 @@
    Array.map (fun y -> (x - y) * (x - y)) as_ in
  Printf.printf "%d\n" @@ cost @@ upper_bound (-100) 100 @@ fun i ->
    cost i - cost (i - 1) <= 0

Score : 200 points

Problem Statement

Evi has N integers a_1,a_2,..,a_N. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x-y)^2 dollars. Even if a_i=a_j (i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100

-100≦a_i≦100

Input

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

N
a_1 a_2 ... a_N

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into 6s will cost (4-6)^2+(8-6)^2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into 2s will cost (1-2)^2+(1-2)^2+(3-2)^2=3 dollars. Note that Evi has to pay (1-2)^2 dollar separately for transforming each of the two 1s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2-4)^2+(5-4)^2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.


let cost_to_n list n =
  List.fold_left (fun x y -> x + y) 0 (List.map (fun x -> (n-x)*(n-x)) list)

let solve list =
  let rec aux list min_cost cto cfrom cnow =
    if cnow = cto then min_cost else
      let cur_cost = cost_to_n list cnow in
      aux list (min min_cost cur_cost) cto cfrom (cnow+1)
  in
  aux list max_int
      (List.fold_left (fun x y -> max x y) min_int list)
      (List.fold_left (fun x y -> min x y) max_int list)
      (List.fold_left (fun x y -> min x y) max_int list)

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

let () =
  let _ = read_int() in
  let list = read_list_of_int () in
  let ans = solve list in
  Printf.printf "%d\n" ans
;;


Scanf.scanf "%d %d" (fun n m ->
    let balls = Array.make n 1 in
    let red   = Array.make n false in
    red.(0) <- true;
    for i = 1 to m do
        Scanf.scanf " %d %d" (fun x y ->
            let x = x - 1 in let y = y - 1 in
            if red.(x) then (
                if balls.(x) = 1 then red.(x) <- false;
                red.(y) <- true
            );
            balls.(x) <- balls.(x) - 1;
            balls.(y) <- balls.(y) + 1;
        )
    done;
    Array.fold_left (fun acc v -> if v then acc + 1 else acc) 0 red |> Printf.printf "%d\n"
)

Problem Statement

We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

2≤N≤10^5

1≤M≤10^5

1≤x_i,y_i≤N

x_i≠y_i

Just before the i-th operation is performed, box x_i contains at least 1 ball.

Input

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

N M
x_1 y_1
:
x_M y_M

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box 1 is empty, box 2 contains one red ball and one white ball, and box 3 contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box 2, the red ball will go into box 3. If he picks the white ball instead, the red ball will stay in box 2.
Thus, the number of boxes that may contain the red ball after all operations, is 2.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box 3.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3


let n, m = Scanf.scanf "%d %d " (fun x y -> x, y)

let rec rev_read_ints accu = function
  | 0 -> accu
  | k -> rev_read_ints ((Scanf.scanf "%d %d\n" (fun x y -> x-1, y-1)) :: accu) (k-1)

let xy = List.rev (rev_read_ints [] m)

let possible = Array.make n false
let () = possible.(0) <- true

let numbers = Array.make n 1

let rec solve = function
  | [] -> ()
  | (x, y) :: tl -> if possible.(x) then begin possible.(y) <- true; if numbers.(x) = 1 then possible.(x) <- false end;
    numbers.(x) <- numbers.(x) - 1; numbers.(y) <- numbers.(y) + 1; solve tl

let () = solve xy; print_int (Array.fold_left (fun x y -> x + (if y then 1 else 0)) 0 possible)


let n, l = Scanf.scanf "%d %d\n" (fun x y -> x, y)

let rec read_ints acc = function
  | 0 -> List.rev acc
  | k -> read_ints (Scanf.scanf "%d " (fun x -> x) :: acc) (k-1)

let al = read_ints [] n

let rec solve i k = function
  | [] | _ :: [] -> Some ([], [])
  | hd0 :: ((hd1 :: tl1) as tl0) -> if k < l then None else
    if hd0 + hd1 >= l then
      match solve (i+1) k (hd0 + hd1 :: tl1) with
        | None -> None
        | Some (x, y) -> Some (x, (i :: y))
    else
      match solve (i+1) (k-hd0) tl0 with
        | None -> None
        | Some (x, y) -> Some ((i :: x), y)

let sum = List.fold_left (+) 0 al

let () =
  match solve 1 sum al with
  | None -> print_endline "Impossible"
  | Some (x, y) -> print_endline "Possible"; let p = List.iter (fun x -> print_int x; print_newline ()) in p x; p (List.rev y)

Problem Statement

We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i.

At first, for each i (1≤i≤N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly:

Choose a (connected) rope with a total length of at least L, then untie one of its knots.

Is it possible to untie all of the N-1 knots by properly applying this operation? If the answer is positive, find one possible order to untie the knots.

Constraints

2≤N≤10^5

1≤L≤10^9

1≤a_i≤10^9

All input values are integers.

Input

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

N L
a_1 a_2 ... a_n

Output

If it is not possible to untie all of the N-1 knots, print Impossible.

If it is possible to untie all of the knots, print Possible, then print another N-1 lines that describe a possible order to untie the knots. The j-th of those N-1 lines should contain the index of the knot that is untied in the j-th operation. Here, the index of the knot connecting piece i and piece i+1 is i.

If there is more than one solution, output any.

Sample Input 1

3 50
30 20 10

Sample Output 1

Possible
2
1

If the knot 1 is untied first, the knot 2 will become impossible to untie.

Sample Input 2

2 21
10 10

Sample Output 2

Impossible

Sample Input 3

5 50
10 20 30 40 50

Sample Output 3

Possible
1
2
3
4

Another example of a possible solution is 3, 4, 1, 2.


let n, l = Scanf.scanf "%d %d\n" (fun x y -> x, y)

let rec read_ints acc = function
  | 0 -> List.rev acc
  | k -> read_ints (Scanf.scanf "%d " (fun x -> x) :: acc) (k-1)

let al = read_ints [] n

let rec solve i k = function
  | [] -> Some []
  | _ :: [] -> Some []
  | hd0 :: ((hd1 :: tl1) as tl0) -> if k < l then None else
    match solve (i+1) (k-hd0) tl0 with
    | Some x -> Some (i :: x)
    | None -> if hd0 + hd1 < l then None else
      match solve (i+1) k (hd0 + hd1 :: tl1) with
      | None -> None
      | Some x -> Some (List.rev (i :: (List.rev x)))

let sum = List.fold_left (+) 0 al

let () =
  match solve 1 sum al with
  | None -> print_endline "Impossible"
  | Some x -> print_endline "Possible"; List.iter (fun x -> print_int x; print_newline ()) x


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

let rec read_ints acc = function
  | 0 ->  acc
  | k -> read_ints (Scanf.scanf " %d" (fun x -> x) :: acc) (k-1)

let al = List.sort (fun x y -> compare y x) (read_ints [] n)

let rec solve i k = function
  | [] -> true
  | hd :: tl -> if hd > i then solve (i+1) (hd - i) tl else k lor (i - hd) mod 2 = 1

let () = print_endline (if solve 1 0 al then "First" else "Second")

Problem Statement

There are N piles of candies on the table. The piles are numbered 1 through N. At first, pile i contains a_i candies.

Snuke and Ciel are playing a game. They take alternating turns. Snuke goes first. In each turn, the current player must perform one of the following two operations:

Choose a pile with the largest number of candies remaining, then eat all candies of that pile.

From each pile with one or more candies remaining, eat one candy.

The player who eats the last candy on the table, loses the game. Determine which player will win if both players play the game optimally.

Constraints

1≤N≤10^5

1≤a_i≤10^9

Input

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

N
a_1 a_2 … a_N

Output

If Snuke will win, print First. If Ciel will win, print Second.

Sample Input 1

2
1 3

Sample Output 1

First

At the beginning of the game, pile 2 contains the most candies. If Snuke eats all candies of this pile, Ciel has no choice but to eat the last candy.

Sample Input 2

3
1 2 1

Sample Output 2

First

If Snuke eats one candy from each pile, Ciel is again left with the last candy.

Sample Input 3

3
1 2 3

Sample Output 3

Second


let modulo = 1000000007

let ( +% ) a b = let c = a + b in if c > modulo then c - modulo else c
let ( -% ) a b = if a >= b then a - b else modulo + a - b
let ( *% ) a b = a * b mod modulo

let pow k =
  let rec aux accu k = function
  | 0 -> accu
  | n when n mod 2 = 0 -> aux accu (k *% k) (n/2)
  | n -> aux (accu *% k) (k *% k) (n/2) in
  aux 1 k

let inv k = pow k (modulo-2)

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

let () = if k = 1 then begin print_int 1; exit 0 end

let smax = n * k
let factbl = Array.make (smax+1) 1
let ifactbl = Array.make (smax+1) 0
let () = for i = 1 to smax do factbl.(i) <- factbl.(i-1) *% i done;
         ifactbl.(smax) <- inv factbl.(smax);
         for i = smax-1 downto 0 do ifactbl.(i) <- ifactbl.(i+1) *% (i+1) done

let binom n k = factbl.(n) *% ifactbl.(k) *% ifactbl.(n-k)

let dp = Array.make (n+1) 0

let () = dp.(0) <- 1;
         for i = 0 to n-1 do for j = i+1 to n do
           dp.(j) <- dp.(j) +% dp.(j-1) *% binom (i+j*(k-1)-1) (k-2) done done;
         print_int (factbl.(n) *% dp.(n))

Problem Statement

Snuke loves colorful balls. He has a total of N×K balls, K in each of his favorite N colors. The colors are numbered 1 through N.

He will arrange all of the balls in a row from left to right, in arbitrary order. Then, for each of the N colors, he will paint the leftmost ball of that color into color 0, a color different from any of the N original colors.

After painting, how many sequences of the colors of the balls are possible? Find this number modulo 10^9+7.

Constraints

1≤N,K≤2,000

Input

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

N K

Output

Print the number of the possible sequences of the colors of the balls after painting, modulo 10^9+7.

Sample Input 1

2 2

Sample Output 1

4

The following 4 sequences are possible:

(0,1,0,2)

(0,0,1,2)

(0,2,0,1)

(0,0,2,1)

Sample Input 2

3 1

Sample Output 2

1

The following 1 sequence is possible:

(0,0,0)

Sample Input 3

2 3

Sample Output 3

14

Sample Input 4

2000 2000

Sample Output 4

546381702


let read_ints =
  let rec aux acc = function
    | 0 -> acc
    | n -> aux ((Scanf.scanf "%d " (fun x -> x)) :: acc) (n-1) in
  aux []

let decimal =
  let rec aux acc = function
    | 0 -> acc
    | n -> aux ((n mod 10)::acc) (n/10) in
  aux []

let pow k =
  let rec aux accu k = function
  | 0 -> accu
  | n when n mod 2 = 0 -> aux accu (k*k) (n/2)
  | n -> aux (accu*k) (k*k) (n/2) in
  aux 1 k

let () =
  let n, k  = Scanf.scanf "%d %d\n" (fun x y -> (x, y)) in
  let l = List.sort compare (read_ints k) in
  let dl = decimal n in
  let rec solver = function
    | [] -> Some 0
    | hd :: tl -> if List.mem hd l then (if hd = 9 then None else (solver ((hd+1):: tl))) else
                  match (solver tl) with
                    | None -> (if hd = 9 then None else (solver ((hd+1):: tl)))
                    | Some x -> Some (hd * (pow 10 (List.length tl)) + x) in
  let rec solve = function
    | [] -> 0
    | hd :: tl -> if List.mem hd l then (if hd = 9 then (solve (1::0::tl)) else (solve ((hd+1):: tl))) else
                  match (solver tl) with
                    | None -> (if hd = 9 then (solve (1::0::tl)) else (solve ((hd+1):: tl)))
                    | Some x -> hd * (pow 10 (List.length tl)) + x in
  print_int (solve dl)

Score : 300 points

Problem Statement

Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.

She is shopping, and now paying at the cashier.
Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

1 ≦ N < 10000

1 ≦ K < 10

0 ≦ D_1 < D_2 < … < D_K≦9

\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}

Input

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

N K
D_1 D_2 … D_K

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except 0 and 2.

The smallest integer equal to or greater than N=1000 whose decimal notation contains only 0 and 2, is 2000.

Sample Input 2

9999 1
0

Sample Output 2

9999


let () =
	let a, b, c = Scanf.scanf "%d %d %d\n" (fun a b c -> a,b,c) in
    Printf.printf
   	(if
    (a=5 && b=5 && c=7) || (a=5 && b=7 && c=5) || (a=7 && b=5 && c=5)
    then "YES" else "NO")

Score : 100 points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with 5, 7 and 5 syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have A, B and C syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

1≦A,B,C≦10

Input

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

A B C

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length 5, 5 and 7, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO


let () = Scanf.scanf "%s" (fun s -> s=="5 7 5")
|> (fun b -> if b then "YES" else "NO")
|> Printf.printf "%s\n"


let contains num num_list =
  let str = string_of_int num
  and chr_list = List.map (fun x -> (string_of_int x).[0]) num_list in
  List.fold_left (fun x y -> x || (String.contains str y)) false chr_list

let unfold f init =
  let rec unfold_inner f init ret =
    match f init with
      Some (a, b) -> unfold_inner f b (a::ret)
    | None        -> ret
  in
  unfold_inner f init []

let make_list from to_ step =
  let accum x =
    if x > to_ then None else Some (x, x + step)
  in
  List.rev @@ unfold accum from

let solve n proh =
  let cand = make_list n (10*n) 1 in
  List.fold_left (fun x y -> if contains x proh then y else x) n cand

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

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


let n, k = Scanf.scanf "%d %d\n" (fun a b -> a, b)
let ds = Array.init k (fun _ -> Scanf.scanf "%c " (fun x -> x))

let rec solve p =
  if (Array.fold_left (fun pre c ->
      pre || String.contains (string_of_int p) c) false ds)
  then solve (p + 1)
  else p

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


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

let rec tabulate n f =
  let rec loop acc m =
    if m < n then loop (f m :: acc) (m + 1)
    else List.rev acc in
  loop [] 0

let rec solve ds = function
  | 0 -> (0, false)
  | n ->
      let m, n = n mod 10, n / 10 in
      if IntSet.mem m ds then
        match solve ds n with
        | (n, false) -> (10 * n + m, false)
        | (n, true) -> (10 * n + IntSet.min_elt ds, true)
      else
        tabulate 10 (fun n -> n)
        |> List.filter (fun n -> IntSet.mem n ds && m < n)
        |> (function
            | [] -> (10 * fst (solve ds (n + 1)) + IntSet.min_elt ds, true)
            | m :: _ ->
                match solve ds n with
                | (n, false) -> (10 * n + m, true)
                | (n, true) -> (10 * n + IntSet.min_elt ds, true))

let () =
  let n, k = Scanf.scanf "%d %d\n" (fun n k -> n, k) in
  let ds =
    IntSet.diff
      (IntSet.of_list (tabulate 10 (fun k -> k)))
      (IntSet.of_list (tabulate k (fun _ -> Scanf.scanf "%d " (fun d -> d)))) in
  Printf.printf "%d\n" (fst (solve ds n))


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

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

let _ =
    let n = Scanf.scanf "%d " (fun n -> 2 * n) in
    let xs = input n [] in
    let xs = List.sort compare xs in
    let l = (List.length xs) - 1 in
    solve xs l 0

Score : 200 points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make N servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks 2 skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be x, then the serving can hold the maximum of x ingredients.

What is the maximum total number of ingredients that his N servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

1≦N≦100

1≦L_i≦100

For each i, L_i is an integer.

Input

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

N
L_1 L_2 ... L_{2N}

Output

Print the maximum total number of ingredients that Snuke's N servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold 1 and 2 ingredients, for the total of 3.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let abs = Array.init (n - 1) @@ fun _ ->
    Scanf.scanf "%d %d\n" @@ fun a b -> a, b in
  let es = Array.make n [] in
  Array.iter (fun (a, b) ->
    es.(a - 1) <- b - 1 :: es.(a - 1);
    es.(b - 1) <- a - 1 :: es.(b - 1)) abs;
  let d = Array.make_matrix n n min_int in
  for s = 0 to n - 1 do
    let rec dfs v =
      List.iter (fun u ->
        if d.(s).(u) < 0 then
          (d.(s).(u) <- 1 + d.(s).(v); dfs u)) es.(v) in
    d.(s).(s) <- 0; dfs s
  done;
  Printf.printf "%d\n" @@ Array.fold_left min max_int @@
  if k mod 2 = 0 then
    Array.init n @@ fun v ->
      Array.fold_left (fun acc u ->
        acc + (if k / 2 < d.(u).(v) then 1 else 0)) 0 @@
      Array.init n @@ fun u -> u
  else
    Array.map (fun (a, b) ->
      Array.fold_left (fun acc u ->
        acc + (if k / 2 < min d.(a - 1).(u) d.(b - 1).(u) then 1 else 0)) 0 @@
      Array.init n @@ fun u -> u) abs

Score : 600 points

Problem Statement

Given an undirected tree, let the distance between vertices u and v be the
number of edges on the simple path from u to v.
The diameter of a tree is the maximum among the distances between any two vertices.
We will call a tree good if and only if its diameter is at most K.

You are given an undirected tree with N vertices numbered 1 through N.
For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i.

You want to remove zero or more vertices from the tree, so that the resulting tree is good.
When a vertex is removed, all incident edges will also be removed.
The resulting graph must be connected.

Find the minimum number of vertices that you need to remove in order to produce a good tree.

Constraints

2≦N≦2000

1≦K≦N-1

1≦A_i≦N, 1≦B_i≦N

The graph defined by A_i and B_i is a tree.

Input

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

N K
A_1 B_1
A_2 B_2
:
A_{N-1} B_{N-1}

Output

Print the minimum number of vertices that you need to remove in order to produce a good tree.

Sample Input 1

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

Sample Output 1

2

The tree is shown below. Removing vertices 5 and 6 will result in a good tree with the diameter of 2.

Sample Input 2

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

Sample Output 2

0

Since the given tree is already good, you do not need to remove any vertex.


let () = Scanf.scanf "%d %d\n" @@ fun n k ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- b - 1 :: es.(a - 1);
      es.(b - 1) <- a - 1 :: es.(b - 1);
  done;
  let d = Array.make_matrix n n min_int in
  for s = 0 to n - 1 do
    let rec dfs v =
      List.iter (fun u ->
        if d.(s).(u) < 0 then
          (d.(s).(u) <- 1 + d.(s).(v); dfs u)) es.(v) in
    d.(s).(s) <- 0; dfs s
  done;
  Printf.printf "%d\n" @@ ( - ) n @@ Array.fold_left max min_int @@ Array.init n @@ fun u ->
    let (_, vs, ws) = Array.fold_left (fun (v, vs, ws) d ->
      (v + 1),
      (if k <> d then vs else v :: vs),
      (if k < d  then ws else v :: ws)) (0, [], []) d.(u) in
    if
      List.exists (fun v ->
        List.exists (fun w ->
          k < d.(v).(w)) ws) vs
    then min_int
    else List.length ws


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

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

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

let al = Array.make n []

let maxarea r =
  let rec area i j = function
    | 0 -> 1
    | r -> List.fold_left (fun a k -> a + (if k = i then 0 else area j k (r-1))) 1 al.(j) in
  let rec aux accu = function
    | 0 -> accu
    | k -> aux (max (area (k-1) (k-1) (r/2)) accu) (k-1) in
  if r mod 2 = 0 then aux 0 n
  else List.fold_left (fun a (i,j) -> max a ((area i j (r/2)) + (area j i (r/2)))) 0 edges

let () =
  List.iter (fun (a,b) -> al.(a) <- b :: al.(a); al.(b) <- a :: al.(b)) edges;
  print_int (n-(maxarea k))


let id x = x

let s = 1000000007

let repeat f =
  let rec aux accu = function
    | 0 -> accu
    | n -> aux (f () :: accu) (n - 1) in
  aux []

let pow k =
  let rec aux accu k = function
  | 0 -> accu
  | n when n mod 2 == 0 -> aux accu (k*k mod s) (n/2)
  | n -> aux (accu*k mod s) (k*k mod s) (n/2) in
  aux 1 k

let inv k = pow k (s-2)

let rec bc n = function 0 -> 1 | k -> ((bc (n-1) (k-1))*(n*inv(k) mod s) mod s)

let () =
  let n = Scanf.scanf "%d\n" id in
  let l = repeat (fun () -> Scanf.scanf "%d %d\n" (fun a b -> (a,b))) n in
  let (maxa, maxb) = List.fold_left (fun (c,d) (a,b) -> (max a c, max d b)) (0, 0) l in
  let sal = List.sort (fun (a,b) (c,d) -> compare c a) l in
  let dp = Array.make (1 + 2 * maxb) 0 in
  let solve =
    let rec auxr sl accu m =
      match sl with
      | [] -> accu
      | (a, b) :: tl when a = m-maxa -> auxr tl ((accu+dp.(b+maxb)) mod s) m
      | _ -> Array.iteri (fun i x -> dp.(i) <- (x + if i > 0 then dp.(i-1) else 0) mod s) dp; auxr sl accu (m+1) in
    let rec auxl sl m =
      if m > maxa then (Array.iteri (fun i x -> dp.(i) <- (x + if i > 0 then dp.(i-1) else 0) mod s) dp; auxr (List.rev sal) 0 m)
        else match sl with
             | (a, b) :: tl when a = maxa-m -> dp.(maxb-b) <- (dp.(maxb-b) +1) mod s; auxl tl m
             | _ -> Array.iteri (fun i x -> dp.(i) <- (x + if i > 0 then dp.(i-1) else 0) mod s) dp; auxl sl (m+1) in
    auxl sal 0 in
  let x = List.fold_left (fun x (a,b) -> (x + bc (2*a+2*b) (2*a)) mod s) 0 l in
    if solve < x then print_int ((s+solve - x)/2) else print_int ((solve-x)/2);

Score : 1400 points

Problem Statement

Snuke is having another barbeque party.

This time, he will make one serving of Skewer Meal.

He has a stock of N Skewer Meal Packs. The i-th Skewer Meal Pack contains one skewer, A_i pieces of beef and B_i pieces of green pepper.
All skewers in these packs are different and distinguishable, while all pieces of beef and all pieces of green pepper are, respectively, indistinguishable.

To make a Skewer Meal, he chooses two of his Skewer Meal Packs, and takes out all of the contents from the chosen packs, that is, two skewers and some pieces of beef or green pepper.
(Remaining Skewer Meal Packs will not be used.)
Then, all those pieces of food are threaded onto both skewers, one by one, in any order.

(See the image in the Sample section for better understanding.)

In how many different ways can he make a Skewer Meal? Two ways of making a Skewer Meal is different if and only if the sets of the used skewers are different, or the orders of the pieces of food are different.
Since this number can be extremely large, find it modulo 10^9+7.

Constraints

2≦N≦200,000

1≦A_i≦2000, 1≦B_i≦2000

Input

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

N
A_1 B_1
A_2 B_2
:
A_N B_N

Output

Print the number of the different ways Snuke can make a serving of Skewer Meal, modulo 10^9+7.

Sample Input 1

3
1 1
1 1
2 1

Sample Output 1

26

The 26 ways of making a Skewer Meal are shown below.
Gray bars represent skewers, each with a number denoting the Skewer Meal Set that contained the skewer.
Brown and green rectangles represent pieces of beef and green pepper, respectively.