Petya loves computer games. Finally a game that he's been waiting for so long came out!The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values of  for all i from 1 to n. The expression ⌊ x⌋ denotes the result of rounding the number x down to the nearest integer.At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.

The first line of the input contains two positive integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 107) — the number of skills of the character and the number of units of improvements at Petya's disposal. The second line of the input contains a sequence of n integers ai (0 ≤ ai ≤ 100), where ai characterizes the level of the i-th skill of the character.

The first line of the output should contain a single non-negative integer — the maximum total rating of the character that Petya can get using k or less improvement units.

NoteIn the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to  lfloor frac{100}{10} rfloor +  lfloor frac{100}{10} rfloor = 10 + 10 =  20.In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is .In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to .

#!/usr/bin/ruby
n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i).sort_by{|e|0-e%10}
a.size.times{|i|
	y=10-a[i]%10
	next if y==10
	x=[y,k].min
	a[i]+=x
	k-=x
}
a.size.times{|i|
	y=100-a[i]
	next if y==0
	x=[y,k].min
	a[i]+=x
	k-=x
}
p a.map{|e|e/10}.reduce(:+)

# Codeforces Round

=begin
# A
a, b = gets.split.map(&:to_i)
c, d = [a, b].min, [a, b].max
puts "#{[a, b].min} #{(a - b).abs / 2}"

# B
n = gets.to_i
h = gets.split.map(&:to_i)
m, a = [0] * (n - 1) + [h[n - 1]], [0] * n
(n - 2).downto(0) do |i|
  if h[i] <= m[i + 1]
    m[i] = m[i + 1]
    a[i] = m[i] - h[i] + 1
  else
    m[i] = h[i]
  end
end
puts a.join(' ')
=end

# C
n, k = gets.split.map(&:to_i)
cmp = ->(x, y) { (y % 10) <=> (x % 10) }
a = gets.split.map(&:to_i).sort(&cmp).map do |x|
  if x % 10 == 0 || k == 0
    x
  else
    d = [10 - x % 10, k].min
    k -= d
    x += d
  end
end
ans = 0
a.each do |y|
  d = [100 - y, k].min
  k -= d
  ans += (y + d) / 10
end
puts ans

input = STDIN.gets
arr = input.split.map(&:to_i)
# всего навыков
n = arr[0]
# очки улучшений
k = arr[1]
# очков на одну способность, если поровну
# constant = (k / n).floor
# получаем все очки
input = STDIN.gets
abilities = input.split.map(&:to_i)
# создаем словарь
indexes = Hash.new

i = 0
# n шагов
abilities.each do |item|
  # заполняем словарь значениями
  indexes[i] = 10 - item % 10
  i += 1
end
# создаем ещё один словарь из первого
# отсортированный по значениям
# ? шагов - не знаю как сортировка устроена
sort =  Hash[indexes.sort_by{|k, v| v}]

# добавляем очки там, где их нужно меньше всего,
# чтобы "добить" до величины, кратной 10-ти
# ещё n шагов
sort.each do |key, value|
  if k - value >= 0
    abilities[key] += value
    k = k - value
  else
    break
  end
end

# если ещё остались очки - разбрасываем их по всем, добивая до 100 сколько
# сможем
if k > 0
  abilities.map! { |element|
    if k >= 100 - element
      k = k - (100 - element)
      100
    else
      prev_k = k
      k = 0
      element + prev_k
    end
  }
end

rating = 0
# финальный проход
# n шагов
abilities.each do |item|
  if item > 100
    item = 100
  end
  rating += (item * 0.1).floor
end

# Итого примерно
# 3n + ? шагов
# ? - сортировка
puts "#{rating}"

input = gets.chomp.split
n = Integer(input[0])
k = Integer(input[1])
input = gets.chomp.split
skills = []
for i in 0...n
    skills[i] = Integer(input[i])
end

sum = 0
sequence = []
skill = []
for i in 0...n
    if skills[i] == 100
        sum += 10
    else
        skill.push(skills[i])
    end
end
for i in 0...skill.length
    sequence[i] = []
    sequence[i][0] = skill[i] / 10
    sequence[i][1] = skill[i] % 10
end
sequence = sequence.sort{|x, y| y[1] <=> x[1]}
for i in 0...sequence.length
    if 10 - sequence[i][1] < k
        k -= 10 - sequence[i][1]
        sequence[i][1] = 10
    else
        sequence[i][1] += k
        k = 0
        break
    end
end
numbers = []
for i in 0...sequence.length
    numbers[i] = 10 * sequence[i][0] + sequence[i][1]
end
if k >= 10
    for i in 0...numbers.length
        if k >= 100 - numbers[i]
            k -= 100 - numbers[i]
            numbers[i] = 100
        else
            numbers[i] += k
            k = 0
            break
        end
    end
end

for i in 0...numbers.length
    sum += (numbers[i].to_f / 10).floor
end
puts sum

firstInput = gets.chomp.split(' ').map {|item| item.to_i}
skillNum, itemNum = firstInput[0], firstInput[1]
ans = 0
skillLevel = gets.chomp.split(' ').map {|item| item.to_i}
skillLevel.sort! {|a, b| b % 10 <=> a % 10}

10.times do |a|
index = 0
until itemNum == 0 || index == skillNum
	if skillLevel[index] == 100
		index += 1
		next
	end

	rest = 10 - (skillLevel[index] % 10)
	itemNum -= rest
	break if itemNum < 0
	skillLevel[index] += rest
	index += 1
end
end

skillLevel.each do |level|
	ans += (level / 10)
end

puts ans

input = STDIN.gets
arr = input.split.map(&:to_i)
# всего навыков
n = arr[0]
# очки улучшений
k = arr[1]
# очков на одну способность, если поровну
# constant = (k / n).floor
# получаем все очки
input = STDIN.gets
abilities = input.split.map(&:to_i)
# создаем словарь
indexes = Hash.new

i = 0
# n шагов
abilities.each do |item|
  # заполняем словарь значениями
  indexes[i] = 10 - item % 10
  i += 1
end
# создаем ещё один словарь из первого
# отсортированный по значениям
# ? шагов - не знаю как сортировка устроена
sort =  Hash[indexes.sort_by{|k, v| v}]

# добавляем очки там, где их нужно меньше всего,
# чтобы "добить" до величины, кратной 10-ти
# ещё n шагов
sort.each do |key, value|
  if k - value >= 0
    abilities[key] += value
    k = k - value
  else
    break
  end
end

# если ещё остались очки - разбрасываем их по всем, добивая до 100 сколько
# сможем
if k > 0
  abilities.map! { |element|
    if k >= 100 - element
      k = k - (100 - element)
      element = 100
    else
      element += k
      k = 0
    end
  }
end

rating = 0
# финальный проход
# n шагов
abilities.each do |item|
  if item > 100
    item = 100
  end
  rating += (item * 0.1).floor
end

# Итого примерно
# 3n + ? шагов
# ? - сортировка
puts "#{rating}"

input = STDIN.gets
arr = input.split.map(&:to_i)
# всего навыков
n = arr[0]
# очки улучшений
k = arr[1]
# очков на одну способность, если поровну
# constant = (k / n).floor
# получаем все очки
input = STDIN.gets
abilities = input.split.map(&:to_i)
# создаем словарь
indexes = Hash.new

i = 0
# n шагов
abilities.each do |item|
  # заполняем словарь значениями
  indexes[i] = 10 - item % 10
  i += 1
end
# создаем ещё один словарь из первого
# отсортированный по значениям
# ? шагов - не знаю как сортировка устроена
sort =  Hash[indexes.sort_by{|k, v| v}]

# добавляем очки там, где их нужно меньше всего,
# чтобы "добить" до величины, кратной 10-ти
# ещё n шагов
sort.each do |key, value|
  if k - value >= 0
    abilities[key] += value
    k = k - value
  else
    break
  end
end

# если ещё остались очки - разбрасываем их по всем, добивая до 100 сколько
# сможем
if k > 0
  abilities.map! { |element|
    if k >= 100 - element
      k = k - (100 - element)
      element = 100
    else
      element += k
      k = 0
    end
  }
end

puts "#{abilities}"
rating = 0
# финальный проход
# n шагов
abilities.each do |item|
  if item > 100
    item = 100
  end
  rating += (item * 0.1).floor
end

# Итого примерно
# 3n + ? шагов
# ? - сортировка
puts "#{rating}"

input = STDIN.gets
arr = input.split.map(&:to_i)
# всего навыков
n = arr[0]
# очки улучшений
k = arr[1]
# получаем все очки
input = STDIN.gets
abilities = input.split.map(&:to_i)
# создаем словарь
indexes = Hash.new

i = 0
# n шагов
abilities.each do |item|
  # заполняем словарь значениями
  indexes[i] = 10 - item % 10
  i += 1
end
# создаем ещё один словарь из первого
# отсортированный по значениям
# ? шагов - не знаю как сортировка устроена
sort =  Hash[indexes.sort_by{|k, v| v}]

# добавляем очки там, где их нужно меньше всего,
# чтобы "добить" до величины, кратной 10-ти
# ещё n шагов в пределе, хотя может и раньше закончиться
sort.each do |key, value|
  if k - value >= 0
    abilities[key] += value
    k = k - value
  else
    break
  end
end

rating = 0
# финальный проход
# n шагов
abilities.each do |item|
  rating += (item * 0.1).floor
end

# Итого примерно
# 3n + ? шагов
# ? - сортировка
puts "#{rating}"

input = STDIN.gets
arr = input.split.map(&:to_i)
# всего навыков
n = arr[0]
# очки улучшений
k = arr[1]
# получаем все очки
input = STDIN.gets
abilities = input.split.map(&:to_i)
# создаем словарь
indexes = Hash.new

rating = 0
i = 0
# n шагов
abilities.each do |item|
  # заполняем словарь значениями
  indexes[i] = 10 - item % 10
  i += 1
end
# создаем ещё один словарь из первого
# отсортированный по значениям
# ? шагов - не знаю как сортировка устроена
sort =  Hash[indexes.sort_by{|k, v| v}]

# добавляем очки там, где их нужно меньше всего,
# чтобы "добить" до величины, кратной 10-ти
# ещё n шагов в пределе, хотя может и раньше закончиться
sort.each do |key, value|
  if k - value > 0
    abilities[key] += value
    k = k - value
  else
    break
  end
end

# финальный проход
# n шагов
abilities.each do |item|
  rating += (item * 0.1).floor
end

# Итого примерно
# 3n + ? шагов
# ? - сортировка
puts "#{rating}"

input = gets.chomp.split
n = Integer(input[0])
k = Integer(input[1])
input = gets.chomp.split
skills = []
for i in 0...n
    skills[i] = Integer(input[i])
end

skills.sort!{|x, y| y <=> x}
for i in 0...n
    if skills[i] % 10 != 0
        unit_needed = 10 - skills[i] % 10
    else
        unit_needed = 0
    end
    if unit_needed > k
        break
    else
        skills[i] += unit_needed
        k -= unit_needed
    end
end
if k >= 10
    for i in 0...n
        x = k / 10
        if skills[i] < 100
            y = (100 - skills[i]) / 10
            if x <= y
                skills[i] += 10 * x
                break
            else
                skills[i] = 100
                k -= 10 * y
            end
        end
    end
end
sum = 0
if skills[0] == skills[n-1] && skills[0] == 0
    sum = (k.to_f / 10).floor
else
    for i in 0...n
        sum += (skills[i].to_f / 10).floor
    end
end
puts sum

input = gets.chomp.split
n = Integer(input[0])
k = Integer(input[1])
input = gets.chomp.split
skills = []
for i in 0...n
    skills[i] = Integer(input[i])
end

sum = 0
for i in 0...skills.length
    if skills[i] == 100
        sum += 10
        skills.delete_at(i)
    end
end
sequence = []
for i in 0...skills.length
    sequence[i] = []
    sequence[i][0] = skills[i] / 10
    sequence[i][1] = skills[i] % 10
end
sequence = sequence.sort{|x, y| y[1] <=> x[1]}
for i in 0...sequence.length
    if 10 - sequence[i][1] < k
        k -= 10 - sequence[i][1]
        sequence[i][1] = 10
    else
        sequence[i][1] += k
        k = 0
        break
    end
end
numbers = []
for i in 0...sequence.length
    numbers[i] = 10 * sequence[i][0] + sequence[i][1]
end
if k >= 10
    for i in 0...numbers.length
        if k >= 100 - numbers[i]
            numbers[i] = 100
            k -= 100 - numbers[i]
        else
            numbers[i] += k
            k = 0
            break
        end
    end
end
for i in 0...numbers.length
    sum += (numbers[i].to_f / 10).floor
end
puts sum

input = gets.chomp.split
n = Integer(input[0])
k = Integer(input[1])
input = gets.chomp.split
skills = []
for i in 0...n
    skills[i] = Integer(input[i])
end

skills.sort!{|x, y| y <=> x}
for i in 0...n
    if skills[i] % 10 != 0
        unit_needed = 10 - skills[i] % 10
    else
        unit_needed = 0
    end
    if unit_needed > k
        break
    else
        skills[i] += unit_needed
        k -= unit_needed
    end
end
sum = 0
if skills[0] == skills[n-1] && skills[0] == 0
    sum = (k.to_f / 10).floor
else
    for i in 0...n
        sum += (skills[i].to_f / 10).floor
    end
end
puts sum

input = gets.chomp.split
n = Integer(input[0])
k = Integer(input[1])
input = gets.chomp.split
skills = []
for i in 0...n
    skills[i] = Integer(input[i])
end

skills.sort!{|x, y| y <=> x}
for i in 0...n
    if skills[i] % 10 != 0
        unit_needed = 10 - skills[i] % 10
    else
        unit_needed = 0
    end
    if unit_needed > k
        break
    else
        skills[i] += unit_needed
        k -= unit_needed
    end
end
if k >= 10
    skills[0] += 10 * (k / 10)
end
sum = 0
if skills[0] == skills[n-1] && skills[0] == 0
    sum = (k.to_f / 10).floor
else
    for i in 0...n
        sum += (skills[i].to_f / 10).floor
    end
end
puts sum

input = gets.chomp.split
n = Integer(input[0])
k = Integer(input[1])
input = gets.chomp.split
skills = []
for i in 0...n
    skills[i] = Integer(input[i])
end

skills.sort!{|x, y| y <=> x}
for i in 0...n
    if skills[i] % 10 != 0
        unit_needed = 10 - skills[i] % 10
    else
        unit_needed = 0
    end
    if unit_needed > k
        break
    else
        skills[i] += unit_needed
        k -= unit_needed
    end
end
sum = 0
for i in 0...n
    sum += (skills[i].to_f / 10).floor
end
puts sum

firstInput = gets.chomp.split(' ').map {|item| item.to_i}
skillNum, itemNum = firstInput[0], firstInput[1]
skillHash = {}
ans = 0
skillLevel = gets.chomp.split(' ').map {|item| item.to_i}
skillLevel.each_with_index do |value, index|
	skillHash[index] = value % 10
end

skillLevel.sort! {|a, b| b % 10 <=> a % 10}

index = 0
until itemNum == 0 || index == skillNum
	rest = 10 - (skillLevel[index] % 10)
	itemNum -= rest
	break if itemNum < 0
	skillLevel[index] += rest
	index += 1
end

skillLevel.each do |level|
	ans += (level / 10)
end

puts ans

firstInput = gets.chomp.split(' ').map {|item| item.to_i}
skillNum, itemNum = firstInput[0], firstInput[1]
ans = 0
skillLevel = gets.chomp.split(' ').map {|item| item.to_i}
skillLevel.sort! {|a, b| b % 10 <=> a % 10}

index = 0
until itemNum == 0 || index == skillNum
	if skillLevel[index] == 100
		index += 1
		next
	end

	rest = 10 - (skillLevel[index] % 10)
	itemNum -= rest
	break if itemNum < 0
	skillLevel[index] += rest
	index += 1
end

skillLevel.sort! {|a, b| b % 100 <=> a % 100}

index = 0
until itemNum == 0 || index == skillNum
	if skillLevel[index] == 100
		index += 1
		next
	end

	rest = 100 - (skillLevel[index] % 100)
	itemNum -= rest
	break if itemNum < 0
	skillLevel[index] += rest
	index += 1
end

skillLevel.each do |level|
	ans += (level / 10)
end

puts ans


There are n cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as c1, c2, ..., cn. The Old Peykan wants to travel from city c1 to cn using roads. There are (n - 1) one way roads, the i-th road goes from city ci to city ci + 1 and is di kilometers long.The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.Each city ci (except for the last city cn) has a supply of si liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly k hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times. Initially (at time zero) the Old Peykan is at city c1 and s1 liters of fuel is transferred to it's empty tank from c1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.Find the minimum time the Old Peykan needs to reach city cn.

The first line of the input contains two space-separated integers m and k (1 ≤ m, k ≤ 1000). The value m specifies the number of roads between cities which is equal to n - 1. The next line contains m space-separated integers d1, d2, ..., dm (1 ≤ di ≤ 1000) and the following line contains m space-separated integers s1, s2, ..., sm (1 ≤ si ≤ 1000).

In the only line of the output print a single integer — the minimum time required for The Old Peykan to reach city cn from city c1.

NoteIn the second sample above, the Old Peykan stays in c1 for 3 hours.

m,k=gets.split.map(&:to_i)
d=gets.split.map(&:to_i)
s=gets.split.map(&:to_i)
f=0
maxi=0
res=0
for i in 0..m-1 do
    maxi=i if s[maxi]<s[i]
    f+=s[i]
    res+=d[i]
    if f<d[i] then
        r=((d[i]-f+s[maxi]-1)/s[maxi]).to_i
        res+=r*k
        f+=r*s[maxi]
    end
    f-=d[i]
#    p [f, res]
end
puts res

def main()
	inpmk=gets.chomp.split(" ")
	inpmk=inpmk.map{|i| i.to_i}
	m=inpmk[0]
	k=inpmk[1]
	n=m+1
	inpd=gets.chomp.split(" ")
	d=inpd.map{|i| i.to_i}
	inps=gets.chomp.split(" ")
	s=inps.map{|i| i.to_i}
	mint=0;
	pet=s[0]
	for i in 0...m
		if pet>=d[i]
			pet-=d[i]
			mint+=d[i]
			if i < m-1
				pet+=s[i+1]
			end
		else
			maxp=s[0..i].max
			while(pet<d[i])
				mint+=k;
				pet+=maxp
			end
			pet-=d[i]
			mint+=d[i]
			if i < m-1
				pet+=s[i+1]
			end
		end
	end
	puts mint
end
main()

def main()
    inpmk=gets.chomp.split(" ")
    inpmk=inpmk.map{|i| i.to_i}
    m=inpmk[0]
    k=inpmk[1]
    n=m+1
    inpd=gets.chomp.split(" ")
    d=inpd.map{|i| i.to_i}
    inps=gets.chomp.split(" ")
    s=inps.map{|i| i.to_i}
    mint=0;
    pet=s[0]
    tiws=0;
    stop=false;
    for i in 0...m
        if pet>=d[i]
            pet-=d[i]
            tiws+=d[i]
            if i < m-1
                pet+=s[i+1]
            end
        else
            stop=true;
            break;
        end
    end
    if stop
        pet=s[0]
        for i in 0...m
            if pet>=d[i]
                pet-=d[i]
                mint+=d[i]
                if i < m-1
                    pet+=s[i+1]
                end
            else
                maxp=s[0..i].max
                while(pet<d[i])
                    mint+=k;
                    pet+=maxp
                end
                pet-=d[i]
                mint+=d[i]
                 if i < m-1
                    pet+=s[i+1]
                end
            end
        end
        puts mint;
    else
        puts tiws
    end
end
main()

# Bayan 2012-2013 Elimination Round
# Problem A -- Old Peykan
read = lambda { gets.split.map(&:to_i) }
m, k = read.call
d = read.call
s = read.call
answer = now = left = delta = 0
while now < m
    delta = [delta, s[now]].max
    left += s[now]
    while left < d[now]
        answer += k
        left += delta
    end
    answer += d[now]
    left -= d[now]
    now += 1
end
puts answer

m,k=gets.split.map(&:to_i)
d=gets.split.map(&:to_i)
s=gets.split.map(&:to_i)
f=s[0]
res=0
for i in 0..m-1 do
    a=(d[i]/f).to_i
    res+=(d[i]+a*k)
    f+=a*s[i]
    f+=s[i]
end
puts res

m,k=gets.split.map(&:to_i)
d=gets.split.map(&:to_i)
s=gets.split.map(&:to_i)
f=s[0]
maxi=0
res=0
for i in 0..m-1 do
    maxi=i if s[maxi]<s[i]
    if f<d[i] then
        r=((d[i]-f+s[maxi]-1)/s[maxi]).to_i
        res+=(r-1)*k
        f+=r*s[maxi]
    end
    f-=d[i]
    res+=d[i]
#    p [f, res]
end
puts res

def main()
	inpmk=gets.chomp.split(" ")
	inpmk=inpmk.map{|i| i.to_i}
	m=inpmk[0]
	k=inpmk[1]
	n=m+1
	inpd=gets.chomp.split(" ")
	d=inpd.map{|i| i.to_i}
	inps=gets.chomp.split(" ")
	s=inps.map{|i| i.to_i}
	mint=0;
	pet=s[0]
	tiws=0;
	stop=false;
	for i in 0...m
		if pet>=d[i]
			pet-=d[i]
			tiws+=d[i]
			if i < m-1
				pet+=s[i+1]
			end
		else
			stop=true;
			break;
		end
	end
	if stop
		pet=s[0]
		for i in 0...m
			if pet>=d[i]
				pet-=d[i]
				mint+=d[i]
				if i < m
					pet+=s[i+1]
				end
			else
				maxp=s[0..i].max
				while(pet<d[i])
					mint+=k;
					pet+=maxp
				end
				pet-=d[i]
				mint+=d[i]
			end
		end
		puts mint;
	else
		puts tiws
	end
end
main()


Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled.

The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108.

If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples).

# Sort the elements
# find diff array
# check if d is the same for all elements
# if so insert at first and last
# if d is diff for just one element insert at that position
# if d is diff for more than one element no ap is possible
# special case when 2 elements - can be inserted in between by changing d as d/ 2

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
ans = nil
if arr.length == 1
	puts -1
else
	arr.sort!
	if arr.length == 2
		d = arr[1] - arr[0]
		ans = [arr[0] - d,arr[1]+d]
		mid = (arr[0] + arr[1]) / 2
		ans << mid if (mid - arr[0] == arr[1] - mid)
	else
		diff = []
		arr.each_cons(2) do |a,b|
			diff << b - a
		end
		d = diff.min
		count = diff.count{|x| x!=d}
		if count == 0
			ans = [arr[0] - d,arr[-1]+d]
		elsif count == 1
			i = diff.index{|x| x!=d}
			ans = [arr[i]+d] if arr[i]+d == arr[i+1]-d
		end

	end

	if ans
		ans.uniq!
		puts ans.length
		puts ans.sort.join(" ")
	else
		puts 0
	end
end

n=gets.to_i
a=gets.split.map(&:to_i).sort
h=Hash.new(0)
if n==1
  p -1
elsif n==2
  if a[0]==a[1]
    puts 1,a[0]
  elsif (a[0]+a[1])%2==0
    d=a[1]-a[0]
    puts 3,[a[0]-d,(a[0]+a[1])/2,a[1]+d].sort*' '
  else
    d=a[1]-a[0]
    puts 2,[a[0]-d,a[1]+d].sort*' '
  end
else
  j=nil
  (1...n).each do |i|
    h[a[i]-a[i-1]]+=1
    break if h.size>2
  end
  if h.size==1
    if h[0]>0
      puts 1,a[0]
    else
      d=a[1]-a[0]
      puts 2,[a[0]-d,a[-1]+d].sort*' '
    end
  elsif h.size==2
    k=h.keys
    d=e=nil
    if k[0]*2==k[1]
      d=k[0]
      e=k[1]
    elsif k[1]*2==k[0]
      d=k[1]
      e=k[0]
    end
    if d&&e&&h[e]==1
      (1...n).each do |i|
        if a[i]-a[i-1]==e
          puts 1,a[i-1]+d
          exit
        end
      end
    else
      p 0
    end
  else
    p 0
  end
end

inp = ARGF.read.split
n = inp.shift.to_i
a = inp.map(&:to_i).sort!

solve = lambda {
  if n == 0 then 0
  elsif n == 1 then -1
  else
    mp = {}
    (1...n).each { |i|
      x = a[i] - a[i - 1]
      mp[x] = 0 if not mp.key? x
      mp[x] += 1
    }
    x, y = mp.keys.min, mp.keys.max
    if mp.size == 1
      d = a[1] - a[0]
      il = [a[0] - d, a[n - 1] + d]
      il << a[0] + d / 2 if a.size == 2 and d % 2 == 0
      il.sort!.uniq!
      il.size.to_s + "\n" + il.map(&:to_s).join(' ')
    elsif mp.size == 2 and mp[y] == 1 and x * 2 == y
      (1...n).step(1) { |i|
        return "1\n#{a[i - 1] + x}" if a[i] - a[i - 1] == y
      }
    else 0 end
  end
}

puts solve.call

# Sort the elements
# find diff array
# check if d is the same for all elements
# if so insert at first and last
# if d is diff for just one element insert at that position
# if d is diff for more than one element no ap is possible
# special case when 2 elements - can be inserted in between by changing d as d/ 2

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
ans = nil
if arr.length == 1
	puts -1
else
	arr.sort!
	if arr.length == 2
		d = arr[1] - arr[0]
		ans = [arr[0] - d,arr[1]+d]
		mid = (arr[0] + arr[1]) / 2
		ans << mid if (mid - arr[0] == arr[1] - mid)
	else
		diff = []
		arr.each_cons(2) do |a,b|
			diff << b - a
		end
		d = diff.min
		count = diff.count{|x| x!=d}
		if count == 0
			ans = [arr[0] - d,arr[-1]+d]
		elsif count == 1
			i = diff.index{|x| x!=d}
			ans = [arr[i]+d] if arr[i]+d == arr[i+1]-d
		end

	end

	if ans
		puts ans.length
		puts ans.sort.join(" ")
	else
		puts 0
	end
end

inp = ARGF.read.split
n = inp.shift.to_i
a = inp.map(&:to_i).sort!

solve = lambda {
  if n == 0 then 0
  elsif n == 1 then -1
  else
    mp = {}
    (1...n).each { |i|
      x = a[n - i] - a[n - i - 1]
      mp[x] = 0 if not mp.key? x
      mp[x] += 1
    }
    if mp.size == 1
      d = a[1] - a[0]
      il = [a[0] - d, a[n - 1] + d]
      il << a[0] + d / 2 if a.size == 2 and d % 2 == 0
      il.sort!.uniq!
      il.size.to_s + "\n" + il.map(&:to_s).join(' ')
    elsif mp.size == 2
      x, y = mp.keys.min, mp.keys.max
      if x * 2 == y
        (1...n).step(1) { |i|
          return "1\n#{a[i - 1] + x}" if a[i] - a[i - 1] == y
        }
      else 0 end
    end
  end
}

puts solve.call


Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba".Dr. Moriarty plans to take string s and cut out some substring from it, let's call it t. Then he needs to change the substring t zero or more times. As a result, he should obtain a fixed string u (which is the string that should be sent to Sherlock Holmes). One change is defined as making one of the following actions:   Insert one letter to any end of the string.  Delete one letter from any end of the string.  Change one letter into any other one. Moriarty is very smart and after he chooses some substring t, he always makes the minimal number of changes to obtain u. Help Moriarty choose the best substring t from all substrings of the string s. The substring t should minimize the number of changes Moriarty should make to obtain the string u from it.

The first line contains a non-empty string s, consisting of lowercase Latin letters. The second line contains a non-empty string u, consisting of lowercase Latin letters. The lengths of both strings are in the range from 1 to 2000, inclusive.

Print the only integer — the minimum number of changes that Dr. Moriarty has to make with the string that you choose.

NoteIn the first sample Moriarty can take any substring of length 3, and it will be equal to the required message u, so Moriarty won't have to make any changes.In the second sample you should take a substring consisting of characters from second to fourth ("bca") or from fifth to sixth ("bc"). Then you will only have to make one change: to change or to add the last character.In the third sample the initial string s doesn't contain any character that the message should contain, so, whatever string you choose, you will have to make at least 7 changes to obtain the required message.

def find_max a
	max = 0
	for i in 1...a.length
		max = i if a[i] > a[max]
	end
	return a[max]
end

s = gets.strip.split("")
u = gets.strip.split("")

a = Array.new(s.length)
b = Array.new(u.length)

s.each_index do |i|
	sum = 0
	for j in 0...u.length
		sum += 1 if s[i+j] == u[j]
	end
	a[i] = sum
end

u.each_index do |i|
	sum = 0
	for j in 0...s.length
		sum += 1 if u[i+j] == s[j]
	end
	b[i] = sum
end

a_max = find_max(a)
b_max = find_max(b)

#puts a.to_s
#puts b.to_s
#puts a_max
#puts b_max
#puts u.length
#puts s.length

if a_max > b_max
	c = a_max
else
	c = b_max
end

puts u.length - c

def find_max_index a
	max = 0
	for i in 1...a.length
		max = i if a[i] > a[max]
	end
	return max
end

s = gets.strip.split("")
u = gets.strip.split("")

b = Array.new(s.length)

s.each_index do |i|
		sum = 0
		for j in 0...u.length
			sum += 1 if s[i+j] == u[j]
		end
		b[i] = sum
	end

puts u.length - b[find_max_index(b)]

def find_max_index a
	max = 0
	for i in 1...a.length
		max = i if a[i] > a[max]
	end
	return max
end

s = gets.strip.split("")
u = gets.strip.split("")

if(s.length >= u.length)
	smaller = u
	bigger = s
else
	smaller = s
	bigger = u
end

b = Array.new(s.length)

bigger.each_index do |i|
	sum = 0
	for j in 0...smaller.length
		sum += 1 if bigger[i+j] == smaller[j]
	end
	b[i] = sum
end

puts u.length - b[find_max_index(b)]

def find_max_index a
	max = 0
	for i in 1...a.length
		max = i if a[i] > a[max]
	end
	return max
end

s = gets.strip.split("")
u = gets.strip.split("")

if(s.length > u.length)
	smaller = u
	bigger = s
else
	smaller = s
	bigger = u
end

b = Array.new(s.length)

bigger.each_index do |i|
	sum = 0
	for j in 0...smaller.length
		sum += 1 if bigger[i+j] == smaller[j]
	end
	b[i] = sum
end

puts b.to_s
puts find_max_index(b)
puts u.length
puts s.length

puts bigger.length - b[find_max_index(b)]


Polycarp has created his own training plan to prepare for the programming contests. He will train for $$$n$$$ days, all days are numbered from $$$1$$$ to $$$n$$$, beginning from the first.On the $$$i$$$-th day Polycarp will necessarily solve $$$a_i$$$ problems. One evening Polycarp plans to celebrate the equator. He will celebrate it on the first evening of such a day that from the beginning of the training and to this day inclusive he will solve half or more of all the problems.Determine the index of day when Polycarp will celebrate the equator.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 200\,000$$$) — the number of days to prepare for the programming contests. The second line contains a sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$), where $$$a_i$$$ equals to the number of problems, which Polycarp will solve on the $$$i$$$-th day.

Print the index of the day when Polycarp will celebrate the equator.

NoteIn the first example Polycarp will celebrate the equator on the evening of the second day, because up to this day (inclusive) he will solve $$$4$$$ out of $$$7$$$ scheduled problems on four days of the training.In the second example Polycarp will celebrate the equator on the evening of the third day, because up to this day (inclusive) he will solve $$$6$$$ out of $$$12$$$ scheduled problems on six days of the training.


You are given two arrays $$$a$$$ and $$$b$$$, both consisting of $$$n$$$ integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$; $$$i \neq j$$$) and swap $$$a_i$$$ with $$$a_j$$$ and $$$b_i$$$ with $$$b_j$$$. You have to perform the swap in both arrays.You are allowed to perform at most $$$10^4$$$ moves (possibly, zero). Can you make both arrays sorted in a non-decreasing order at the end? If you can, print any sequence of moves that makes both arrays sorted.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of elements in both arrays. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the first array. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le n$$$) — the second array.

For each testcase, print the answer. If it's impossible to make both arrays sorted in a non-decreasing order in at most $$$10^4$$$ moves, print -1. Otherwise, first, print the number of moves $$$k$$$ $$$(0 \le k \le 10^4)$$$. Then print $$$i$$$ and $$$j$$$ for each move $$$(1 \le i, j \le n$$$; $$$i \neq j)$$$. If there are multiple answers, then print any of them. You don't have to minimize the number of moves.

gets.to_i.times do
  n = gets.to_i
  as = gets.split.map(&:to_i)
  bs = gets.split.map(&:to_i)
  swaps = []
  0.upto(n - 1).each do |i|
    (i + 1).upto(n - 1).each do |j|
      if as[i] > as[j] || bs[i] > bs[j]
        swaps << [i, j]
        as[i], as[j] = as[j], as[i]
        bs[i], bs[j] = bs[j], bs[i]
      end
    end
  end
  sorted = as.each_cons(2).all? { |x, y| x <= y } && bs.each_cons(2).all? { |x, y| x <= y }
  if sorted
    p swaps.size
    swaps.each do |i, j|
      puts "#{i + 1} #{j + 1}"
    end
  else
    p -1
  end
end


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the interval [pl, pr] and Vasya chooses an integer v from the interval [vl, vr] (also randomly). Both players choose their integers equiprobably. Find the probability that the interval [min(v, p), max(v, p)] contains exactly k lucky numbers.

The single line contains five integers pl, pr, vl, vr and k (1 ≤ pl ≤ pr ≤ 109, 1 ≤ vl ≤ vr ≤ 109, 1 ≤ k ≤ 1000).

On the single line print the result with an absolute error of no more than 10 - 9.

NoteConsider that [a, b] denotes an interval of integers; this interval includes the boundaries. That is, In first case there are 32 suitable pairs: (1, 7), (1, 8), (1, 9), (1, 10), (2, 7), (2, 8), (2, 9), (2, 10), (3, 7), (3, 8), (3, 9), (3, 10), (4, 7), (4, 8), (4, 9), (4, 10), (7, 1), (7, 2), (7, 3), (7, 4), (8, 1), (8, 2), (8, 3), (8, 4), (9, 1), (9, 2), (9, 3), (9, 4), (10, 1), (10, 2), (10, 3), (10, 4). Total number of possible pairs is 10·10 = 100, so answer is 32 / 100.In second case Petya always get number less than Vasya and the only lucky 7 is between this numbers, so there will be always 1 lucky number.

p1,p2,v1,v2,k = gets.split(' ').map(&:to_i)

lucky = [4, 7]

i = 0

while true do
    if lucky[i] == 444444444 then break end
    lucky << lucky[i] * 10 + 4
    lucky << lucky[i] * 10 + 7
    i += 1
end

def acc(lucky, i, k, p1, p2, v1, v2)
    if i > 0 then p1 = [p1, lucky[i - 1] + 1].max end
    if i + k < lucky.length then
        v2 = [v2, lucky[i + k] - 1].min
    end
    a = [lucky[i], p2].min - p1 + 1
    b = v2 - [v1, lucky[i + k - 1]].max + 1
    if (a > 0 and b > 0) then return a * b end
    return 0
end

ans = 0
(lucky.length - k + 1).times do |i|
    ans += acc(lucky, i, k, p1, p2, v1, v2)
    ans += acc(lucky, i, k, v1, v2, p1, p2)
end

lucky.each do |a|
    if k == 1 and (v1..v2).include?(a) and (p1..p2).include?(a) then ans -= 1 end
end

puts ans.to_f / ((p2 - p1 + 1) * (v2 - v1 + 1))

p1,p2,v1,v2,k = gets.split(' ').map(&:to_i)

lucky = [4, 7]

i = 0

while true do
    if lucky[i] == 444444444 then break end
    lucky << lucky[i] * 10 + 4
    lucky << lucky[i] * 10 + 7
    i += 1
end

def acc(lucky, i, k, p1, p2, v1, v2)
    if i > 0 then p1 = [p1, lucky[i - 1] + 1].max end
    if i + k < lucky.length then
        v2 = [v2, lucky[i + k] - 1].min
    end
    a = [lucky[i], p2].min - p1 + 1
    b = v2 - [v1, lucky[i + k - 1]].max + 1
    if (a > 0 and b > 0) then return a * b end
    return 0
end

ans = 0
(lucky.length - k + 1).times do |i|
    ans += acc(lucky, i, k, p1, p2, v1, v2)
    ans += acc(lucky, i, k, v1, v2, p1, p2)
end

lucky.each do |a|
    if (v1..v2).include?(a) and (p1..p2).include?(a) then ans -= 1 end
end

puts ans.to_f / ((p2 - p1 + 1) * (v2 - v1 + 1))

p1,p2,v1,v2,k = gets.split(' ').map(&:to_i)

lucky = [4, 7]

i = 0

while true do
    if lucky[i] == 444444444 then break end
    lucky << lucky[i] * 10 + 4
    lucky << lucky[i] * 10 + 7
    i += 1
end

def acc(lucky, i, k, p1, p2, v1, v2, add)
    if i > 0 then p1 = [p1, lucky[i - 1] + 1].max end
    if i + k < lucky.length then
        v2 = [v2, lucky[i + k] - 1].min
    end
    a = [lucky[i], p2].min - p1 + 1
    b = v2 - [v1, lucky[i + k - 1] + add].max + 1
    if (a > 0 and b > 0) then return a * b end
    return 0
end

ans = 0
(lucky.length - k + 1).times do |i|
    ans += acc(lucky, i, k, p1, p2, v1, v2, 0)
    ans += acc(lucky, i, k, v1, v2, p1, p2, k == 1 ? 1 : 0)
end

puts ans.to_f / ((p2 - p1 + 1) * (v2 - v1 + 1))


Given three distinct integers $$$a$$$, $$$b$$$, and $$$c$$$, find the medium number between all of them.The medium number is the number that is neither the minimum nor the maximum of the given three numbers. For example, the median of $$$5,2,6$$$ is $$$5$$$, since the minimum is $$$2$$$ and the maximum is $$$6$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 6840$$$) — the number of test cases. The description of each test case consists of three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \leq a, b, c \leq 20$$$).

For each test case, output a single integer — the medium number of the three numbers.

main = -> {
  abc = gets.split.map(&:to_i)
  abc.sum - abc.min - abc.max
}

t = gets.to_i
puts t.times.map{ main.call }.join("\n")

gets.to_i.times{
    n=gets.split.map &:to_i
    n=n.sort
    puts n[1]
}

=begin

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

=end

t=gets.to_i
for i in 1..t
    a,b,c =gets.split.map &:to_i

    if a>b
        if (b>c)
            p b
        elsif a>c
            p c
        else
            p a
        end
    else
        if (a>c)
            p a
        elsif b>c
            p c
        else
            p b
        end
   end

end

gets
x=$<.map{|x|x.split.map(&:to_i).sort[1]}
puts x


Jack decides to invite Emma out for a dinner. Jack is a modest student, he doesn't want to go to an expensive restaurant. Emma is a girl with high taste, she prefers elite places.Munhattan consists of n streets and m avenues. There is exactly one restaurant on the intersection of each street and avenue. The streets are numbered with integers from 1 to n and the avenues are numbered with integers from 1 to m. The cost of dinner in the restaurant at the intersection of the i-th street and the j-th avenue is cij.Jack and Emma decide to choose the restaurant in the following way. Firstly Emma chooses the street to dinner and then Jack chooses the avenue. Emma and Jack makes their choice optimally: Emma wants to maximize the cost of the dinner, Jack wants to minimize it. Emma takes into account that Jack wants to minimize the cost of the dinner. Find the cost of the dinner for the couple in love.

The first line contains two integers n, m (1 ≤ n, m ≤ 100) — the number of streets and avenues in Munhattan. Each of the next n lines contains m integers cij (1 ≤ cij ≤ 109) — the cost of the dinner in the restaurant on the intersection of the i-th street and the j-th avenue.

Print the only integer a — the cost of the dinner for Jack and Emma.

NoteIn the first example if Emma chooses the first or the third streets Jack can choose an avenue with the cost of the dinner 1. So she chooses the second street and Jack chooses any avenue. The cost of the dinner is 2.In the second example regardless of Emma's choice Jack can choose a restaurant with the cost of the dinner 1.

max_min = 0
n, m = gets.split.map(&:to_i)
for i in 1..n do
  row = gets.split.map(&:to_i)
  min = 1000000001
  row.each do |num|
    min = num if num < min
  end
  max_min = min if min > max_min
end
puts max_min

n, _ = gets.split.map &:to_i
prices = Array.new n
n.times do |i|
    prices[i] = gets.split.map(&:to_i).min
end
puts prices.max

ans = 0
rows, cols = gets.split.map(&:to_i)
rows.times do
	ans = [ans, gets.split.map(&:to_i).min].max
end

puts ans

n_e_m = gets.split(" ")
n = n_e_m[0].to_i
m = n_e_m[1].to_i
restaurantes = []
restaurante_escolhido = 0
n.times do
	ruas_numero = []
	ruas =  gets.split(" ")
	for i in 0..ruas.size - 1 do
		ruas_numero << ruas[i].to_i
	end
	restaurantes << ruas_numero.sort
end
for avenida in 0..restaurantes.size-1 do
	if restaurantes[avenida][0] > restaurante_escolhido
		restaurante_escolhido = restaurantes[avenida][0]
	end
end
puts restaurante_escolhido

n, m = gets.chomp.split(" ").map(&:to_i)
restraunts = []
street = gets.chomp.split(" ").map(&:to_i)
street_min = street.min
row = 0
restraunts << street
(n-1).times do |i|
  street = gets.chomp.split(" ").map(&:to_i)
  if street_min < street.min then
    street_min = street.min
    row = i + 1
  end
  restraunts << street
end
puts restraunts[row].min

n, m = gets.split(' ').map(&:to_i);
a = [];
n.times {
    a += [(gets.split(' ').map(&:to_i).min)];
}
puts a.max;

n =gets.split
ans=0
n[0].to_i.times do
    now=2000000000
    a=gets.split
    for x in a do
       now=x.to_i if x.to_i<now
    end
    ans=now if now>ans
end
p ans

n, m = gets.split.map(&:to_i)
max = 0
n.times do
  a = gets.split.map(&:to_i).min
  max = a if a > max
end
puts max

n_e_m = gets.split(" ")
n = n_e_m[0].to_i
m = n_e_m[1].to_i
restaurantes = []
ruas_numero = []
restaurante_escolhido = 0
n.times do
	ruas =  gets.split(" ")
	ruas.each do |rua|
		ruas_numero << rua.to_i
	end
	restaurantes << ruas_numero.sort
end
for avenida in 0..restaurantes.size-1 do
	if restaurantes[avenida][0] > restaurante_escolhido
		restaurante_escolhido = restaurantes[avenida][0]
	end
end
puts restaurante_escolhido

n_e_m = gets.split(" ")
n = n_e_m[0].to_i
restaurantes = []
restaurante_escolhido = 0
n.times do
	restaurantes << gets.split(" ").sort
end
for avenida in 0..restaurantes.size-1 do
	if restaurantes[avenida][0].to_i > restaurante_escolhido
		avenida_escolhida = restaurantes[avenida]
		restaurante_escolhido = restaurantes[avenida][0].to_i
	end
end
puts restaurante_escolhido

n_e_m = gets.split(" ")
n = n_e_m[0].to_i
m = n_e_m[1].to_i
restaurantes = []
avenida_letras = []
restaurante_da_emma = 0
emma = 0
jack = 100000000
n.times do
	restaurantes << gets.split(" ")
end
restaurantes.each_with_index do |avenida, index|
	for rua in 0..avenida.size - 1 do
		restaurante_atual = restaurantes[index][rua].to_i
		if restaurante_atual > restaurante_da_emma
			emma = index
			restaurante_da_emma = restaurante_atual
		end
	end
end
escolha_da_emma = restaurantes[emma]
for escolha in 0..escolha_da_emma.size-1 do
	if escolha_da_emma[escolha].to_i < jack
		jack = escolha_da_emma[escolha].to_i
	end
end
puts jack

n_e_m = gets.split(" ")
n = n_e_m[0].to_i
m = n_e_m[1].to_i
restaurantes = []
avenida_letras = []
emma = 0
nova_emma = 1000000000
jack = 100000000
n.times do
	restaurantes << gets.split(" ")
end
restaurantes.each_with_index do |avenida, index|
	for rua in 0..avenida.size - 1 do
		restaurante_atual = restaurantes[index][rua].to_i
		if restaurante_atual < nova_emma
			nova_emma = restaurante_atual
		end
	end
	if nova_emma > emma
		emma = index
	end
end
escolha_da_emma = restaurantes[emma]
for escolha in 0..escolha_da_emma.size-1 do
	if escolha_da_emma[escolha].to_i < jack
		jack = escolha_da_emma[escolha].to_i
	end
end
puts jack

n_e_m = gets.split(" ")
n = n_e_m[0].to_i
m = n_e_m[1].to_i
restaurantes = []
avenida_letras = []
emma = 0
nova_emma = 1000000000
jack = 100000000
n.times do
	restaurantes << gets.split(" ")
end
restaurantes.each_with_index do |avenida, index|
	for rua in 0..avenida.size - 1 do
		restaurante_atual = restaurantes[index][rua].to_i
		if restaurante_atual > nova_emma
			nova_emma = restaurante_atual
		end
	end
	if nova_emma > emma
		emma = index
	end
end
escolha_da_emma = restaurantes[emma]
for escolha in 0..escolha_da_emma.size-1 do
	if escolha_da_emma[escolha].to_i < jack
		jack = escolha_da_emma[escolha].to_i
	end
end
puts jack


Not so long ago, Vlad had a birthday, for which he was presented with a package of candies. There were $$$n$$$ types of candies, there are $$$a_i$$$ candies of the type $$$i$$$ ($$$1 \le i \le n$$$).Vlad decided to eat exactly one candy every time, choosing any of the candies of a type that is currently the most frequent (if there are several such types, he can choose any of them). To get the maximum pleasure from eating, Vlad does not want to eat two candies of the same type in a row.Help him figure out if he can eat all the candies without eating two identical candies in a row.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. The following is a description of $$$t$$$ test cases of input, two lines for each. The first line of the case contains the single number $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of types of candies in the package. The second line of the case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — the number of candies of the type $$$i$$$. It is guaranteed that the sum of $$$n$$$ for all cases does not exceed $$$2 \cdot 10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case of input. As an answer, output "YES" if Vlad can eat candy as planned, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first example, it is necessary to eat sweets in this order: a candy of the type $$$2$$$, it is the most frequent, now $$$a = [2, 2]$$$; a candy of the type $$$1$$$, there are the same number of candies of the type $$$2$$$, but we just ate one, now $$$a = [1, 2]$$$; a candy of the type $$$2$$$, it is the most frequent, now $$$a = [1, 1]$$$; a candy of the type $$$1$$$, now $$$a = [0, 1]$$$; a candy of the type $$$2$$$, now $$$a = [0, 0]$$$ and the candy has run out.In the second example, all the candies are of the same type and it is impossible to eat them without eating two identical ones in a row.In the third example, first of all, a candy of the type $$$2$$$ will be eaten, after which this kind will remain the only kind that is the most frequent, and you will have to eat a candy of the type $$$2$$$ again.

def solve(a)
    if a.length == 1 && a[0] == 1
        return true
    end

    if a.length < 2
        return false
    end

    a = a.sort

    if a[-1] - a[-2] > 1
        return false
    end

    return true
end

for _ in 1..(gets.to_i)
    gets
    a = gets.split.map(&:to_i)
    puts solve(a) ? 'YES' : 'NO'
end


Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.Initially, on day $$$1$$$, there is one bacterium with mass $$$1$$$.Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $$$m$$$ splits, it becomes two bacteria of mass $$$\frac{m}{2}$$$ each. For example, a bacterium of mass $$$3$$$ can split into two bacteria of mass $$$1.5$$$.Also, every night, the mass of every bacteria will increase by one.Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $$$n$$$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the sum of bacteria masses that Phoenix is interested in.

For each test case, if there is no way for the bacteria to exactly achieve total mass $$$n$$$, print -1. Otherwise, print two lines. The first line should contain an integer $$$d$$$  — the minimum number of nights needed. The next line should contain $$$d$$$ integers, with the $$$i$$$-th integer representing the number of bacteria that should split on the $$$i$$$-th day. If there are multiple solutions, print any.

NoteIn the first test case, the following process results in bacteria with total mass $$$9$$$:   Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$ each.  Night $$$1$$$: All bacteria's mass increases by one. There are now two bacteria with mass $$$1.5$$$.  Day $$$2$$$: None split.  Night $$$2$$$: There are now two bacteria with mass $$$2.5$$$.  Day $$$3$$$: Both bacteria split. There are now four bacteria with mass $$$1.25$$$.  Night $$$3$$$: There are now four bacteria with mass $$$2.25$$$.  The total mass is $$$2.25+2.25+2.25+2.25=9$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 9 in 3 nights.$$$ $$$In the second test case, the following process results in bacteria with total mass $$$11$$$:   Day $$$1$$$: The bacterium with mass $$$1$$$ splits. There are now two bacteria with mass $$$0.5$$$.  Night $$$1$$$: There are now two bacteria with mass $$$1.5$$$.  Day $$$2$$$: One bacterium splits. There are now three bacteria with masses $$$0.75$$$, $$$0.75$$$, and $$$1.5$$$.  Night $$$2$$$: There are now three bacteria with masses $$$1.75$$$, $$$1.75$$$, and $$$2.5$$$.  Day $$$3$$$: The bacteria with mass $$$1.75$$$ and the bacteria with mass $$$2.5$$$ split. There are now five bacteria with masses $$$0.875$$$, $$$0.875$$$, $$$1.25$$$, $$$1.25$$$, and $$$1.75$$$.  Night $$$3$$$: There are now five bacteria with masses $$$1.875$$$, $$$1.875$$$, $$$2.25$$$, $$$2.25$$$, and $$$2.75$$$.  The total mass is $$$1.875+1.875+2.25+2.25+2.75=11$$$. It can be proved that $$$3$$$ is the minimum number of nights needed. There are also other ways to obtain total mass 11 in 3 nights.$$$ $$$In the third test case, the bacterium does not split on day $$$1$$$, and then grows to mass $$$2$$$ during night $$$1$$$.

def solve n
  arr = []
  (0..50).each do |i|
    arr << (2 ** i)
    break if arr.reduce(:+) >= n
  end
  rem = arr.reduce(:+) - n
  idx = arr.length - 1
  idx.downto(1).each do |i|
    break if rem == 0
    if arr[i] - rem < arr[i - 1]
      rem -= (arr[i] - arr[i - 1])
      arr[i] = arr[i - 1]
    else
      arr[i] -= rem
      rem = 0
    end
  end
  res = []
  (1...arr.length).each do |i|
    res << 0 if arr[i] == arr[i - 1]
    if arr[i] > arr[i - 1]
      if arr[i] == arr[i - 1] * 2
        res << arr[i - 1]
      else
        res << arr[i] % arr[i - 1]
      end
    end
  end
  res
end

t = STDIN.gets.chomp.to_i

(1..t).each do |i|
  n = STDIN.gets.chomp.to_i
  res = solve n
  puts res.length
  puts res.join(" ")
end


A frog is currently at the point $$$0$$$ on a coordinate axis $$$Ox$$$. It jumps by the following algorithm: the first jump is $$$a$$$ units to the right, the second jump is $$$b$$$ units to the left, the third jump is $$$a$$$ units to the right, the fourth jump is $$$b$$$ units to the left, and so on.Formally:   if the frog has jumped an even number of times (before the current jump), it jumps from its current position $$$x$$$ to position $$$x+a$$$;  otherwise it jumps from its current position $$$x$$$ to position $$$x-b$$$. Your task is to calculate the position of the frog after $$$k$$$ jumps.But... One more thing. You are watching $$$t$$$ different frogs so you have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. Each of the next $$$t$$$ lines contain queries (one query per line). The query is described as three space-separated integers $$$a, b, k$$$ ($$$1 \le a, b, k \le 10^9$$$) — the lengths of two types of jumps and the number of jumps, respectively.

Print $$$t$$$ integers. The $$$i$$$-th integer should be the answer for the $$$i$$$-th query.

NoteIn the first query frog jumps $$$5$$$ to the right, $$$2$$$ to the left and $$$5$$$ to the right so the answer is $$$5 - 2 + 5 = 8$$$.In the second query frog jumps $$$100$$$ to the right, $$$1$$$ to the left, $$$100$$$ to the right and $$$1$$$ to the left so the answer is $$$100 - 1 + 100 - 1 = 198$$$.In the third query the answer is $$$1 - 10 + 1 - 10 + 1 = -17$$$.In the fourth query the answer is $$$10^9 - 1 + 10^9 - 1 + 10^9 - 1 = 2999999997$$$.In the fifth query all frog's jumps are neutralized by each other so the answer is $$$0$$$.The sixth query is the same as the fifth but without the last jump so the answer is $$$1$$$.

n = gets.strip.to_i
results = []
for i in 0..n-1
  a, b, k = gets.strip.split.map(&:to_i)

  result = 0

  if a == b
    if k % 2 == 0
        result = 0
    else
        result = a
    end
  else
    if k % 2 == 0
        result = a*k/2-b*k/2
    else
      result = a*((k/2).floor+1)-b*(k/2).floor
    end
  end

  results << result
end
results.each do |result|
  p result
end

class Sol
  def initialize(a, b, k)
    @k = k
    @b = b
    @a = a
  end

  def res
    puts (@k + 1) / 2 * @a - (@k / 2) * @b
  end
end

t = gets.to_i
t.times do
  a, b, k = gets.split.map &:to_i
  s = Sol.new(a, b, k)
  s.res
end

t = gets.strip.to_i
t.times do
  a, b, k = gets.strip.split.map(&:to_i)
  puts (a - b) * (k / 2) + ((k % 2).zero? ? 0 : a)
end

gets.to_i.times do
  a, b, k = gets.split.map(&:to_i)
  puts (k/2) * (a-b) + (k%2)*a
end

gets.to_i.times do
    a,b,k = gets.split.map(&:to_i)
    puts a*((k+1)/2)-b*(k/2)
end

# coding: utf-8

# if __FILE__ == $0
# end

t = gets.to_i
t.times {
    a, b, k = gets.split.map(&:to_i)
    even_jumps, odd_jumps = (k/2.0).ceil, k/2
    puts even_jumps * a - odd_jumps * b
}

t = gets.to_i

t.times do
  s = gets.split.map &:to_i
  q = s[2] / 2 + s[2] % 2
  puts q * s[0] - (s[2] - q) * s[1]
end

t = gets.to_i
t.times do
  a, b, k = gets.split.map(&:to_i)
  p(a*((k + 1)/2) - b*(k/2))
end

def solve()
    line = gets

    a = line.split(' ')[0].to_i
    b = line.split(' ')[1].to_i
    k = line.split(' ')[2].to_i

    if ( k%2 == 0 )
        return ( a * (k/2) - b * (k/2))
    end

    return ( a * (k/2) - b * (k/2)) + a
end

ntest = gets

ntest.to_i.times { |nn|

    puts solve()

}

1.upto(gets.to_i) do
  a, b, k = gets.split(' ').map(&:to_i)

  puts (a-b)*k.div(2) + a*k.modulo(2)
end


A string is binary, if it consists only of characters "0" and "1".String v is a substring of string w if it has a non-zero length and can be read starting from some position in string w. For example, string "010" has six substrings: "0", "1", "0", "01", "10", "010". Two substrings are considered different if their positions of occurrence are different. So, if some string occurs multiple times, we should consider it the number of times it occurs.You are given a binary string s. Your task is to find the number of its substrings, containing exactly k characters "1".

The first line contains the single integer k (0 ≤ k ≤ 106). The second line contains a non-empty binary string s. The length of s does not exceed 106 characters.

Print the single number — the number of substrings of the given string, containing exactly k characters "1". Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the sought substrings are: "1", "1", "10", "01", "10", "010".In the second sample the sought substrings are: "101", "0101", "1010", "01010".

k = gets.to_i
s = gets.chop
a = [0]
b = []
s.size.times{|i|
    if s[i] == '1'
        a << a[-1] + 1
        b << i
    else
        a << a[-1]
    end
}
b += [s.size] * (k + 1)
c = 0
a.each_with_index{|i, j|
    c += b[i + k] - (k == 0 ? j : b[i + k - 1])
}
p c

k = gets.to_i
s = gets.chop
a = [0]
b = []
s.size.times{|i|
    if s[i] == '1'
        a << a[-1] + 1
        b << i
    else
        a << a[-1]
    end
}
b += [s.size] * (k + 1)
p a.map{|i| b[i + k] - b[i + k - 1]}.inject(&:+)


The GCD table G of size n × n for an array of positive integers a of length n is defined by formula   Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows:  Given all the numbers of the GCD table G, restore array a.

The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a.  All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.

In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.

n = gets.chomp.to_i

h = Hash.new(0)
gets.chomp.split(' ').map(&:to_i).each { |item| h[item] += 1 }

arr = h.keys.sort.reverse

ans = Array.new(n, nil)

def gcd(a, b)
  return a if b == 0
  gcd(b, a % b)
end

index = 0
arr.each do |item|
  until h[ item ] == 0
    ans[ index ] = item
    h[ item ] -= 1
    index.times do |i|
      h[ gcd( item, ans[i] ) ] -= 2
    end
    index += 1
  end
end

puts ans.join(' ')


You are given an array $$$a$$$ of $$$n$$$ positive integers. Determine if, by rearranging the elements, you can make the array strictly increasing. In other words, determine if it is possible to rearrange the elements such that $$$a_1 < a_2 < \dots < a_n$$$ holds.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.

For each test case, output "YES" (without quotes) if the array satisfies the condition, and "NO" (without quotes) otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case any rearrangement will keep the array $$$[1,1,1,1]$$$, which is not strictly increasing.In the second test case, you can make the array $$$[1,3,4,7,8]$$$.

n = gets.to_i
n.times do
  _ = gets.to_i
  puts gets.split(' ').uniq! ? 'NO' : 'YES'
end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i).uniq
  puts a.size==n ? 'YES' : 'NO'
end

t=gets.to_i
t.times do
    _=gets
    a=gets.split.map(&:to_i)
    l=a.length
    nl=a.uniq.length
    if l==nl
        puts "YES"
    else
        puts "NO"
    end
end


BerOilGasDiamondBank has branches in n cities, at that n is an even number. The bank management wants to publish a calendar with the names of all those cities written in two columns: the calendar should consist of exactly n / 2 lines of strictly equal length, each of which contains exactly two names and exactly one separator character between them. The name of every city should be used in the calendar exactly once. For historical reasons the symbol d is used as the separator of words in the calendar. The BerOilGasDiamondBank management wants to show that all its branches are equally important to it, that's why the order of their appearance in the calendar should be following: if we "glue"(concatinate) all the n / 2 calendar lines (from top to bottom) to make a single line, then the lexicographically minimal line is obtained. No separator character will be used to separate calendar lines. For example, if the lines are "bertown!berville", "newberville!bera", then the resulting line is "bertown!bervillenewberville!bera". In some sense one has to find the lexicographically minimal calendar, where the comparison of calendars happens line by line.Help BerOilGasDiamondBank and construct the required calendar.

The first line contains an integer n (1 ≤ n ≤ 104, n is even) which is the number of branches. Then follow n lines which are the names of the cities. All the names consist of lowercase Latin letters; their lengths are no less than 1 and no more than 10 symbols. The next line contains a single symbol d (d has an ASCII-code from 33 to 126 inclusively, excluding lowercase Latin letters) which is the separator between words in the calendar lines. It is guaranteed that the calendar is possible to be constructed and all the names are different.

Print n / 2 lines of similar length which are the required calendar. Every line should contain exactly two words and exactly one separator between them. If there are several solutions, print the lexicographically minimal one. The lexicographical comparison of lines is realized by the "<" operator in the modern programming languages.

class Solution
  def initialize
    @n = gets.to_i
    @cities = []
    @n.times {@cities << gets.chomp}
    @d = gets.chomp
  end

  def solve
    length = (@cities.inject(0){|x, s| x + s.length})/(@n/2)

    left  = []
    right = []
    str_by_len = []
    for c in @cities do
      str_by_len[c.length] ||= []
      str_by_len[c.length] << c
    end
    (1..10).each do |i|
      unless str_by_len[i].nil?
        str_by_len[i].sort!
      end
    end

    (@n/2).times do
      min_s = '~' * 21
      min_i = -1
      min_j = -1
      (1..10).each do |i|
        next if str_by_len[i].nil? or str_by_len[i].empty?
        s1 = str_by_len[i].shift
        j = length - i
        next if str_by_len[j].nil? or str_by_len[j].empty?
        s2 = str_by_len[j].shift
        if s1 + @d + s2 < min_s
          min_s = s1 + @d + s2
          min_i = i
          min_j = j
        end
        str_by_len[j].unshift(s2)
        str_by_len[i].unshift(s1)
      end
      left  << str_by_len[min_i].shift
      right << str_by_len[min_j].shift
    end

    # find the last right column item
    (1..10).each do |i|
      if (not str_by_len[i].nil?) and (not str_by_len[i].empty?)
        right << str_by_len[i].shift
        break
      end
    end

    (@n/2).times do
      puts left.shift + @d + right.shift
    end
  end
end

solution = Solution.new
solution.solve

class Solution
  def initialize
    @n = gets.to_i
    @cities = []
    @n.times {@cities << gets.chomp}
    @d = gets.chomp
  end

  def solve
    length = (@cities.inject(0){|x, s| x + s.length})/(@n/2)

    left  = []
    right = []
    str_by_len = []
    for c in @cities do
      str_by_len[c.length] ||= []
      str_by_len[c.length] << c
    end
    (1..10).each do |i|
      unless str_by_len[i].nil?
        str_by_len[i].sort!
      end
    end

    (@n/2).times do
      min_s = '~' * 21
      min_i = -1
      min_j = -1
      (1..10).each do |i|
        next if str_by_len[i].nil? or str_by_len[i].empty?
        s1 = str_by_len[i].shift
        j = length - i
        next if str_by_len[j].nil? or str_by_len[j].empty?
        s2 = str_by_len[j].shift
        if s1 + @d + s2 < min_s
          min_s = s1 + @d + s2
          min_i = i
          min_j = j
        end
        str_by_len[j].unshift(s2)
        str_by_len[i].unshift(s1)
      end
      left  << str_by_len[min_i].shift
      right << str_by_len[min_j].shift
    end

    (@n/2).times do
      puts left.shift + @d + right.shift
    end
  end
end

solution = Solution.new
solution.solve


One day Vasya went out for a walk in the yard but there weren't any of his friends outside and he had no one to play touch and run. But the boy didn't lose the high spirits and decided to play touch and run with himself. You may ask: "How did he do that?" The answer is simple.Vasya noticed that the yard is a rectangular n × m field. The squares have coordinates (x, y) (1 ≤ x ≤ n, 1 ≤ y ≤ m), where x is the index of the row and y is the index of the column.Initially Vasya stands in the square with coordinates (xc, yc). To play, he has got a list of k vectors (dxi, dyi) of non-zero length. The game goes like this. The boy considers all vectors in the order from 1 to k, and consecutively chooses each vector as the current one. After the boy has chosen a current vector, he makes the maximally possible number of valid steps in the vector's direction (it is possible that he makes zero steps).A step is defined as one movement from the square where the boy is standing now, in the direction of the current vector. That is, if Vasya is positioned in square (x, y), and the current vector is (dx, dy), one step moves Vasya to square (x + dx, y + dy). A step is considered valid, if the boy does not go out of the yard if he performs the step.Vasya stepped on and on, on and on until he ran out of vectors in his list. Ha had been stepping for so long that he completely forgot how many steps he had made. Help the boy and count how many steps he had made.

The first input line contains two integers n and m (1 ≤ n, m ≤ 109) — the yard's sizes. The second line contains integers xc and yc — the initial square's coordinates (1 ≤ xc ≤ n, 1 ≤ yc ≤ m). The third line contains an integer k (1 ≤ k ≤ 104) — the number of vectors. Then follow k lines, each of them contains two integers dxi and dyi (|dxi|, |dyi| ≤ 109, |dx| + |dy| ≥ 1).

Print the single number — the number of steps Vasya had made. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteIn the first sample Vasya is initially positioned at square (1, 1) and makes 3 steps by the first vector (1, 1). So, he consecutively visits the squares (2, 2), (3, 3), (4, 4). Then he makes 0 steps by the second vector (1, 1). He makes 1 more step by the third vector (0,  - 2) and he ends up in square (4, 2). Overall, Vasya makes 4 steps.In the second sample Vasya is initially positioned in square (1, 2) and makes 0 steps by vector ( - 1, 0), as the square with coordinates (0, 2) is located outside the yard.

n,m = gets.chomp.split(/ /).map!{|x| x.to_i}
p0 = gets.chomp.split(/ /).map!{|x| x.to_i}
k = gets.chomp.to_i
step = 0
for i in 0..k-1
	p = gets.chomp.split(/ /).map!{|x| x.to_i}
	sx = 0
	sy = 0
	if p[0] != 0
		if p[0] < 0
			sx = (p0[0]-1) / -p[0]
		else
			sx = (n - p0[0]) / p[0]
		end
	end
	if p[1] != 0
		if p[1] < 0
			sy = (p0[1]-1) / -p[1]
		else
			sy = (m - p0[1]) / p[1]
		end
	end
	ws = [sx, sy].min
	ws = sy if p[0] == 0 && p[1] != 0
	ws = sx if p[0] != 0 && p[1] == 0
	p0 = [p0[0]+p[0]*ws, p0[1]+p[1]*ws]
	step += ws
end
puts step

w,h=gets.split.map(&:to_i)
x,y=gets.split.map(&:to_i)
x,y=x-1,y-1
k=gets.to_i
ans=0
k.times{|i|
	dx,dy=gets.split.map(&:to_i)
	minimum=[]
	if dx<0
		minimum+=[x/-dx]
	elsif dx>0
		minimum+=[(w-x-1)/dx]
	end

	if dy<0
		minimum+=[y/-dy]
	elsif dy>0
		minimum+=[(h-y-1)/dy]
	end
	ans+=minimum.min
	x+=dx*minimum.min
	y+=dy*minimum.min
}

p ans

#!/usr/bin/env ruby

def getmax(cur, lim, d)
  if d > 0
    (lim-cur) / d
  elsif d < 0
    (cur-1) / (-d)
  else
    1000000000
  end
end

n, m = gets.split.map(&:to_i)
x, y = gets.split.map(&:to_i)
k = gets.to_i

ans = 0
k.times do
  dx, dy = gets.split.map(&:to_i)
  max_x = getmax(x, n, dx)
  max_y = getmax(y, m, dy)
  maxstep =  [max_x, max_y].min
  x += dx*maxstep
  y += dy*maxstep
  ans += maxstep
end

p ans

n, m = STDIN.readline.split.map {|s| s.to_i }
x, y = STDIN.readline.split.map {|s| s.to_i }

def max_steps(x, d, n)
  return 10**9 if d == 0
  span = (d > 0 ? n-x : x-1)
  d = d.abs
  return span/d
end

count = 0
k = STDIN.readline.to_i
k.times do
  dx, dy = STDIN.readline.split.map {|s| s.to_i }
  a, b = max_steps(x, dx, n), max_steps(y, dy, m)
  c = [a, b].min
  x += c*dx
  y += c*dy
  count += c
end

puts count

sizes=gets.chomp
init=gets.chomp
v=[]
n=gets.chomp.to_i
n.times do
  v<<gets.chomp
end
a=[]
v.length.times do |x|
  a<<v[x].split(' ')
  2.times {|y| a[x][y]=a[x][y].to_i }
end
c=[]
s=[]
c=init.split(' ')
s=sizes.split(' ')
2.times {|x| c[x]=c[x].to_i;s[x]=s[x].to_i}
steps=0
for j in (0..n-1)
i=0;min=0;max=2*10**9;delta=0
while i>-1 do
  delta=(max-min)/2
  i=min+delta
  if !(c[0]+a[j][0]*i<1||c[0]+a[j][0]*i>s[0]||c[1]+a[j][1]*i<1||c[1]+a[j][1]*i>s[1])
    min=i
    if delta==0
      c[0]+=a[j][0]*i;c[1]+=a[j][1]*i
      steps+=i
      break
    end
  else
    max=i
  end
end
end
puts steps

n,m = gets.split.map(&:to_i)
x,y = gets.split.map(&:to_i)
vs = gets.to_i
v = []
vs.times{ v << gets.split.map(&:to_i) }
st = 0

v.each do |dxy|
  dx,dy = dxy[0],dxy[1]
  cx = dx > 0 ? n : 1
  cy = dy > 0 ? m : 1
  xx = dx != 0 ? ((cx-x)/dx).abs : 1000000000000
  yy = dy != 0 ? ((cy-y)/dy).abs : 1000000000000
  s = [yy,xx].min
  y = y+s*dy
  x = x+s*dx
  st += s
end
p st

inp = gets.split(" ")
n = inp[0].to_i
m = inp[1].to_i
inp = gets.split(" ")
xc = inp[0].to_i
yc = inp[1].to_i
k = gets.to_i
steps = 0
for i in 0..(k-1)

  inp = gets.split(" ")
  dxi = inp[0].to_i
  dyi = inp[1].to_i

  xsteps = 1000000000
  ysteps = 1000000000
  if(dxi > 0)
    xsteps = (n - xc) / dxi
  elsif (dxi < 0)
    xsteps = (xc - 1) / (-dxi)
  end
  if(dyi > 0)
    ysteps = (m - yc) / dyi
  elsif (dyi < 0)
    ysteps = (yc - 1) / (-dyi)
  end
  #puts ysteps
  s = [xsteps, ysteps].min
  xc += s * dxi
  yc += s * dyi
  #puts s
  #puts xc.to_s + "," + yc.to_s
  steps += s
end

puts steps

INF = 1000000001
nm = gets.split(" ")
n = nm[0].to_i
m = nm[1].to_i

xy = gets.split(" ")
x = xy[0].to_i
y = xy[1].to_i

k = gets.to_i
ans = 0
while k > 0
  dxy = gets.split(" ")
  dx = dxy[0].to_i
  w = INF
  if dx > 0 then
    w = (n - x) / dx
  elsif dx < 0 then
    w = (x-1) / (-dx)
  end
  dy = dxy[1].to_i
  h = INF
  if dy > 0 then
    h = (m - y) / dy
  elsif dy < 0 then
    h = (y - 1) / (-dy)
  end
  mn = w < h ? w : h
  ans += mn
  x += dx * mn
  y += dy * mn
  k = k-1
end

puts ans

sizes=gets.chomp
init=gets.chomp
v=[]
n=gets.chomp.to_i
n.times do
  v<<gets.chomp
end
a=[]
v.length.times do |x|
  a<<v[x].split(' ')
  2.times {|y| a[x][y]=a[x][y].to_i }
end

c=[]
s=[]
c=init.split(' ')
s=sizes.split(' ')
2.times {|x| c[x]=c[x].to_i;s[x]=s[x].to_i}
steps=0
for j in (0..n-1)
i=10**9
while i>0 do
  if !(c[0]+a[j][0]*i<1||c[0]+a[j][0]*i>s[0]||c[1]+a[j][1]*i<1||c[1]+a[j][1]*i>s[1])
    c[0]+=a[j][0]*i;c[1]+=a[j][1]*i
    steps+=i
    break
  end
  i/=2
end
end
puts steps

sizes=gets.chomp
init=gets.chomp
v=[]
(n_v=gets.chomp.to_i).times do
  v<<gets.chomp
end
a=[]
v.length.times do |x|
  a<<v[x].split(' ')
  2.times {|y| a[x][y]=a[x][y].to_i }
end
i=0
c=[init[0].chr.to_i,init[2].chr.to_i]
s=[sizes[0].chr.to_i,sizes[2].chr.to_i]
steps=0
while i<v.length do
  until c[0]<1||c[0]>s[0]||c[1]<1||c[1]>s[1] do
    c[0]+=a[i][0];c[1]+=a[i][1]
    if c[0]<1||c[0]>s[0]||c[1]<1||c[1]>s[1]
      c[0]-=a[i][0];c[1]-=a[i][1]
      break
    end
    steps+=1
  end
  i+=1
end
puts steps

inp = gets.split(" ")
n = inp[0].to_i
m = inp[1].to_i
inp = gets.split(" ")
xc = inp[0].to_i
yc = inp[1].to_i
k = gets.to_i
steps = 0
for i in 0..(k-1)

  inp = gets.split(" ")
  dxi = inp[0].to_i
  dyi = inp[1].to_i

  xsteps = 1000000000
  ysteps = 1000000000
  if(dxi > 0)
    xsteps = (n - xc) / dxi
  elsif (dxi < 0)
    xsteps = (xc - 1) / (-dxi)
  end
  if(dyi > 0)
    ysteps = (m - yc) / dyi
  elsif (dyi < 0)
    ysteps = (yc - 1) / (-dyi)
  end
  #puts ysteps
  s = [xsteps, ysteps].min
  xc += s * dxi
  yc += s * dyi
  puts s
  puts xc.to_s + "," + yc.to_s
  steps += s
end

puts steps

inp = gets.split(" ")
n = inp[0].to_i
m = inp[1].to_i
inp = gets.split(" ")
xc = inp[0].to_i
yc = inp[1].to_i
k = gets.to_i
steps = 0
for i in 0..(k-1)

  inp = gets.split(" ")
  dxi = inp[0].to_i
  dyi = inp[1].to_i

  xsteps = 1000000000
  ysteps = 1000000000
  if(dxi > 0)
    xsteps = (n - xc) / dxi
  elsif (dxi < 0)
    xsteps = (xc - 1) / (-dxi)
  end
  if(dyi > 0)
    ysteps = (n - yc) / dyi
  elsif (dyi < 0)
    ysteps = (yc - 1) / (-dyi)
  end
  #puts ysteps
  s = [xsteps, ysteps].min
  xc += s * dxi
  yc += s * dyi
  #puts s
  #puts xc.to_s + "," + yc.to_s
  steps += s
end

puts steps


A class of students wrote a multiple-choice test.There are $$$n$$$ students in the class. The test had $$$m$$$ questions, each of them had $$$5$$$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $$$i$$$ worth $$$a_i$$$ points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of students in the class and the number of questions in the test. Each of the next $$$n$$$ lines contains string $$$s_i$$$ ($$$|s_i| = m$$$), describing an answer of the $$$i$$$-th student. The $$$j$$$-th character represents the student answer (A, B, C, D or E) on the $$$j$$$-th question. The last line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le 1000$$$) — the number of points for the correct answer for every question.

Print a single integer — the maximum possible total score of the class.

NoteIn the first example, one of the most optimal test answers is "ABCD", this way the total number of points will be $$$16$$$.In the second example, one of the most optimal test answers is "CCC", this way each question will be answered by exactly one student and the total number of points is $$$5 + 4 + 12 = 21$$$.

a, b = gets.split.map(&:to_i)
c = Array.new(a).map do
  gets.chomp.bytes
end
f = gets.split.map(&:to_i)
puts(
  c.transpose.zip(f).map do |d, i|
    i * d.uniq.map{ |e| d.count e }.max
  end.inject(:+)
)

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

freq = Array.new(m){ {'A' => 0, 'B' => 0, 'C' => 0, 'D' => 0, 'E' => 0} }

n.times do |i|
  line = STDIN.gets.chomp.each_char.with_index do |c, j|
    freq[j][c] += 1
  end
end

scores = STDIN.gets.chomp.split(" ").map(&:to_i)
puts freq.map.with_index{|f, i| f.values.max*scores[i]}.reduce(&:+)

n, m = gets.split.map &:to_i
s = []
n.times { s << gets.chomp }
b = m.times.map do |j|
  h = {}
  (0...n).each do |i|
    h[s[i][j]] ||= 0
    h[s[i][j]] += 1
  end
  h.values.max
end
puts gets.split.each_with_index.inject(0) { |s, x| s + x[0].to_i*b[x[1]] }


At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, because for some groups periods of their lessons intersect. If at some moment of time one groups finishes it's lesson, and the other group starts the lesson, their lessons don't intersect.The dean wants to cancel the lesson in one group so that no two time periods of lessons of the remaining groups intersect. You are to find all ways to do that.

The first line contains integer n (1 ≤ n ≤ 5000) — amount of groups, which have lessons in the room 31. Then n lines follow, each of them contains two integers li ri (1 ≤ li < ri ≤ 106) — starting and finishing times of lesson of the i-th group. It is possible that initially no two lessons intersect (see sample 1).

Output integer k — amount of ways to cancel the lesson in exactly one group so that no two time periods of lessons of the remaining groups intersect. In the second line output k numbers — indexes of groups, where it is possible to cancel the lesson. Groups are numbered starting from 1 in the order that they were given in the input. Output the numbers in increasing order.


In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions:  overall, there must be m dances; exactly three people must take part in each dance; each dance must have one dancer in white clothes, one dancer in red clothes and one dancer in blue clothes (these are the colors of the national flag of Berland). The agency has n dancers, and their number can be less than 3m. That is, some dancers will probably have to dance in more than one dance. All of your dancers must dance on the party. However, if some dance has two or more dancers from a previous dance, then the current dance stops being spectacular. Your agency cannot allow that to happen, so each dance has at most one dancer who has danced in some previous dance. You considered all the criteria and made the plan for the m dances: each dance had three dancers participating in it. Your task is to determine the clothes color for each of the n dancers so that the President's third condition fulfilled: each dance must have a dancer in white, a dancer in red and a dancer in blue. The dancers cannot change clothes between the dances.

The first line contains two space-separated integers n (3 ≤ n ≤ 105) and m (1 ≤ m ≤ 105) — the number of dancers and the number of dances, correspondingly. Then m lines follow, describing the dances in the order of dancing them. The i-th line contains three distinct integers — the numbers of the dancers that take part in the i-th dance. The dancers are numbered from 1 to n. Each dancer takes part in at least one dance.

Print n space-separated integers: the i-th number must represent the color of the i-th dancer's clothes (1 for white, 2 for red, 3 for blue). If there are multiple valid solutions, print any of them. It is guaranteed that at least one solution exists.

n, m = gets.split.map(&:to_i)
color = Array.new(n+1, 0)
for i in 0...m
  a = gets.split.map(&:to_i)
  mark = Array.new(4, false)
  mark[color[a[0]]] = true
  mark[color[a[1]]] = true
  mark[color[a[2]]] = true
  if !mark[1] then
    for j in 0..2
      if color[a[j]] == 0 then
	color[a[j]] = 1
	break
      end
    end
  end
  if !mark[2] then
    for j in 0..2
      if color[a[j]] == 0 then
	color[a[j]] = 2
	break
      end
    end
  end
  if !mark[3] then
    for j in 0..2
      if color[a[j]] == 0 then
	color[a[j]] = 3
	break
      end
    end
  end
end

for i in 1..n
  print color[i], " "
end

m,d = gets.split.map{|s| s.to_i}
men = Array::new(m+1,0)
d.times {
	cd = gets.split.map{|s| s.to_i}
	fixed = 1
	cd.each {|i|
		fixed = men[i] if men[i] > 0 # only one men participating in the dance may have color associated previously
	}
	idx = fixed
	cd.each {|i|
		if men[i] != fixed
			men[i] = idx%3 + 1
			idx += 1
		end
	}
}
print men[1..-1].join(" ")

ar=Array.new(100100,0)
n,m=gets.chomp.split.map(&:to_i)
m.times do
	a=gets.chomp.split.map(&:to_i)
	b=[0,0,0,0]
	b[ar[a[0]]],b[ar[a[1]]],b[ar[a[2]]]=1,1,1
	3.times do |i|
		for j in 1...4
			if b[j]==0 && ar[a[i]]==0
				ar[a[i]]=j
				b[j]=1
			end
		end
	end
end
for i in 1..n
	print "#{ar[i]} "
end
puts

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

assignment = {}

m.times do
	arr = gets.split(" ").map(&:to_i)
	colors = [3,2,1]
	intersec = arr.detect{|a| assignment[a]}
	if intersec
		arr = arr - [intersec]
		colors -= [assignment[intersec]]
		# puts "colors #{intersec}"
	end
	arr.each do |a|
		assignment[a] = colors.pop
	end
end
ans = []
assignment.keys.sort.each do |k|
	ans << assignment[k]
end
puts ans.join(" ")

def solution(n, dancers)
  input = {}
  value = 0

  dancers.each do |i|
    color = [1, 2, 3]
    value = 0

    i.each do |j|
      if input.has_key?(j)
        color.delete(input[j])
      end
    end

    i.each_with_index do |j, k|
      value += 1 if input.has_key?(j)
      input[j] = color[k-value] unless input.has_key?(j)
    end
  end

  output = []
  n.times { |i| output << input[i+1] }

  output.join(" ")
end

n, m = STDIN.readline.split(" ").map(&:to_i)
dancers = []
m.times do
  dancers << STDIN.readline.split(" ").map(&:to_i)
end

values = solution(n,dancers)
puts values

#! /usr/bin/env ruby

WHITE = 4
RED = 2
BLUE = 1

def convert(calc_num)
  case calc_num
  when WHITE
    1
  when RED
    2
  when BLUE
    3
  end
end

n, m = STDIN.gets.split(' ').map(&:to_i)
dances = []
m.times {
  dances << STDIN.gets.split(' ').map(&:to_i)
}

colors = Array.new(n){0}

def fill(colors, dancers, color)
  dancers.each do |dancer|
    if colors[dancer.to_i - 1].zero?
      colors[dancer.to_i - 1] = color
      break
    end
  end
  colors
end

dances.each do |dancers|
  result = dancers.inject(0) {|s, i|
    s += colors[i - 1]
  }
  next if result == 7

  if result < WHITE
    colors = fill(colors, dancers, WHITE)
  else
    result -= WHITE
  end

  if result < RED
    colors = fill(colors, dancers, RED)
  else
    result -= RED
  end

  if result < BLUE
    colors = fill(colors, dancers, BLUE)
  end
end

answer = colors.map do |color|
  convert(color)
end.join(' ')
puts answer

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

assignment = {}

m.times do
	arr = gets.split(" ").map(&:to_i)
	colors = [3,2,1]
	intersec = arr.detect{|a| assignment[a]}
	if !intersec
		arr = arr - [intersec]
		colors -= [assignment[intersec]]
		# puts "colors #{intersec}"
	end
	arr.each do |a|
		assignment[a] = colors.pop
	end
end
ans = []
assignment.keys.sort.each do |k|
	ans << assignment[k]
end
puts ans.join(" ")

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

assignment = {}

m.times do
	arr = gets.split(" ").map(&:to_i)
	colors = [3,2,1]
	intersec = arr & assignment.keys
	if !intersec.empty?
		arr = arr - assignment.keys
		colors -= [assignment[intersec[0]]]
		# puts "colors #{intersec}"
	end
	arr.each do |a|
		assignment[a] = colors.pop
	end
end
puts assignment.values.join(" ")

def solution(n, dancers)
  input = {}
  value = 0

  dancers.each do |i|
    color = [1, 2, 3]
    value = 0
    i.each_with_index do |j, k|
      if input.has_key?(j)
        color.delete(input[j])
        value += 1
      else
        input[j] = color[k-value]
      end
    end
  end

  input.values.join(" ")
end

n, m = STDIN.readline.split(" ").map(&:to_i)
dancers = []
m.times do
  dancers << STDIN.readline.split(" ").map(&:to_i)
end

values = solution(n,dancers)
puts values

def solution(n, dancers)
  input = {}
  value = 0

  dancers.each do |i|
    color = [1, 2, 3]
    value = 0
    i. each do |j|
      if input.has_key?(j)
        color.delete(input[j])
        value += 1
      end
    end

    i.each_with_index do |j, k|
        input[j] = color[k-value]
      end
  end

  output = []
  n.times { |i| output << input[i+1] }

  output.join(" ")
end

n, m = STDIN.readline.split(" ").map(&:to_i)
dancers = []
m.times do
  dancers << STDIN.readline.split(" ").map(&:to_i)
end

values = solution(n,dancers)
puts values

def solution(n, dancers)
  input = {}
  value = 0

  dancers.each do |i|
    color = [1, 2, 3]
    value = 0
    i. each do |j|
      if input.has_key?(j)
        color.delete(input[j])
        value += 1
      end
    end

    i.each_with_index do |j, k|
        input[j] = color[k]
      end
  end

  output = []
  n.times { |i| output << input[i+1] }

  output.join(" ")
end

n, m = STDIN.readline.split(" ").map(&:to_i)
dancers = []
m.times do
  dancers << STDIN.readline.split(" ").map(&:to_i)
end

values = solution(n,dancers)
puts values

def solution(n, dancers)
  input = {}
  value = 0

  dancers.each do |i|
    color = [1, 2, 3]
    value = 0
    i.each_with_index do |j, k|
      if input.has_key?(j)
        color.delete(input[j])
        value += 1
      else
        input[j] = color[k-value]
      end
    end
  end

  output = []
  n.times { |i| output << input[i+1] }

  output.join(" ")
end

n, m = STDIN.readline.split(" ").map(&:to_i)
dancers = []
m.times do
  dancers << STDIN.readline.split(" ").map(&:to_i)
end

values = solution(n,dancers)
puts values


Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||.   Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. The only line of each query contains one integer $$$n$$$ ($$$2 \le n \le 10^9$$$) — the number of matches.

For each test case print one integer in single line — the minimum number of matches which you have to buy for assembling CME.

NoteThe first and second queries are explained in the statement.In the third query, you can assemble $$$1 + 3 = 4$$$ (|+|||=||||) without buying matches.In the fourth query, buy one match and assemble $$$2 + 4 = 6$$$ (||+||||=||||||).

gets.to_i.times do
    n = gets.to_i
    puts n == 2 ? 2 : n % 2
end

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1223/A

count = gets.to_i
answers = []

count.times do
  match_count = gets.to_i
  answers << if match_count == 2
               2
             else
                match_count % 2
             end
end

answers.each { |answer| puts answer }

q = gets.to_i
q.times do
  n = gets.to_i
  if n == 1
    puts 3
  elsif n == 2
    puts 2
  else
    a = (n.to_f/2).ceil
    b = n - a
    puts (a-b).abs
  end
end

n = gets.chomp.to_i
n.times do
	ngo = gets.chomp.to_i
	if ngo <= 3
		puts 4 - ngo
	elsif ngo.even?
		puts 0
	else
	  puts 1
	end
end

q = gets.to_i
q.times do
  n = gets.to_i
  puts n < 4 ? 4 - n : n%2
end

1.upto(gets.to_i) do
  n = gets.to_i

  case n
  when 2..4
    puts 4 - n
  when proc(&:odd?)
    puts 1
  else
    puts 0
  end
end


You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.You must paint a fence which consists of $$$10^{100}$$$ planks in two colors in the following way (suppose planks are numbered from left to right from $$$0$$$):   if the index of the plank is divisible by $$$r$$$ (such planks have indices $$$0$$$, $$$r$$$, $$$2r$$$ and so on) then you must paint it red;  if the index of the plank is divisible by $$$b$$$ (such planks have indices $$$0$$$, $$$b$$$, $$$2b$$$ and so on) then you must paint it blue;  if the index is divisible both by $$$r$$$ and $$$b$$$ you can choose the color to paint the plank;  otherwise, you don't need to paint the plank at all (and it is forbidden to spent paint on it). Furthermore, the Government added one additional restriction to make your punishment worse. Let's list all painted planks of the fence in ascending order: if there are $$$k$$$ consecutive planks with the same color in this list, then the Government will state that you failed the labor and execute you immediately. If you don't paint the fence according to the four aforementioned conditions, you will also be executed.The question is: will you be able to accomplish the labor (the time is not important) or the execution is unavoidable and you need to escape at all costs.

The first line contains single integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. The next $$$T$$$ lines contain descriptions of test cases — one per line. Each test case contains three integers $$$r$$$, $$$b$$$, $$$k$$$ ($$$1 \le r, b \le 10^9$$$, $$$2 \le k \le 10^9$$$) — the corresponding coefficients.

Print $$$T$$$ words — one per line. For each test case print REBEL (case insensitive) if the execution is unavoidable or OBEY (case insensitive) otherwise.

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b,k = inp
  gcd = (a).gcd(b)
  max = [a,b].max
  min = [a,b].min
  if(([(max-gcd-1)/min,0].max + 1)>=k)
    puts "REBEL"
    next
  else
    puts "OBEY"
  end
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b,k = inp
  if(r_up(a,b)>k or r_up(b,a)>k)
    puts "REBEL"
  else
    puts "OBEY"
  end
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b,k = inp
  gcd = (a).gcd(b)
  a = a - gcd + 1
  b = b - gcd + 1
  if(r_up(a,b)>k or r_up(b,a)>k)
    puts "REBEL"
    next
  else
    puts "OBEY"
  end
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b,k = inp
  gcd = (a).gcd(b)
  max = [a,b].max
  min = [a,b].min
  if((max-gcd)/min>=k)
    puts "REBEL"
    next
  else
    puts "OBEY"
  end
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
n.times do
  a,b,k = inp
  gcd = (a).gcd(b)
  max = [a,b].max
  min = [a,b].min
  if((max-gcd)/min>=(k) or k == 1)
    puts "REBEL"
    next
  else
    puts "OBEY"
  end
end


There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the number of boxes you have. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^7$$$) — the quantity of candies in each box.

For each test case, print a single integer denoting the minimum number of candies you have to eat to satisfy the requirements.

NoteFor the first test case, you can eat $$$1$$$ candy from the second box, $$$2$$$ candies from the third box, $$$3$$$ candies from the fourth box and $$$4$$$ candies from the fifth box. Now the boxes have $$$[1, 1, 1, 1, 1]$$$ candies in them and you ate $$$0 + 1 + 2 + 3 + 4 = 10$$$ candies in total so the answer is $$$10$$$.For the second test case, the best answer is obtained by making all boxes contain $$$5$$$ candies in them, thus eating $$$995 + 995 + 0 + 995 + 995 + 995 = 4975$$$ candies in total.

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  min = xs.min
  p xs.map { |x| x - min }.sum
end

t = Integer(gets)

for i in 0..t-1
    n = Integer(gets)
    arr = Array.new
    a = gets
    arr = a.split(" ")

    for j in 0..n-1
       arr[j] = Integer(arr[j]);
    end

    mn = arr.min
    ans = 0
    for j in 0..n-1
        ans += (arr[j] - mn)
    end
    puts ans
end

gets.to_i.times do
  gets
  as = gets.split.map(&:to_i)
  m = as.min
  puts as.map { _1 - m }.sum
end

def main
  gets.to_i.times do
    n = gi
    a = gli.sort
    puts a.sum - a[0] * n
  end
end

MOD = 10**9 + 7
def gs = gets.chomp
def gi = gets.to_i
def gli = gets.split.map(&:to_i)
def cyesno(x) = x ? :Yes : :No
def uyesno(x) = x ? :YES : :NO

main

main = -> {
  T = int
  T.times do
      n = int
      a = ints
      m = a.min
      puts a.sum { |x| x - m }
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]