nu = gets.to_i - 1
inst = nu
ar = []
count = 0
for i in 0..19
  if nu == 1
    ar.push(1)
    count += 1
    break
  elsif nu % 2 == 0
    ar.push(0)
    nu /= 2
  else
    ar.push(1)
    count += 1
    nu /= 2
  end
end
leng = ar.length
if count == leng
  puts "#{count + 1} #{count*2}"
  for i in 1..count
    puts "#{i} #{i + 1} 0"
  end
  for i in 1..count
    puts "#{i} #{i + 1} #{2**(count - i)}"
  end
  exit
end

check = 0
check2 = 0
for i in 0..leng - 2
  if (ar[0] == 0 && i == 0) || (ar[0] == 1 && ar[1] == 0 && i == 0)
    check += 1
  elsif i != 0 && ar[i] == 1
    check += 1
  end
  if ar[i] == 1 && check2 == i
    check2 += 1
  end
end

count2 = 0
puts "#{leng} #{(leng - 1)*2 + check}"
for i in 1..leng - 1
  puts "#{i} #{i + 1} #{2**(leng - 1 - i)}"
end
for i in 1..leng - 1
  puts "#{i} #{i + 1} 0"
end
for i in 2..leng
  if check2 >= 2 && check2 == leng + 1 - i
    for j in 1..i - 1
      if ar[-j] == 1
        count2 += 2**(leng - j)
      end
    end
    puts "1 #{i - 1} #{count2}"
    exit
  elsif (ar[-i] == 1) && (i != leng)
    for j in 1..i - 1
      if ar[-j] == 1
        count2 += 2**(leng - j)
      end
    end
    puts "1 #{i} #{count2}"
  elsif (i == leng && ar[0] == 1 && ar[1] == 0)
    for j in 1..i - 1
      if ar[-j] == 1
        count2 += 2**(leng - j)
      end
    end
    puts "1 #{leng - 1} #{inst - 1}"
  elsif (i == leng && ar[0] == 0)
    puts "1 #{leng} #{inst}"
  end
  count2 = 0
end

p check2
p ar.reverse

Score : 700 points

Problem Statement

You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.

The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.

The number of edges, M, is at most 60. Each edge has an integer length between 0 and 10^6 (inclusive).

Every edge is directed from the vertex with the smaller ID to the vertex with the larger ID. That is, 1,2,...,N is one possible topological order of the vertices.

There are exactly L different paths from Vertex 1 to Vertex N. The lengths of these paths are all different, and they are integers between 0 and L-1.

Here, the length of a path is the sum of the lengths of the edges contained in that path, and two paths are considered different when the sets of the edges contained in those paths are different.

Constraints

2 \leq L \leq 10^6

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

In the first line, print N and M, the number of the vertices and edges in your graph.
In the i-th of the following M lines, print three integers u_i,v_i and w_i, representing the starting vertex, the ending vertex and the length of the i-th edge.
If there are multiple solutions, any of them will be accepted.

Sample Input 1

4

Sample Output 1

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

In the graph represented by the sample output, there are four paths from Vertex 1 to N=8:

1 → 2 → 3 → 4 → 8 with length 0

1 → 2 → 3 → 7 → 8 with length 1

1 → 2 → 6 → 7 → 8 with length 2

1 → 5 → 6 → 7 → 8 with length 3

There are other possible solutions.

Sample Input 2

5

Sample Output 2

5 7
1 2 0
2 3 1
3 4 0
4 5 0
2 4 0
1 3 3
3 5 1


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

Score : 100 points

Problem Statement

There is an N-car train.

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

Constraints

1 \leq N \leq 100

1 \leq i \leq N

Input

Input is given from Standard Input in the following format:

N i

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

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

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5

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.


H, W = gets.split.map(&:to_i)
puts (0...H).map {gets.chomp.chars}.
  reject {|xs| xs.all? {|x| x == "."}}.
  transpose.
  reject {|xs| xs.all? {|x| x == "."}}.
  transpose.
  map {|xs| xs.join}

Score : 200 points

Problem Statement

There is a grid of squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column from the left is represented as (i, j).
Each square is black or white.
The color of the square is given as an H-by-W matrix (a_{i, j}).
If a_{i, j} is ., the square (i, j) is white; if a_{i, j} is #, the square (i, j) is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

1 \leq H, W \leq 100

a_{i, j} is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

H W
a_{1, 1}...a_{1, W}
:
a_{H, 1}...a_{H, W}

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

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

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

..#
#..
.#.
.#.
#.#


Score: 100 points

Problem Statement

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

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

Note

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

Constraints

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

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

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

2 2

Sample Output 1

1

In this case, the area is 1 square yard.

Sample Input 2

5 7

Sample Output 2

24

In this case, the area is 24 square yards.


a, b = gets.split.map(&:to_i)

puts (a * b) - a - b + 1


a, b = gets.chomp.split.map(&:to_i)
puts (a-1) * (b-1)


N = gets.to_i
cnt = 0
(1..N).each do |i|
  dn = 0
  next if i.even?
  (1..i).each do |n|
    dn += 1 if i%n == 0
  end
  cnt += 1 if dn == 8
end

puts cnt

Score: 200 points

Problem Statement

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

Constraints

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

Input

Input is given from Standard Input in the following format:

N

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

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

Sample Input 2

7

Sample Output 2

0

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


N = gets.to_i
c = 0
(1..N).each do |n|
 next unless n.odd?
 c += (1..n).count { |m| (n % m).zero? } == 8 ? 1 : 0
end
puts c


p->(s,k){s.each_with_index{|i,j|return (j<k ?i:1)if i!=1}}.(gets.split('').map(&:to_i),gets.to_i)

Score: 300 points

Problem Statement

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

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

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

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

S
K

Output

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

Sample Input 1

1214
4

Sample Output 1

2

The string S changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

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

Sample Input 2

3
157

Sample Output 2

3

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

Sample Input 3

299792458
9460730472580800

Sample Output 3

2


#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

def cumulative_sum(arr)
  arr.reduce([0]) do |prev, cur|
    prev.push(prev.last + cur)
    prev
  end
end

N, M, Q = get_ints

array = Array.new(N+1) { Array.new(N+1, 0) }
M.times do |i|
  l, r = get_ints
  array[l][r] += 1
end

S = Array.new(N+1) { Array.new(N+1, 0) }

1.step(N) do |i|
  1.step(N) do |j|
    S[i][j] = array[i][j] + S[i][j-1] + S[i-1][j] - S[i-1][j-1]
  end
end

Q.times do
  l, r = get_ints
  puts S[r][r] - S[r][l-1] - S[l-1][r] + S[l-1][l-1]
end

Score: 400 points

Problem Statement

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

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

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

Constraints

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

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

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

1
1

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

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10


N, M, Q = gets.split(" ").map { |e| e.to_i }
data = Array.new(N) { Array.new(N) {0} }

for i in 0..M-1 do
  li, ri = gets.split(" ").map { |e| e.to_i }
  data[li-1][ri-1] += 1
end

data2 = Array.new(N+1) {Array.new(N+1) {0}}
for i in 0..N-1 do
  count = 0
  for j in 0..N-1 do
    count += data[i][j]
    data2[i][j] = count
  end
end

pq = []
for i in 0..Q-1 do
  piqi = gets.split(" ").map { |e| e.to_i }
  pq << piqi
end

for i in 0..Q-1 do
  pi, qi = pq[i]
  res = 0
  for j in pi-1..qi-1 do
    res += data2[j][qi-1] - data2[j][pi-2]
  end
  puts res
end


N,K = gets.split.map(&:to_i)
puts N % K == 0 ? 0 : 1

Score : 100 points

Problem Statement

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

Constraints

1 \leq N,K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

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

Sample Input 1

7 3

Sample Output 1

1

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

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0


Score : 400 points

Problem Statement

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

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

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

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

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

Constraints

All values in input are integers.

1 \leq N \leq 10^5

2 \leq M \leq 10^9

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N

Output

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

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

Sample Input 1

3 2
4 1 5

Sample Output 1

3

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

Sum for (1, 1): 4

Sum for (1, 2): 5

Sum for (1, 3): 10

Sum for (2, 2): 1

Sum for (2, 3): 6

Sum for (3, 3): 5

Among these, three are multiples of 2.

Sample Input 2

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

Sample Output 2

6

Sample Input 3

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

Sample Output 3

25


# frozen_string_literal: true

s = gets.chomp.chars

if s[0] == 'A' && s[2..-2].count('C') == 1 && s.count { |c| c.upcase == c } == 2
  puts :AC
else
  puts :WA
end

Score : 200 points

Problem Statement

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

The initial character of S is an uppercase A.

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

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

Constraints

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

Each character of S is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

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

Sample Input 1

AtCoder

Sample Output 1

AC

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

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.


S = gets.chomp

ans = 'AC'

ans = 'WA' if S[0] != 'A'
ans = 'WA' if S[2..-2].count('C') != 1
ans = 'WA' if S.count('A-Z') != 2

puts ans


s = gets.chomp
if s.match(/^A([a-z]{0,1}C[a-z]*|[a-z]*C[a-z]{0,1})$/).nil?
  puts 'WA'
else
  puts 'AC'
end


#!/usr/bin/ruby
#encoding: utf-8

s = gets.chomp

cnt = 0
(2..s.size-2).each do |i|
  if s[i] == 'C'
    cnt += 1
  end
end

if cnt != 1 or s[0] != 'A'
  puts "WA"
  exit
end

(0..s.size-1).each do |i|
  if s[i] != 'A' and s[i] != 'C'
    if s[i].ord < 97 or s[i].ord > 122
      puts "WA"
      exit
    end
  end
end

puts "AC"


s= gets.chomp
count=0
flag = false
l=s[2..s.size-2].split("")
  l.each do |i|
  if i == "C"
    count=count+1
    flag = true
  end
  if i=="A" || i=="B" || i>"C"
    flag == false
  end
  if count==2
    flag = false
    break
  end
end
if s[0]== "A" && flag ==true
  puts "AC"
else
  puts "WA"
end


lines = $stdin.read
array = lines.split("\n")
S     = array[0].split("")
str   = S.dup

if S.first=='A' and S[2...S.length-1].count{|s| s=='C'}==1
  str.delete_at(0)
  idx = S[2...S.length-1].index{|s| s=='C'} + 2
  str.delete_at(idx)

  if str =~ /[a-z]+/
    puts "AC"
  else
    puts "WA"
  end
else
  puts "WA"
end


"
3. ABC104C - All Green
リンク：　https://atcoder.jp/contests/abc104/tasks/abc104_c
"

# 入力
D, G = gets.split.map(&:to_i)
p = []
c = []
D.times do |i|
  p[i], c[i] = gets.split.map(&:to_i)
end

# Dでbit全探索
# i桁目をp[i]進報で表せば、得点の計算できそう
ans = 10000
(1 << D).times do |i|
  point = 0
  ma = -1
  gap = 0
  num = 0
  tmp = 0
  D.times do |j|
    # i[j]==1なら配点100(j+1)の問題を完全に解く
    if i[j] == 1
      point = point + 100*(j+1) * p[j] + c[j]
      num = num + p[j]
      if point >= G
        ans = [ans, num].min
      end
    else
      ma = [ma, j].max
    end
  end
  # ここまでで全問解く配点の問題は決まった
  # 目標までの差を出す
  gap = G - point
  if ma != -1 && gap > 0
  # 完全に解かない(i[j]==0なるjの最大値)もののうち、
  # 最も高い配点はmaに入ってる配点100(ma+1)点
    tmp = gap / (100*(ma+1)) #その配点を何問解けば目標達成できるか
    if tmp <= p[ma]-1 # これを満たさない場合は、完全に解く選択がミスってる
      # ここに入ったってことは、maの問題をnumだけ中途半端に解けば目標達成できる
      num = num + tmp
      ans = [ans, num].min
    end
  end
  puts ans
end
puts ans

Score : 300 points

Problem Statement

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

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

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

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

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

Constraints

1 ≤ D ≤ 10

1 ≤ p_i ≤ 100

100 ≤ c_i ≤ 10^6

100 ≤ G

All values in input are integers.

c_i and G are all multiples of 100.

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

Input

Input is given from Standard Input in the following format:

D G
p_1 c_1
:
p_D c_D

Output

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

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

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

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

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

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

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

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

Sample Input 4

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

Sample Output 4

66

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


S = gets.chomp
N = S.length
MOD = 10**9+7
dp = [1,0,0,0] # 3^cnt(X),A,AB,ABC
N.times do |i|
	prev = dp.dup
	c = S[i]
	if c == "A"
		dp[1] += prev[0]
	elsif c == "B"
		dp[2] += prev[1]
	elsif c == "C"
		dp[3] += prev[2]
	else
		dp[1] += prev[1]*2 + prev[0]
		dp[2] += prev[2]*2 + prev[1]
		dp[3] += prev[3]*2 + prev[2]
		dp[0] *= 3
	end
	dp[0] %= MOD
	dp[1] %= MOD
	dp[2] %= MOD
	dp[3] %= MOD
end

p dp[3]

Score : 400 points

Problem Statement

The ABC number of a string T is the number of triples of integers (i, j, k) that satisfy all of the following conditions:

1 ≤ i < j < k ≤ |T| (|T| is the length of T.)

T_i = A (T_i is the i-th character of T from the beginning.)

T_j = B

T_k = C

For example, when T = ABCBC, there are three triples of integers (i, j, k) that satisfy the conditions: (1, 2, 3), (1, 2, 5), (1, 4, 5). Thus, the ABC number of T is 3.

You are given a string S. Each character of S is A, B, C or ?.

Let Q be the number of occurrences of ? in S. We can make 3^Q strings by replacing each occurrence of ? in S with A, B or C. Find the sum of the ABC numbers of all these strings.

This sum can be extremely large, so print the sum modulo 10^9 + 7.

Constraints

3 ≤ |S| ≤ 10^5

Each character of S is A, B, C or ?.

Input

Input is given from Standard Input in the following format:

S

Output

Print the sum of the ABC numbers of all the 3^Q strings, modulo 10^9 + 7.

Sample Input 1

A??C

Sample Output 1

8

In this case, Q = 2, and we can make 3^Q = 9 strings by by replacing each occurrence of ? with A, B or C. The ABC number of each of these strings is as follows:

AAAC: 0

AABC: 2

AACC: 0

ABAC: 1

ABBC: 2

ABCC: 2

ACAC: 0

ACBC: 1

ACCC: 0

The sum of these is 0 + 2 + 0 + 1 + 2 + 2 + 0 + 1 + 0 = 8, so we print 8 modulo 10^9 + 7, that is, 8.

Sample Input 2

ABCBC

Sample Output 2

3

When Q = 0, we print the ABC number of S itself, modulo 10^9 + 7. This string is the same as the one given as an example in the problem statement, and its ABC number is 3.

Sample Input 3

????C?????B??????A???????

Sample Output 3

979596887

In this case, the sum of the ABC numbers of all the 3^Q strings is 2291979612924, and we should print this number modulo 10^9 + 7, that is, 979596887.


i = gets.chomp.split(' ').map(&:to_i)
result = []

for p in 0..(i.length-1)
  for q in (p+1)..(i.length-1)
    result << (i[p]-i[q]).abs
  end
end

result.sort!{ |i, j| i <=> j }.reverse!
puts result[0]

Score : 100 points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost 0.

Then, just after completing the i-th task, you can complete the j-th task at cost |A_j - A_i|.

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

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

1 \leq A_1, A_2, A_3 \leq 100

Input

Input is given from Standard Input in the following format:

A_1 A_2 A_3

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be 5, which is the minimum:

Complete the first task at cost 0.

Complete the third task at cost 2.

Complete the second task at cost 3.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0


s = gets.chomp.chars
t = gets.chomp.chars
ns = s.count

res = false

res = true if s == t
unless res
  ns.times do |i|
    first = s.delete_at(0)
    s << first
    if s == t
      res = true
      break
    end
  end
end
puts res ? 'Yes' : 'No'

Score : 200 points

Problem Statement

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

Determine if S equals T after rotation.

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

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

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

Constraints

2 \leq |S| \leq 100

|S| = |T|

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

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

Sample Input 1

kyoto
tokyo

Sample Output 1

Yes

In the first operation, kyoto becomes okyot.

In the second operation, okyot becomes tokyo.

Sample Input 2

abc
arc

Sample Output 2

No

abc does not equal arc after any number of operations.

Sample Input 3

aaaaaaaaaaaaaaab
aaaaaaaaaaaaaaab

Sample Output 3

Yes


require 'pp'

s = gets.chomp! * 2
t = gets.chomp!

if s.match(/#{t}/)
    puts "Yes"
else
    puts "No"
end


s=gets.chomp
t=gets.chomp
s<<s
if s.include?(t) then
	puts("Yes")
else
	puts("No")
end


N = gets.to_i
a = gets.split(' ').map(&:to_i)

ret = 0

for i in 0..N-1 do
    ret += a[i] - 1
end

puts ret

Score : 300 points

Problem Statement

You are given N positive integers a_1, a_2, ..., a_N.

For a non-negative integer m, let f(m) = (m\ mod\ a_1) + (m\ mod\ a_2) + ... + (m\ mod\ a_N).

Here, X\ mod\ Y denotes the remainder of the division of X by Y.

Find the maximum value of f.

Constraints

All values in input are integers.

2 \leq N \leq 3000

2 \leq a_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the maximum value of f.

Sample Input 1

3
3 4 6

Sample Output 1

10

f(11) = (11\ mod\ 3) + (11\ mod\ 4) + (11\ mod\ 6) = 10 is the maximum value of f.

Sample Input 2

5
7 46 11 20 11

Sample Output 2

90

Sample Input 3

7
994 518 941 851 647 2 581

Sample Output 3

4527


Score : 200 points

Problem Statement

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

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

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

Constraints

2 \leq N \leq 100

1 \leq a_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the minimum number of spells required.

Sample Input 1

5
1 1 2 2 2

Sample Output 1

2

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

Sample Input 2

3
1 2 1

Sample Output 2

0

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

Sample Input 3

5
1 1 1 1 1

Sample Output 3

2

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

Sample Input 4

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

Sample Output 4

4


def judge(morning, buy, thresh, adder)
  # 朝より購入のほうが多い -> 即NG
  return false if morning < buy

  # 購入より補充のほうが少ない -> 即NG
  return false if adder < buy

  # 購入よりしきい値のほうが多い -> 即OK
  # 購入-1 <= しきい値           -> 即OK
  return true if buy-1 <= thresh

  # 初期処理
  # morningをthreshぎりぎりまで減らす
  if thresh < morning
    d = (morning - thresh) / buy
    morning -= buy * d
  end
  # adderもthreshぎりぎりまで減らす
  if thresh < adder
    d = (adder - thresh) / buy
    adder -= buy * d
  end

  s = morning
  s_ary = []
  inc = adder - buy

  while true do
    if s <= thresh
      # ここの回数を減らしたい！
      # s += adder
      # 単純に加算するのではなく、(adder-buy)ずつ増やしていって、threshを超えさせよう

      # thresh < s + (adder - buy) * XXX
      return true if inc == 0

      d = (thresh - s) / inc + 1
      s += inc * d
    else
      # 補充なしターン
      if s < buy
        return false
      end
      if s_ary.index(s)
        return true
      end
      # thresh上に出たところだけ記憶しておく
      s_ary << s
      s -= buy
    end
  end
end

def main
  t = ARGF.gets.to_i

  t.times do
    morning, buy, thresh, adder = ARGF.gets.split.map(&:to_i)
    if judge(morning, buy, thresh, adder)
      puts 'Yes'
    else
      puts 'No'
    end
  end
end

if __FILE__ == $0
  main
end

Score : 600 points

Problem Statement

Ringo Mart, a convenience store, sells apple juice.

On the opening day of Ringo Mart, there were A cans of juice in stock in the morning.
Snuke buys B cans of juice here every day in the daytime.
Then, the manager checks the number of cans of juice remaining in stock every night.
If there are C or less cans, D new cans will be added to the stock by the next morning.

Determine if Snuke can buy juice indefinitely, that is, there is always B or more cans of juice in stock when he attempts to buy them.
Nobody besides Snuke buy juice at this store.

Note that each test case in this problem consists of T queries.

Constraints

1 \leq T \leq 300

1 \leq A, B, C, D \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

T
A_1 B_1 C_1 D_1
A_2 B_2 C_2 D_2
:
A_T B_T C_T D_T

In the i-th query, A = A_i, B = B_i, C = C_i, D = D_i.

Output

Print T lines. The i-th line should contain Yes if Snuke can buy apple juice indefinitely in the i-th query; No otherwise.

Sample Input 1

14
9 7 5 9
9 7 6 9
14 10 7 12
14 10 8 12
14 10 9 12
14 10 7 11
14 10 8 11
14 10 9 11
9 10 5 10
10 10 5 10
11 10 5 10
16 10 5 10
1000000000000000000 17 14 999999999999999985
1000000000000000000 17 15 999999999999999985

Sample Output 1

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

In the first query, the number of cans of juice in stock changes as follows: (D represents daytime and N represents night.)

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 6
→D x

In the second query, the number of cans of juice in stock changes as follows:

9
→D 2
→N 11
→D 4
→N 13
→D 6
→N 15
→D 8
→N 8
→D 1
→N 10
→D 3
→N 12
→D 5
→N 14
→D 7
→N 7
→D 0
→N 9
→D 2
→N 11
→D …

and so on, thus Snuke can buy juice indefinitely.

Sample Input 2

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

Sample Output 2

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


Score : 100 points

Problem Statement

You are given two integers a and b.
Determine if a+b=15 or a\times b=15 or neither holds.

Note that a+b=15 and a\times b=15 do not hold at the same time.

Constraints

1 \leq a,b \leq 15

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b

Output

If a+b=15, print +;
if a\times b=15, print *;
if neither holds, print x.

Sample Input 1

4 11

Sample Output 1

+

4+11=15.

Sample Input 2

3 5

Sample Output 2

*

3\times 5=15.

Sample Input 3

1 1

Sample Output 3

x

1+1=2 and 1\times 1=1, neither of which is 15.


class PriorityQueue
  include Enumerable

  MIN = -(2 << 60)

  attr_reader :size

  def initialize(&block)
    @size = 0
    @heap = Array.new
    @get_key = block || :itself.to_proc
  end

  def each
    (1..@size).each do |i|
      yield @heap[i]
    end
  end

  def empty?
    size == 0
  end

  def pop
    return nil if @size <= 0
    max = @heap[1]
    @heap[1] = @heap[@size]
    @size -= 1
    max_heapify(1)
    max
  end

  def push(x)
    @size += 1
    i = @size
    @heap[i] = x
    while i > 1 && @get_key.call(@heap[i / 2]) < @get_key.call(@heap[i])
      t = @heap[i / 2]
      @heap[i / 2] = @heap[i]
      @heap[i] = t
      i = i / 2
    end
  end

  def top
    return nil if @size <= 0
    @heap[1]
  end

  private

  def max_heapify(i)
    l = 2 * i
    r = 2 * i + 1
    largest =
      l <= @size && @get_key.call(@heap[l]) > @get_key.call(@heap[i]) ? l : i
    largest = r \
      if r <= @size && @get_key.call(@heap[r]) > @get_key.call(@heap[largest])
    unless largest == i
      t = @heap[i]
      @heap[i] = @heap[largest]
      @heap[largest] = t
      max_heapify(largest)
    end
  end
end

N, M, S, T = gets.split.map(&:to_i)
uvab_list = M.times.map { gets.split.map(&:to_i) }
MONEY = 10 ** 15
yen_graph = Array.new(N) { Array.new }
snuke_graph = Array.new(N) { Array.new }
uvab_list.each do |(u, v, a, b)|
  u -= 1
  v -= 1
  yen_graph[u].push([v, a])
  yen_graph[v].push([u, a])
  snuke_graph[u].push([v, b])
  snuke_graph[v].push([u, b])
end

def dijkstra(s, graph)
  pq = PriorityQueue.new { |(_, d)| -d }
  d_list = Array.new(graph.size, 1 << 60)
  d_list[s] = 0
  pq.push([s, 0])
  while !pq.empty?
    v, d = pq.pop
    next if d > d_list[v]
    graph[v].each do |(u, c)|
      if d_list[u] > d_list[v] + c
        d_list[u] = d_list[v] + c
        pq.push([u, d_list[u]])
      end
    end
  end
  d_list
end

yen_d_list = dijkstra(S - 1, yen_graph)
snuke_d_list = dijkstra(T - 1, snuke_graph)
cost_list = yen_d_list.zip(snuke_d_list).map { |(y, s)| y + s }
ans_list = Array.new(N)
ans_list[N - 1] = MONEY - cost_list[N - 1]
(N - 2).downto(0).each do |i|
  ans_list[i] = [MONEY - cost_list[i], ans_list[i + 1]].max
end
ans_list.each { |ans| puts ans }

Score : 400 points

Problem Statement

Kenkoooo is planning a trip in Republic of Snuke.
In this country, there are n cities and m trains running.
The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally.
Any city can be reached from any city by changing trains.

Two currencies are used in the country: yen and snuuk.
Any train fare can be paid by both yen and snuuk.
The fare of the i-th train is a_i yen if paid in yen, and b_i snuuk if paid in snuuk.

In a city with a money exchange office, you can change 1 yen into 1 snuuk.
However, when you do a money exchange, you have to change all your yen into snuuk.
That is, if Kenkoooo does a money exchange when he has X yen, he will then have X snuuk.
Currently, there is a money exchange office in every city, but the office in City i will shut down in i years and can never be used in and after that year.

Kenkoooo is planning to depart City s with 10^{15} yen in his pocket and head for City t, and change his yen into snuuk in some city while traveling.
It is acceptable to do the exchange in City s or City t.

Kenkoooo would like to have as much snuuk as possible when he reaches City t by making the optimal choices for the route to travel and the city to do the exchange.
For each i=0,...,n-1, find the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i years.
You can assume that the trip finishes within the year.

Constraints

2 \leq n \leq 10^5

1 \leq m \leq 10^5

1 \leq s,t \leq n

s \neq t

1 \leq u_i < v_i \leq n

1 \leq a_i,b_i \leq 10^9

If i\neq j, then u_i \neq u_j or v_i \neq v_j.

Any city can be reached from any city by changing trains.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n m s t
u_1 v_1 a_1 b_1
:
u_m v_m a_m b_m

Output

Print n lines.
In the i-th line, print the maximum amount of snuuk that Kenkoooo has when he reaches City t if he goes on a trip from City s to City t after i-1 years.

Sample Input 1

4 3 2 3
1 4 1 100
1 2 1 10
1 3 20 1

Sample Output 1

999999999999998
999999999999989
999999999999979
999999999999897

After 0 years, it is optimal to do the exchange in City 1.

After 1 years, it is optimal to do the exchange in City 2.

Note that City 1 can still be visited even after the exchange office is closed.
Also note that, if it was allowed to keep 1 yen when do the exchange in City 2 and change the remaining yen into snuuk, we could reach City 3 with 999999999999998 snuuk, but this is NOT allowed.

After 2 years, it is optimal to do the exchange in City 3.

After 3 years, it is optimal to do the exchange in City 4.
Note that the same train can be used multiple times.

Sample Input 2

8 12 3 8
2 8 685087149 857180777
6 7 298270585 209942236
2 4 346080035 234079976
2 5 131857300 22507157
4 8 30723332 173476334
2 6 480845267 448565596
1 4 181424400 548830121
4 5 57429995 195056405
7 8 160277628 479932440
1 6 475692952 203530153
3 5 336869679 160714712
2 7 389775999 199123879

Sample Output 2

999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994


Score : 100 points

Problem Statement

You are given a positive integer N.
Find the minimum positive integer divisible by both 2 and N.

Constraints

1 \leq N \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum positive integer divisible by both 2 and N.

Sample Input 1

3

Sample Output 1

6

6 is divisible by both 2 and 3.
Also, there is no positive integer less than 6 that is divisible by both 2 and 3.
Thus, the answer is 6.

Sample Input 2

10

Sample Output 2

10

Sample Input 3

999999999

Sample Output 3

1999999998


n = gets.to_i

if n.even?
  puts n
else
  puts n*2
end


n = gets.to_i
a = gets.split.map(&:to_i)
puts a.max - a.min

Score : 200 points

Problem Statement

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

Constraints

2 \leq N \leq 100

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum absolute difference of two elements (with different indices) in A.

Sample Input 1

4
1 4 6 3

Sample Output 1

5

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

Sample Input 2

2
1000000000 1

Sample Output 2

999999999

Sample Input 3

5
1 1 1 1 1

Sample Output 3

0


gets
a=gets.chomp.split.map(&:to_i)
puts a.max - a.min


N = gets.to_i
A = gets.split.map &:to_i
m = 0
for i in 0...N
  for j in (i+1)...N
    m = [m, (A[i]-A[j]).abs].max
  end
end
puts m


N = gets.to_i
a_list = gets.split.map(&:to_i)
diff_list = a_list.map.with_index do |a, i|
  a - i - 1
end.sort

def calc(diff_list, b)
  diff_list.map do |d|
    (d - b).abs
  end.reduce(&:+)
end

ans = calc(diff_list, diff_list[N / 2])
puts ans

Score : 300 points

Problem Statement

Snuke has an integer sequence A of length N.

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

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

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

Find the minimum possible sadness of Snuke.

Constraints

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

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the minimum possible sadness of Snuke.

Sample Input 1

5
2 2 3 5 5

Sample Output 1

2

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

Sample Input 2

9
1 2 3 4 5 6 7 8 9

Sample Output 2

0

Sample Input 3

6
6 5 4 3 2 1

Sample Output 3

18

Sample Input 4

7
1 1 1 1 2 3 4

Sample Output 4

6


n = gets.to_i
as = gets.split.map(&:to_i).map.with_index { |x, i| x - i - 1 }
if n.odd?
  med = as[n/2]
  p as.map { |a| (a-med).abs }.inject(:+)
else
  med = as[n/2-1] + as[n/2]
  med_f = med.fdiv(2).floor
  med_c = med.fdiv(2).ceil
  ans_f = 0
  ans_c = 0
  as.each do |a|
    ans_f += (a-med_f).abs
    ans_c += (a-med_c).abs
  end
  p [ans_f, ans_c].min
end


array = gets.chomp.split("")
sum = 0

array.each do |mark|
  if mark == "+"
    sum += 1
  else
    sum -= 1
  end
end

puts sum

Score : 100 points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is 0. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by 1; when he eats -, the integer in his mind decreases by 1.

The symbols Takahashi is going to eat are given to you as a string S. The i-th character in S is the i-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of S is 4.

Each character in S is + or -.

Input

Input is given from Standard Input in the following format:

S

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is 0.

The first integer for him to eat is +. After eating it, the integer in his mind becomes 1.

The second integer to eat is -. After eating it, the integer in his mind becomes 0.

The third integer to eat is +. After eating it, the integer in his mind becomes 1.

The fourth integer to eat is +. After eating it, the integer in his mind becomes 2.

Thus, the integer in Takahashi's mind after he eats all the symbols is 2.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4


s = gets
ans = 0
s.chars.each do |op|
  ans += 1 if op == '+'
  ans -= 1 if op == '-'
end

puts ans
~


n = gets.strip
sum = 0
n.split('').map(&:to_i).each do |n|
  sum+=n
end
if (n.to_i % sum).zero?
  p 'Yes'
else
  p 'No'
end

Score : 200 points

Problem Statement

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

Given an integer N, determine if S(N) divides N.

Constraints

1 \leq N \leq 10^9

Input

Input is given from Standard Input in the following format:

N

Output

If S(N) divides N, print Yes; if it does not, print No.

Sample Input 1

12

Sample Output 1

Yes

In this input, N=12.
As S(12) = 1 + 2 = 3, S(N) divides N.

Sample Input 2

101

Sample Output 2

No

As S(101) = 1 + 0 + 1 = 2, S(N) does not divide N.

Sample Input 3

999999999

Sample Output 3

Yes


n,k=gets.chomp.split(" ").map(&:to_i)
a=gets.chomp.split(" ").map(&:to_i);
one = a.index(1)
if k < one then
  l = one
  r = n - one + 1
  ans = 0
  ans += l / k
  if l % k != 0 then
    ans += 1
  end
  ans += r / k
  if r % k != 0 then
    ans += 1
  end
else
  ans = n/k
  if n % k != 0
    ans += 1
  end
end
puts ans

Score : 300 points

Problem Statement

There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.

On this sequence, Snuke can perform the following operation:

Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

2 \leq K \leq N \leq 100000

A_1, A_2, ..., A_N is a permutation of 1, 2, ..., N.

Input

Input is given from Standard Input in the following format:

N K
A_1 A_2 ... A_N

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence A becomes 1, 1, 1, 4.

In the second operation, choose the second, third and fourth elements. The sequence A becomes 1, 1, 1, 1.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4


n, k = gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split("")

if n == k then
  puts "1"
  exit
end

t = k - 1

puts 1 + ((n - k).to_f / t).ceil


n, k = gets.split(" ").map{|d| d.to_i }
a = gets.split(" ").map{|m| m.to_i }
puts (a.size + k - 3)  / (k - 1)


k = gets.chomp.to_i

def s(n)
    nn = n
    ret = 0
    while(nn>0) do
        ret += nn % 10
        nn /= 10
    end
    return ret
end

def f(n)
    nn = n
    i = 0
    ret = 0
    val = 10 ** 16
    while(nn>0) do
        nn /= 10
        i += 1
        m = (nn+1) * 10 ** i - 1
        if val > m.to_f / s(m)
            val = m.to_f / s(m)
            ret = m
        end
    end
    return ret
end

(1..9).each do |i|
    puts i
    k -= 1
    exit if k == 0
end

n = 10
while(k>0)
    n = f(n+1)
    puts n
    k -= 1
end

Score : 500 points

Problem Statement

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

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

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

Constraints

1 \leq K

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

Input

Input is given from Standard Input in the following format:

K

Output

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

Sample Input 1

10

Sample Output 1

1
2
3
4
5
6
7
8
9
19


arr = $stdin.gets.chomp.split" "
arr.map! do |a_j|
 a_j.to_i
end

if arr[0] <= 8 and arr[1] <= 8
  puts "Yay!"
else
  puts ":("
end

Score: 100 points

Problem Statement

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

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

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

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

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

Constraints

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

A+B is at most 16.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

5 4

Sample Output 1

Yay!

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

Sample Input 2

8 8

Sample Output 2

Yay!

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

Sample Input 3

11 4

Sample Output 3

:(

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


a, b = gets.chomp.split(" ").map(&:to_i)

v = 16 - [a, b].min * 2

if v == 0 || v / 2 >= ([a, b].max - [a, b].min) then
  puts "Yay!"
else
  puts ":("
end


def cnt(n)
	i = 0
	while n%2 < 1
		n = n / 2
		i += 1
	end
	return i
end
n = gets
nums = gets.chomp.split(" ").map(&:to_i)
sum = 0
nums.each do |num|
	sum+=cnt(num)
end
puts sum

Score: 300 points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length N, a = {a_1, a_2, a_3, ..., a_N}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every i satisfying 1 \leq i \leq N, perform one of the following: "divide a_i by 2" and "multiply a_i by 3".
Here, choosing "multiply a_i by 3" for every i is not allowed, and the value of a_i after the operation must be an integer.

At most how many operations can be performed?

Constraints

N is an integer between 1 and 10 \ 000 (inclusive).

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

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 a_3 ... a_N

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially {5, 2, 4}. Three operations can be performed as follows:

First, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {15, 6, 2}.

Next, multiply a_1 by 3, divide a_2 by 2 and multiply a_3 by 3. The sequence is now {45, 3, 6}.

Finally, multiply a_1 by 3, multiply a_2 by 3 and divide a_3 by 2. The sequence is now {135, 9, 3}.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is 0.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39


N, *AS = $stdin.read.split.map(&:to_i)
def n_2(a)
  return 0 if a.odd?
  30.downto(1) do |i|
    k = 2**i
    next if k > a
    if a % k == 0
      return i
    end
  end
  return 0
end
#AS.each do |a|
#  p a: a, n_2: n_2(a)
#end
p AS.map{|a| n_2(a)}.inject(:+)


N, M = gets.split.map(&:to_i)
cakes = []; N.times { cakes << gets.split.map(&:to_i) }
def cb(i); i==1 ? 1 : -1 ;end ;
ans = 0
p ans

Score: 400 points

Problem Statement

Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.

The shop sells N kinds of cakes.

Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.

These values may be zero or negative.

Ringo has decided to have M pieces of cakes here. He will choose the set of cakes as follows:

Do not have two or more pieces of the same kind of cake.

Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity).

Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Constraints

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

M is an integer between 0 and N (inclusive).

x_i, y_i, z_i \ (1 \leq i \leq N) are integers between -10 \ 000 \ 000 \ 000 and 10 \ 000 \ 000 \ 000 (inclusive).

Input

Input is given from Standard Input in the following format:

N M
x_1 y_1 z_1
x_2 y_2 z_2
: :
x_N y_N z_N

Output

Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Sample Input 1

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

Sample Output 1

56

Consider having the 2-nd, 4-th and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 3 + 9 = 13

Tastiness: 5 + 5 + 7 = 17

Popularity: 9 + 8 + 9 = 26

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 13 + 17 + 26 = 56. This is the maximum value.

Sample Input 2

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

Sample Output 2

54

Consider having the 1-st, 3-rd and 5-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: 1 + 7 + 13 = 21

Tastiness: (-2) + (-8) + (-14) = -24

Popularity: 3 + (-9) + 15 = 9

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 21 + 24 + 9 = 54. This is the maximum value.

Sample Input 3

10 5
10 -80 21
23 8 38
-94 28 11
-26 -2 18
-69 72 79
-26 -86 -54
-72 -50 59
21 65 -32
40 -94 87
-62 18 82

Sample Output 3

638

If we have the 3-rd, 4-th, 5-th, 7-th and 10-th kinds of cakes, the total beauty, tastiness and popularity will be -323, 66 and 249, respectively.

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is 323 + 66 + 249 = 638. This is the maximum value.

Sample Input 4

3 2
2000000000 -9000000000 4000000000
7000000000 -5000000000 3000000000
6000000000 -1000000000 8000000000

Sample Output 4

30000000000

The values of the beauty, tastiness and popularity of the cakes and the value to be printed may not fit into 32-bit integers.


N, M = gets.split.map(&:to_i)
if M > 0
  inf = 10000000000 * M
  arr = Array.new(8){Array.new(M){-inf}}
  N.times do
    x, y, z = gets.split.map(&:to_i)
    for j in 0..7 do
      num = x * (-1) ** j + y * (-1) ** (j / 2) + z * (-1) ** (j / 4)
      if num > arr[j][M-1]
        arr[j].pop
        k = M - 2
        while k > 0 && num > arr[j][k-1]
          k -= 1
        end
        arr[j].insert(k, num)
      end
    end
  end
  ans = []
  arr.each {|nums| ans += [nums.inject(&:+)]}
  puts ans.max
else
  N.times{gets}
  puts 0
end


n, m = gets.strip.split.map(&:to_i)
cakes = []

n.times do
    cakes << gets.strip.split.map(&:to_i)
end

patterns = [
    [+1, +1, +1],
    [+1, +1, -1],
    [+1, -1, +1],
    [+1, -1, -1],
    [-1, +1, +1],
    [-1, +1, -1],
    [-1, -1, +1],
    [-1, -1, -1],
]

mxs = []

patterns.each do |p|
    score = cakes.map.with_index { |cake, i| [i, cake[0] * p[0] + cake[1] * p[1] + cake[2] * p[2]] }
    ranking = score.sort_by { |s| s[1] }.reverse
    leaders = []
    m.times do |i|
        leaders << cakes[ranking[i][0]]
    end
    total = leaders.transpose.map { |row| row.inject(:+) }.map(&:abs).inject(:+)
    mxs << total
end

puts mxs.max


n, m = gets.split(" ").map{|v|v.to_i}
cakes = Array.new(8) {|i| Array.new }
n.times{|i|
  x, y, z = gets.split(" ").map{|v|v.to_i}
  cakes[0] << (x + y + z)
  cakes[1] << (-x + y + z)
  cakes[2] << (x - y + z)
  cakes[3] << (-x - y + z)
  cakes[4] << (x + y - z)
  cakes[5] << (-x + y - z)
  cakes[6] << (x - y - z)
  cakes[7] << (-x - y - z)
}

max = 0
cakes.each{|c|
  c.sort!{|a, b|
    v = 0 if a == b
    v = 1 if a < b
    v = -1 if a > b
    v
  }
  max = [max, c[0, m].inject(:+)].max
}
puts max


n=gets.to_i
if n>=1000
  printf("ABD%03d\n",n-999)
else
  printf("ABC%03d\n",n)
end

Score : 100 points

Problem Statement

Decades have passed since the beginning of AtCoder Beginner Contest.

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

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

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

Constraints

1 \leq N \leq 1998

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

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

Sample Input 1

999

Sample Output 1

ABC

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

Sample Input 2

1000

Sample Output 2

ABD

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

Sample Input 3

1481

Sample Output 3

ABD

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


a, b = gets.split.map(&:to_i)

c = b - a - 1
puts c * (c + 1) / 2 - a

Score : 200 points

Problem Statement

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

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

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

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

Constraints

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

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

a b

Output

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

Sample Input 1

8 13

Sample Output 1

2

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

Sample Input 2

54 65

Sample Output 2

1


N = gets.to_i
r = N

def calc(r, i)
  if r < 6
    return [r, i]
  end

  j = 0
  v = 1
  while r >= v
    j += 1
    v = 6 ** j
  end

  result = []
  result << calc(r - 6 ** (j - 1), i + 1)

  if r >= 9
    j = 0
    v = 1
    while r >= v
      j += 1
      v = 9 ** j
    end

    result << calc(r - 9 ** (j - 1), i + 1)
  end

  result
end

d = calc(r, 0).flatten
result = []
0.step(d.size - 1, 2) do |i|
  result << d[i + 1] + d[i]
end
p result.min

Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16


n = gets.to_i
ans = []
(2..n).each do |a|
  b = n - a
  sum_a = a.to_s.split('').map{|i| i.to_i}.inject(&:+)
  sum_b = b.to_s.split('').map{|i| i.to_i}.inject(&:+)

  ans << (sum_a + sum_b)
end
p ans.min()

Score : 200 points

Problem Statement

Takahashi has two positive integers A and B.

It is known that A plus B equals N.
Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).

Constraints

2 ≤ N ≤ 10^5

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B".

Sample Input 1

15

Sample Output 1

6

When A=2 and B=13, the sums of their digits are 2 and 4, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10


a,b = gets.chomp.split.map(&:to_i)
puts [a+b,a-b,a*b].max

Score : 100 points

Problem Statement

You are given two integers A and B.
Find the largest value among A+B, A-B and A \times B.

Constraints

-1000 \leq A,B \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

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

Sample Input 1

3 1

Sample Output 1

4

3+1=4, 3-1=2 and 3 \times 1=3. The largest among them is 4.

Sample Input 2

4 -2

Sample Output 2

6

The largest is 4 - (-2) = 6.

Sample Input 3

0 0

Sample Output 3

0


Score : 200 points

Problem Statement

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

Constraints

2 \leq N \leq 100

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

6
aabbca

Sample Output 1

2

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

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

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

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9


n = gets.to_i
s = gets.chomp

ans = 0
n.times do |i|
    s1 = s[0..i]
    s2 = s[(i+1)...n]
    hoge = (s1.split('') & s2.split('')).uniq
    ans = [ans, hoge.size].max
end
p ans


n = gets.to_i
s = gets.chomp.split('').map &:to_s

$w_rui = [0]
$e_rui = [0]
(1..n).each do |i|
  $w_rui.push s[i-1] === 'W' ? $w_rui[-1] + 1 : $w_rui[-1]
  $e_rui.unshift s[n-i] === 'E' ? $e_rui[0] + 1 : $e_rui[0]
end

puts [$w_rui[0, n] , $e_rui[1, n+1]].transpose.map{|x| x.sum}.min

Score : 300 points

Problem Statement

There are N people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string S of length N.
The i-th person from the west is facing east if S_i = E, and west if S_i = W.

You will appoint one of the N people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

|S| = N

S_i is E or W.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is 1 in this case.
It is not possible to have 0 people who have to change their directions, so the answer is 1.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3


n = gets.to_i
s = gets.chomp
min = n
w = s.scan(/W/).size
e = n - w
l = 0
(0...n).each do |x|
  if s[x] == 'W'
    l += 1
    w -= 1
  else
    e -= 1
  end
  m = (s[x] == 'W') ? l+e-1 : l+e
  min = m if min > m
end
puts min


array = gets.split(" ").map(&:to_i)
p1 = array[0] - array[1]
p2 = array[1] - array[0]
if array[3].even? && p1 < 1000000000000000000
  puts p1
elsif array[3].odd? && p2 < 1000000000000000000
  puts p2
else
  puts 'Unfair'
end

Score : 300 points

Problem Statement

Takahashi, Nakahashi and Hikuhashi have integers A, B and C, respectively.
After repeating the following operation K times, find the integer Takahashi will get minus the integer Nakahashi will get:

Each of them simultaneously calculate the sum of the integers that the other two people have, then replace his own integer with the result.

However, if the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Constraints

1 \leq A,B,C \leq 10^9

0 \leq K \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C K

Output

Print the integer Takahashi will get minus the integer Nakahashi will get, after repeating the following operation K times.
If the absolute value of the answer exceeds 10^{18}, print Unfair instead.

Sample Input 1

1 2 3 1

Sample Output 1

1

After one operation, Takahashi, Nakahashi and Hikuhashi have 5, 4 and 3, respectively. We should print 5-4=1.

Sample Input 2

2 3 2 0

Sample Output 2

-1

Sample Input 3

1000000000 1000000000 1000000000 1000000000000000000

Sample Output 3

0


a, b, c, k = STDIN.gets.split.map(&:to_i)

if a == b && b == c && c == a
  puts 0
end

k.times do
  na = b + c
  nb = a + c
  nc = a + b
  a, b, c = na, nb, nc
  if a - b > 10**18
    puts 'Unfair'
  end
end

puts a - b


require 'pp'
a, b, c, k = gets.chomp.split(" ").map(&:to_i)

x = a - b
if x > 10 ** 18 || x < - (10 ** 18)
  puts 'Unfair'
elsif k.even?
  puts x
else
  puts -x
end


def ascan; gets.split.map(&:to_i);end

A,B,C,K = ascan

u = A-B

u=-u if K.odd?

p u


#prime_divisionを用いた。
require "prime"
x = gets.chomp.to_i
x.downto (1) do |i|
    ans = i.prime_division
    size = ans.size
    count = 0
    if size == 1 && ans[0][1] != 1 && x >= 4
        puts i
        break
    elsif size >= 2
        count = 0
        me = ans[0][1]
        ans.each do |i|
            if me == i[1] && me != 1
                count += 1
            end
        end
        if count == size
            puts i
            break
        end
    elsif x < 4
        puts "1"
        break
    end
end

Score : 200 points

Problem Statement

You are given a positive integer X.
Find the largest perfect power that is at most X.
Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.

Constraints

1 ≤ X ≤ 1000

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the largest perfect power that is at most X.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most 10: 1, 4, 8 and 9.
We should print the largest among them, 9.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961


#!/usr/bin/ruby
#encoding: utf-8

x = gets.to_i
max = 0

(1..x).each do |i|
  (2..10).each do |j|
    a = i ** j
    if a <= x
      max = [max,a].max
    end
  end
end

puts max


x = gets.to_i
max = 1

(1..x).each do |i|
	(2..x).each do |j|
		num = i ** j
		if num <= x
			max = num if num > max
		else
			break
		end
	end
end

puts max


x = gets.to_i

ps = [2]

(3..31).each do |n|
  if ps.all? {|p| n%p != 0}
    ps << n
  end
end

ns = [1]

ps.each do |b|
  p = 2
  while b**p <= 1000
    ns << b**p
    p += 1
  end
end

ns = ns.sort

(0..ns.length-1).each do |i|
  if x < ns[i]
    p ns[i-1]
    exit 0
  end
end


x = gets.to_i

x.downto(1) do |i|
    2.upto(i) do |j|
        if i % j == 0
            y = i
            cnt = 0
            while y % j == 0
                y /= j
                cnt += 1
            end
            if y == 1 && cnt > 1
                puts i
                exit
            end
        end
    end
end


require 'set'
s = gets.chomp.chars
K = gets.to_i

set = SortedSet.new()
used = {}
(0...(s.size)).each do |i|
  (i...(s.size)).each do |j|
    subs = s[i..j]
    set.add(subs)
  end
end
puts set.to_a[K - 1].join('')

Score : 300 points

Problem Statement

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

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

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

Constraints

1 ≤ |s| ≤ 5000

s consists of lowercase English letters.

1 ≤ K ≤ 5

s has at least K different substrings.

Partial Score

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

Input

Input is given from Standard Input in the following format:

s
K

Output

Print the K-th lexicographically smallest substring of K.

Sample Input 1

aba
4

Sample Output 1

b

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

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z


gets
ps = [0] + gets.split.map(&:to_i)
xys = $stdin.read.split

h = {}
xys.each_slice(2) do |xs,ys|
  x = xs.to_i
  y = ys.to_i
  h[x] ||= []
  h[x] << y
  h[y] ||= []
  h[y] << x
end

used = {}
ret = 0
h.each do |k,v|
  next if used[k]
  b = v
  lused = {}
  lused[k] = 1
  until b.empty?
    b.each do |n|
      lused[n] = 1
    end
    b = b.flat_map {|n| h[n] || []}.uniq.reject {|n| lused[n]}
  end
  used.merge!(lused)

  ret += lused.keys.count {|n| lused[ps[n]]}
end

1.upto(ps.length-1) do |i|
  ret += 1 if !used[i] && ps[i] == i
end

p ret

Score : 400 points

Problem Statement

We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N.
We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M).
AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N) such that p_i = i is maximized:

Choose j such that 1 ≤ j ≤ M, and swap p_{x_j} and p_{y_j}.

Find the maximum possible number of i such that p_i = i after operations.

Constraints

2 ≤ N ≤ 10^5

1 ≤ M ≤ 10^5

p is a permutation of integers from 1 through N.

1 ≤ x_j,y_j ≤ N

x_j ≠ y_j

If i ≠ j, \{x_i,y_i\} ≠ \{x_j,y_j\}.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
p_1 p_2 .. p_N
x_1 y_1
x_2 y_2
:
x_M y_M

Output

Print the maximum possible number of i such that p_i = i after operations.

Sample Input 1

5 2
5 3 1 4 2
1 3
5 4

Sample Output 1

2

If we perform the operation by choosing j=1, p becomes 1 3 5 4 2, which is optimal, so the answer is 2.

Sample Input 2

3 2
3 2 1
1 2
2 3

Sample Output 2

3

If we perform the operation by, for example, choosing j=1, j=2, j=1 in this order, p becomes 1 2 3, which is obviously optimal.
Note that we may choose the same j any number of times.

Sample Input 3

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

Sample Output 3

8

Sample Input 4

5 1
1 2 3 4 5
1 5

Sample Output 4

5

We do not have to perform the operation.


class Unionfind
  attr_accessor(:par, :size)

  def initialize(n)
    @par = Array.new(n+1)
    (n+1).times do |i|
      @par[i] = i
    end
    @size = Array.new(n+1,1)
  end

  def root(x)
    while @par[x] != x
      x = @par[@par[x]]
      @par[x] = @par[@par[x]]
    end
    x
  end

  def unite(x,y)
    rx = root(x)
    ry = root(y)
    if rx != ry
      @size[ry] += size(rx)
      @par[rx] = ry
    end
  end

  def same(x,y)
    return root(x)==root(y)
  end

  def size(x)
    if @par[x] == x
      @size[x]
    else
      size(root(par[x]))
    end
  end

end

n,m = gets.chomp.split(" ").map(&:to_i)
p = gets.chomp.split(" ").map(&:to_i)
x = []
y = []
tree = Unionfind.new(n)
m.times do |i|
  x,y = gets.chomp.split(" ").map(&:to_i)
  tree.unite(x,y)
end
cnt = 0
1.upto(n) do |i|
  if i == p[i]
    cnt += 1
  elsif tree.same(p[i-1],i)
    cnt += 1
  end
end
puts cnt


require 'pp'
# IS_DEBUG = true
IS_DEBUG = false
def dputs str
	if(IS_DEBUG)
		puts str
	end
end
def dpp str
	if(IS_DEBUG)
		pp str
	end
end

require 'pp'

INT_MAX = 999999999999999999999999

N,M=gets.chomp.split(' ').map{|n| n.to_i}
P=[nil] + gets.chomp.split(' ').map{|n| n.to_i}
dpp P
X = Array.new(M)
0.upto(M-1){|d|
	X[d]=gets.chomp.split(' ').map{|n| n.to_i}
}

# flat array

class Sarr
	def initialize(m)
		@S = Array.new(m) { nil }
		@next_i = 0
		@index = []
	end
	def s_index(n)
		@S[n]
		# return nil
	end
	# index
	def s_merge(n,m)
		if(n > m)
			tmp = n
			n = m
			m = tmp
		end
		@S.map!{|i|
			if(i==m)
				n
			else
				i
			end
		}
		@index.delete(m)
	end
	def s_add(n)
		@S[n] = @next_i
		@index << @next_i
		@next_i += 1
		return @next_i - 1
	end
	def s_i_add(n,i)
		@S[n]=i
	end
	def getS
		@S
	end
	def getnexti
		@next_i
	end
	def connect(x,y)
		dpp @S
		sx_index = s_index(x)
		dputs "sx_index is #{sx_index}"
		if(sx_index.nil?)
			sx_index = s_add(x)
		else
			# ok
		end
		sy_index = s_index(y)
		if(sy_index.nil?)
			sy_index = sx_index
			s_i_add(y,sx_index)
		else
			if(sx_index == sy_index)
				# ok
			else
				s_merge(sx_index,sy_index)
			end
		end
	end
	def reindex
		reverse_index_map = {}
		@index.sort.each_with_index{|old_i, new_i|
			reverse_index_map[old_i] = new_i
		}
		@S.map{|si|
			if(si.nil?)
				nil
			else
				reverse_index_map[si]
			end
		}
	end
end

sarr = Sarr.new(N)

X.each{|x,y|
	sarr.connect(x,y)
}

sarr.reindex

s = sarr.getS
dpp s
num_si = s.compact.max
dpp num_si
ss = Array.new(num_si+1){[]}

s.each_with_index{|si,i|
	if(! si.nil?)
		ss[si] << i
	end
}
dpp ss
sum = 0
ss.each{|set|
	setp = {}
	set.each{|i|
		setp[P[i]] = P[i]
	}
	dputs "set, setp is"
	dpp set
	dpp setp
	set.each{|i|
		if(! setp[i].nil?)
			sum += 1
		end
	}
}
dputs "appeared sum is #{sum}"
s.each_with_index{|si,i|
	if(si.nil? && P[i] == i)
		sum += 1
		dputs "hit"
	end
}

puts sum


a, b = gets.strip.split.map(&:to_i)

if a <= b
  puts a
else
  puts a - 1
end

Score: 100 points

Problem Statement

In AtCoder Kingdom, Gregorian calendar is used, and dates are written in the "year-month-day" order, or the "month-day" order without the year.

For example, May 3, 2018 is written as 2018-5-3, or 5-3 without the year.

In this country, a date is called Takahashi when the month and the day are equal as numbers. For example, 5-5 is Takahashi.

How many days from 2018-1-1 through 2018-a-b are Takahashi?

Constraints

a is an integer between 1 and 12 (inclusive).

b is an integer between 1 and 31 (inclusive).

2018-a-b is a valid date in Gregorian calendar.

Input

Input is given from Standard Input in the following format:

a b

Output

Print the number of days from 2018-1-1 through 2018-a-b that are Takahashi.

Sample Input 1

5 5

Sample Output 1

5

There are five days that are Takahashi: 1-1, 2-2, 3-3, 4-4 and 5-5.

Sample Input 2

2 1

Sample Output 2

1

There is only one day that is Takahashi: 1-1.

Sample Input 3

11 30

Sample Output 3

11

There are eleven days that are Takahashi: 1-1, 2-2, 3-3, 4-4, 5-5, 6-6, 7-7, 8-8, 9-9, 10-10 and 11-11.


a,b = gets.split.map(&:to_i)
if b >= a
    puts a
else
    puts a - 1
end


a, b, c = gets.split.map(&:to_i)
k = gets.chomp.to_i
m = [a, b, c].max
r = [a, b, c] - [m]
puts m * 2 ** k + r.first + r.last

Score: 200 points

Problem Statement

There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:

Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.

What is the largest possible sum of the integers written on the blackboard after K operations?

Constraints

A, B and C are integers between 1 and 50 (inclusive).

K is an integer between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

A B C
K

Output

Print the largest possible sum of the integers written on the blackboard after K operations by E869220.

Sample Input 1

5 3 11
1

Sample Output 1

30

In this sample, 5, 3, 11 are initially written on the blackboard, and E869120 can perform the operation once.

There are three choices:

Double 5: The integers written on the board after the operation are 10, 3, 11.

Double 3: The integers written on the board after the operation are 5, 6, 11.

Double 11: The integers written on the board after the operation are 5, 3, 22.

If he chooses 3., the sum of the integers written on the board afterwards is 5 + 3 + 22 = 30, which is the largest among 1. through 3.

Sample Input 2

3 3 4
2

Sample Output 2

22

E869120 can perform the operation twice. The sum of the integers eventually written on the blackboard is maximized as follows:

First, double 4. The integers written on the board are now 3, 3, 8.

Next, double 8. The integers written on the board are now 3, 3, 16.

Then, the sum of the integers eventually written on the blackboard is 3 + 3 + 16 = 22.


m = gets.split.map(&:to_i)
k = gets.to_i
puts  m.sum + (2*k-1)*m.max


array = gets.chop.split.map(&:to_i)
k = gets.chop.to_i
sum = 0
m = array.sort.max
(0..k).each do | i |
  m *= 2
end
array[0] = m
array.each do |n|
  sum += n
end
puts sum


h,w = gets.strip.split.map(&:to_i)
data = []
ay = Array.new(w+2,".")
data << ay.join("").to_s
h.times do
  ax = gets.strip.to_s
  data << "."+ax+"."
end
data << ay.join("").to_s

outcount = 0
#とにかく離れ小島が一個でもあればダメ
for i in 1..h
  for j in 1..w
    if data[i][j]=="#"
      if data[i-1][j]=="." && data[i+1][j]=="." && data[i][j-1]=="." && data[i][j+1]=="."
        outcount += 1
      end
    end
  end
end
if outcount != 0
  puts "No"
else
  puts "Yes"
end

Score: 300 points

Problem Statement

We have a canvas divided into a grid with H rows and W columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j).

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square (i, j) black when s_{i, j}= #, and to make Square (i, j) white when s_{i, j}= ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

H is an integer between 1 and 50 (inclusive).

W is an integer between 1 and 50 (inclusive).

For every (i, j) (1 \leq i \leq H, 1 \leq j \leq W), s_{i, j} is # or ..

Input

Input is given from Standard Input in the following format:

H W
s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}
s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}
: :
s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

5 5
#.#.#
.#.#.
#.#.#
.#.#.
#.#.#

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes


h, w = gets.split.map(&:to_i)

maze = []
h.times do
  maze << gets.chomp
end
ans = 'No'
(0..h-1).each do |j|
  (0..w-1).each do |i|
    if maze[j][i] == "#"
      if j-1 >=0 && maze[j-1][i] == "#" ||
        j+1 < h && maze[j+1][i] == "#" ||
        i-1 >=0 && maze[j][i-1] == "#" ||
        i+1 < w && maze[j][i+1] == "#"
        ans = 'Yes'
      else
        ans = 'No'
      end
    end
  end
end
puts ans


h, w = gets.split.map(&:to_i)
c = []
h.times{|i| c << gets.split('') }

h.times do |x|
  w.times do |y|
    next if c[x][y] != '#'
    next if x > 1     && c[x-1][y] == '#'
    next if x < h - 1 && c[x+1][y] == '#'
    next if y > 1     && c[x][y-1] == '#'
    next if y < w - 1 && c[x][y+1] == '#'

    puts "No"
    exit
  end
end

puts 'Yes'


# util functions
class UnionFind
  def initialize(n) # n: number of elements in the forest
    @par  = []
    @rank = []
    @vs   = []
    n.times do |i|
      @par[i] = i
      @rank[i] = 0
      @vs[i] = 1
    end
  end
  attr_accessor :par, :rank, :vs

  def find(x)
    raise "x = #{x} is out of range 0..#{@par.size - 1}" unless @par[x]
    if @par[x] == x
      return x
    else
      return find( @par[x] )
    end
  end

  def unite( x, y )
    xrt = find(x)
    yrt = find(y)
    return if xrt == yrt

    if @rank[xrt] > @rank[yrt]
      @par[yrt] = xrt
      @vs[xrt] += @vs[yrt]
    else
      @par[xrt] = yrt
      @vs[yrt] += @vs[xrt]
      @rank[yrt] += 1 if @rank[xrt] == @rank[yrt]
    end
  end

  def same( x, y ) # returns true/false
    return find( x ) == find( y )
  end

end # UnionFind

# debug
$debugFlag = ( ARGV[0] != nil )
p "==== DEBUG MODE ====" if $debugFlag

def pd(str)
  p str if $debugFlag
end

def printd(str)
  print str if $debugFlag
end

# input
inputs = []
lc = 0
while l = $stdin.gets do
  if false
    inputs << l.chomp.split(" ").map(&:to_s)
  else
    inputs << l.chomp.split(" ").map(&:to_i)
  end
  lc += 1
end

# input check
if $debugFlag
  p "--- INPUT (begin) ---"
  inputs.each do |l_i|
    p l_i
  end
  p "--- INPUT (end) ---"
  print "\n"
end

nn = inputs[0][0]
$lst = inputs[1]

# body
if $debugFlag
end

nn = inputs[0][0]

arr = [11, 31, 41, 61, 71, 101, 131, 151, 181, 191, 211, 241, 251, 271, 281, 311, 331, 401, 421, 431, 461, 491, 521, 541, 571, 601, 631, 641, 661, 691, 701, 751, 761, 811, 821, 881, 911, 941, 971, 991, 1021, 1031, 1051, 1061, 1091, 1151, 1171, 1181, 1201, 1231, 1291, 1301, 1321, 1361, 1381]

for i in 0..nn-1
  print "#{arr[i]} "
end
print "\n"

Score: 400 points

Problem Statement

Print a sequence a_1, a_2, ..., a_N whose length is N that satisfies the following conditions:

a_i (1 \leq i \leq N) is a prime number at most 55 555.

The values of a_1, a_2, ..., a_N are all different.

In every choice of five different integers from a_1, a_2, ..., a_N, the sum of those integers is a composite number.

If there are multiple such sequences, printing any of them is accepted.

Notes

An integer N not less than 2 is called a prime number if it cannot be divided evenly by any integers except 1 and N, and called a composite number otherwise.

Constraints

N is an integer between 5 and 55 (inclusive).

Input

Input is given from Standard Input in the following format:

N

Output

Print N numbers a_1, a_2, a_3, ..., a_N in a line, with spaces in between.

Sample Input 1

5

Sample Output 1

3 5 7 11 31

Let us see if this output actually satisfies the conditions.

First, 3, 5, 7, 11 and 31 are all different, and all of them are prime numbers.

The only way to choose five among them is to choose all of them, whose sum is a_1+a_2+a_3+a_4+a_5=57, which is a composite number.

There are also other possible outputs, such as 2 3 5 7 13, 11 13 17 19 31 and 7 11 5 31 3.

Sample Input 2

6

Sample Output 2

2 3 5 7 11 13

2, 3, 5, 7, 11, 13 are all different prime numbers.

2+3+5+7+11=28 is a composite number.

2+3+5+7+13=30 is a composite number.

2+3+5+11+13=34 is a composite number.

2+3+7+11+13=36 is a composite number.

2+5+7+11+13=38 is a composite number.

3+5+7+11+13=39 is a composite number.

Thus, the sequence 2 3 5 7 11 13 satisfies the conditions.

Sample Input 3

8

Sample Output 3

2 5 7 13 19 37 67 79


n = gets.to_i
strings = []
n.times { strings << gets.chomp.split("") }
count = 0
n.times do
  symmetry = true
  (0...n).each do |h|
    (0...n).each do |w|
      if strings[h][w] != strings[w][h]
        symmetry = false
        break
      end
    end
  end
  count += 1 if symmetry
  strings.each { |string| string.rotate! }
end
puts count * n

Score : 500 points

Problem Statement

Snuke has two boards, each divided into a grid with N rows and N columns.
For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j).

There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i,j}. On the second board, nothing is written yet.

Snuke will write letters on the second board, as follows:

First, choose two integers A and B ( 0 \leq A, B < N ).

Write one letter in each square on the second board.
Specifically, write the letter written in Square ( i+A, j+B ) on the first board into Square (i,j) on the second board.
Here, the k-th row is also represented as the (N+k)-th row, and the k-th column is also represented as the (N+k)-th column.

After this operation, the second board is called a good board when, for every i and j ( 1 \leq i, j \leq N ), the letter in Square (i,j) and the letter in Square (j,i) are equal.

Find the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Constraints

1 \leq N \leq 300

S_{i,j} ( 1 \leq i, j \leq N ) is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}S_{1,2}..S_{1,N}
S_{2,1}S_{2,2}..S_{2,N}
:
S_{N,1}S_{N,2}..S_{N,N}

Output

Print the number of the ways to choose integers A and B ( 0 \leq A, B < N ) such that the second board is a good board.

Sample Input 1

2
ab
ca

Sample Output 1

2

For each pair of A and B, the second board will look as shown below:

The second board is a good board when (A,B) = (0,1) or (A,B) = (1,0), thus the answer is 2.

Sample Input 2

4
aaaa
aaaa
aaaa
aaaa

Sample Output 2

16

Every possible choice of A and B makes the second board good.

Sample Input 3

5
abcde
fghij
klmno
pqrst
uvwxy

Sample Output 3

0

No possible choice of A and B makes the second board good.


Score : 100 points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs 700 yen (the currency of Japan), plus 100 yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string S. S is three characters long, and if the first character in S is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in S mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when S is given, prints the price of the corresponding bowl of ramen.

Constraints

S is a string of length 3.

Each character in S is o or x.

Input

Input is given from Standard Input in the following format:

S

Output

Print the price of the bowl of ramen corresponding to S.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is 700 + 100 \times 2 = 900 yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is 700 + 100 \times 3 = 1000 yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is 700 yen.


# frozen_string_literal: true

# Generated by AtcoderGreedy on 2018-04-22
# ABC095 C
# Your code here

$A, $B, $C, $X, $Y = gets.chomp.split(' ').map(&:to_i)

def min(a, b)
  a < b ? a : b
end

def min_3(a, b, c)
  min(min(a, b), c)
end

res = if $X < $Y
        min_3($Y * 2 * $C, $A * $X + $B * $Y, $X * 2 * $C + ($Y - $X) * $B)
      else
        min_3($X * 2 * $C, $A * $X + $B * $Y, $Y * 2 * $C + ($X - $Y) * $A)
      end

puts res

Score : 300 points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare X A-pizzas and Y B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

1 ≤ A, B, C ≤ 5000

1 ≤ X, Y ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C X Y

Output

Print the minimum amount of money required to prepare X A-pizzas and Y B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy 200000 AB-pizzas and rearrange them into 100000 A-pizzas and 100000 B-pizzas. We will have 10000 more A-pizzas than necessary, but that is fine.


a, b ,x = gets.chomp.split(" ").map(&:to_i)
if a + b >= x && b <= x
    puts "YES"
else
    puts "NO"
end

Score : 100 points

Problem Statement

There are a total of A + B cats and dogs.
Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs.

Determine if it is possible that there are exactly X cats among these A + B animals.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

1 \leq X \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B X

Output

If it is possible that there are exactly X cats, print YES; if it is impossible, print NO.

Sample Input 1

3 5 4

Sample Output 1

YES

If there are one cat and four dogs among the B = 5 animals, there are X = 4 cats in total.

Sample Input 2

2 2 6

Sample Output 2

NO

Even if all of the B = 2 animals are cats, there are less than X = 6 cats in total.

Sample Input 3

5 3 2

Sample Output 3

NO

Even if all of the B = 3 animals are dogs, there are more than X = 2 cats in total.


a,b,c = gets.split.map(&:to_i)
if a + b > c && a <= c
    puts "Yes"
else
    puts "No"
end


N, M, X = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)

s = t = 0
A.each{ |a| a < X ? s += 1 : t += 1 }

puts [s, t].min

Score : 200 points

Problem Statement

There are N + 1 squares arranged in a row, numbered 0, 1, ..., N from left to right.

Initially, you are in Square X.
You can freely travel between adjacent squares. Your goal is to reach Square 0 or Square N.
However, for each i = 1, 2, ..., M, there is a toll gate in Square A_i, and traveling to Square A_i incurs a cost of 1.
It is guaranteed that there is no toll gate in Square 0, Square X and Square N.

Find the minimum cost incurred before reaching the goal.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

1 \leq X \leq N - 1

1 \leq A_1 < A_2 < ... < A_M \leq N

A_i \neq X

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M X
A_1 A_2 ... A_M

Output

Print the minimum cost incurred before reaching the goal.

Sample Input 1

5 3 3
1 2 4

Sample Output 1

1

The optimal solution is as follows:

First, travel from Square 3 to Square 4. Here, there is a toll gate in Square 4, so the cost of 1 is incurred.

Then, travel from Square 4 to Square 5. This time, no cost is incurred.

Now, we are in Square 5 and we have reached the goal.

In this case, the total cost incurred is 1.

Sample Input 2

7 3 2
4 5 6

Sample Output 2

0

We may be able to reach the goal at no cost.

Sample Input 3

10 7 5
1 2 3 4 6 8 9

Sample Output 3

3


n, m, x = gets.chomp.split(" ").map(&:to_i)
a = gets.chomp.split(" ").map(&:to_i)

left = 0
right = 0

a.each do |i|
  if i < x
    left+=1
  else
    right+=1
  end
end

if left < right
  puts left
else
  puts right
end


n = gets.chomp.split(" ").map(&:to_i)
x = gets.chomp.split(" ").map(&:to_i)

x.length.times do |c|
  selected = x.each_with_index.select{|v,i|i!=c}
  selected.map! do |v|
    v[0]
  end
  selected.sort!
  puts selected[(n[0]+1)/2-1]
end

Score : 300 points

Problem Statement

When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.

You are given N numbers X_1, X_2, ..., X_N, where N is an even number.
For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N be B_i.

Find B_i for each i = 1, 2, ..., N.

Constraints

2 \leq N \leq 200000

N is even.

1 \leq X_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X_1 X_2 ... X_N

Output

Print N lines.
The i-th line should contain B_i.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of X_2, X_3, X_4 is 4, B_1 = 4.

Since the median of X_1, X_3, X_4 is 3, B_2 = 3.

Since the median of X_1, X_2, X_4 is 3, B_3 = 3.

Since the median of X_1, X_2, X_3 is 4, B_4 = 4.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4


N = gets.chomp.to_i
nums = gets.chomp.split(' ').map(&:to_i)
sorted = nums.sort
deleted = {}
for i in 1..N do
  a = sorted.clone
  delete = nums[i - 1]
  if deleted.has_key? delete
    puts deleted[delete]
    break
  end
  a.each_with_index do |val, index|
    if val == delete
      a.delete_at index
      break
    end
  end
  deleted[delete.to_s] = a[(a.count + 1)/2 - 1]
  puts a[(a.count + 1)/2 - 1]
end


n = gets.chomp.to_i
a = gets.chomp.split(" ").map(&:to_i).sort
if n == 2
    puts a[1].to_s + " " + a[0].to_s
    exit
end
mid = a.size / 2
puts [a[-1], a[mid]].join(" ")

Score : 400 points

Problem Statement

Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order.
From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized.
If there are multiple pairs that maximize the value, any of them is accepted.

Constraints

2 \leq n \leq 10^5

0 \leq a_i \leq 10^9

a_1,a_2,...,a_n are pairwise distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

n
a_1 a_2 ... a_n

Output

Print a_i and a_j that you selected, with a space in between.

Sample Input 1

5
6 9 4 2 11

Sample Output 1

11 6

\rm{comb}(a_i,a_j) for each possible selection is as follows:

\rm{comb}(4,2)=6

\rm{comb}(6,2)=15

\rm{comb}(6,4)=15

\rm{comb}(9,2)=36

\rm{comb}(9,4)=126

\rm{comb}(9,6)=84

\rm{comb}(11,2)=55

\rm{comb}(11,4)=330

\rm{comb}(11,6)=462

\rm{comb}(11,9)=55

Thus, we should print 11 and 6.

Sample Input 2

2
100 0

Sample Output 2

100 0


A,B,K=gets.split.map &:to_i
puts (K.times.map{|i|A+i} | K.downto(1).map{|i|B-i+1}).select{|i|i>=A&&i<=B}

Score : 200 points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between A and B (inclusive), it is either within the K smallest integers or within the K largest integers.

Constraints

1 \leq A \leq B \leq 10^9

1 \leq K \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B K

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

3 is the first smallest integer among the integers between 3 and 8.

4 is the second smallest integer among the integers between 3 and 8.

7 is the second largest integer among the integers between 3 and 8.

8 is the first largest integer among the integers between 3 and 8.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9


a,b,k = gets.split(" ").map!{|i| i.to_i}
if a+k-1 < b-k+1
  a.upto(a+k-1) do |j|
    puts j
  end
  (b-k+1).upto(b) do |l|
    puts l
  end
else a.upto(b) do |u|
    puts u
  end
end


s = gets.chomp.chars
hs = Hash.new(false)
n = s.size

if n < 26
  s.each do |c|
    hs[c] = true
  end
  lb = "a"
else
  cur = "a"
  while !s.empty? && s[-1] >= cur
    hs[s[-1]] = true
    cur = s.pop
  end

  if s.empty?
    puts "-1"
    exit
  end
  lb = (s.pop.ord + 1).chr
end

(lb.."z").each do |c|
  if hs[c] == (n >= 26)
    puts s.join("") + c
    break
  end
end

Score : 300 points

Problem Statement

Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.

A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, atcoder, zscoder and agc are diverse words while gotou and connect aren't diverse words.

Given a diverse word S, determine the next word that appears after S in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than S, or determine that it doesn't exist.

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

Constraints

1 \leq |S| \leq 26

S is a diverse word.

Input

Input is given from Standard Input in the following format:

S

Output

Print the next word that appears after S in the dictionary, or -1 if it doesn't exist.

Sample Input 1

atcoder

Sample Output 1

atcoderb

atcoderb is the lexicographically smallest diverse word that is lexicographically larger than atcoder. Note that atcoderb is lexicographically smaller than b.

Sample Input 2

abc

Sample Output 2

abcd

Sample Input 3

zyxwvutsrqponmlkjihgfedcba

Sample Output 3

-1

This is the lexicographically largest diverse word, so the answer is -1.

Sample Input 4

abcdefghijklmnopqrstuvwzyx

Sample Output 4

abcdefghijklmnopqrstuvx