The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).The shop assistant told the teacher that there are m puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of f1 pieces, the second one consists of f2 pieces and so on.Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let A be the number of pieces in the largest puzzle that the teacher buys and B be the number of pieces in the smallest such puzzle. She wants to choose such n puzzles that A - B is minimum possible. Help the teacher and find the least possible value of A - B.

The first line contains space-separated integers n and m (2 ≤ n ≤ m ≤ 50). The second line contains m space-separated integers f1, f2, ..., fm (4 ≤ fi ≤ 1000) — the quantities of pieces in the puzzles sold in the shop.

Print a single integer — the least possible difference the teacher can obtain.

NoteSample 1. The class has 4 students. The shop sells 6 puzzles. If Ms. Manana buys the first four puzzles consisting of 10, 12, 10 and 7 pieces correspondingly, then the difference between the sizes of the largest and the smallest puzzle will be equal to 5. It is impossible to obtain a smaller difference. Note that the teacher can also buy puzzles 1, 3, 4 and 5 to obtain the difference 5.

def main
    n = gets.chomp.to_i
    fi = gets.chomp.split(" ").map{ |e| e.to_i }.sort

    r = 0
    r_s = fi[n-1]-fi[0]
    i = 1
    k = fi.size - n + 1
    while  i<k
        s = fi[i+n-1]-fi[i]
        if (s<r_s)
            r = i
            r_s = s
        end
        i += 1
    end
    puts r_s
end

main()

# cook your code here
n,m=gets.split(/ /).map! {|e| e=e.to_i}
sa=gets.split(/ /).map! {|e| e=e.to_i}
sa = sa.sort { |x,y| x<=>y  }
min=100000000000

for i in 0..(m-n)
    j=i+n-1
    l=(sa[j]-sa[i])
    if(min>l)
        min=l
    end
end
puts min

n, m = gets.split(' ').map(&:to_i)
ar = gets.split(' ').map(&:to_i).sort
n -= 1
puts (n...m).map{|x| ar[x]-ar[x-n]}.min

n_m = gets.split.map &:to_i
n = n_m[0]
m = n_m[1]

puzzles = gets.split.map(&:to_i).sort

min_difficulty = Float::INFINITY

(m - n + 1).times do |i|
  difficulty = puzzles[i+n-1] - puzzles[i]
  min_difficulty = difficulty if difficulty < min_difficulty
end

puts min_difficulty

#!/usr/bin/ruby
n=gets.to_i
p gets.split.map(&:to_i).sort.each_cons(n).map{|e|e.last-e.first}.min

tmp = gets.chomp.split(" ")
n = tmp[0].to_i
m = tmp[1].to_i
a = gets.chomp.split(" ").map {|x| x.to_i}
a = a.sort
min = a[n-1] - a[0]
for i in 1..m-n
  min = a[i+n-1]-a[i] if a[i+n-1]-a[i] < min
end
puts min

g=->{gets.split.map(&:to_i)}
n,m=g[]
a=g[].sort
p (m-n+1).times.map{|i|a[i+n-1]-a[i]}.min

n, m=gets.split(" ").map {|i| i.to_i}
arr = gets.split(" ").map{|i| i.to_i}.sort!
answer=(m-n+1).times.map{|i| arr[i+n-1]-arr[i]}.min

p answer

inp = STDIN.gets <<-EOF
EOF

inp = inp.split("\n")

stu_num = inp[0].split(" ")[0].to_i
puz_num = inp[0].split(" ")[1].to_i
puz_difs = inp[1].split(" ").map(&:to_i).sort

min_dif_div = if stu_num < puz_num
                puz_difs.first(puz_difs.length - stu_num + 1).inject([]) do |divs,i|
                  divs << (puz_difs[puz_difs.index(i) + stu_num - 1] - i)
                end.sort.first
              else
                puz_difs.max - puz_difs.min
              end

puts min_dif_div

n,m=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i).sort
min=a.last
i=0
while i+n-1<m
	if (a[i+n-1]-a[i])<min
		min=a[i+n-1]-a[i]
	end
	i+=1
end
puts min

MAX_INT = 1<<31

n, m = $stdin.readline.split.map(&:to_i)
f = $stdin.readline.split.map(&:to_i)

class Array
    def diameter
        m = 0
        for i in 0...self.count
            for j in i+1...self.count
                t = (self[i]-self[j]).abs
                if t>m
                    m = t
                end
            end
        end
        m
    end

    def complect_and_count
        self.dup.complect_and_count!
    end

    def complect_and_count!
        a = self.shift
        h = {a => 1}
        k = 1
        while self.size>0
            b = self.shift
            if a != b
                h[a] = k
                h[b] = 1
                k = 0
            end
            a = b
            k += 1
        end
        h[b]=k
        h
    end
end

f.sort!
#p f
f_uniq = f.uniq
#p f_uniq
ff = f.complect_and_count
#p ff

# t_s = ff.collect do |key,value|
#   [key]*value
# end

# t = t_s.dup

# идея алгоритма: вокруг каждого элемента начинаю образовывать круг минимального радиуса
# когда будет построен круг содержащий более n элементов - начинаю смотреть какой из кругов лучший

# for each f_uniq we build an area
areas = []
for i in 0...f_uniq.count
    elem = f_uniq[i]
    areas[i] = {elements: [elem]*ff[elem], diameter: 0}
end

def area_found?(areas,n)
    a_with_max_count = areas.max_by {|e| e.count}
    a_with_max_count[:elements].count >= n
end

l = 1
until area_found?(areas,n)
    # add one elem to each area
    areas.each do |a|
        elements = a[:elements]

        next if elements.count >= l

        a_min = elements.min
        a_max = elements.max
        t_min, _ = f_uniq.partition {|el| el<a_min}
        t_max, _ = f_uniq.partition {|el| el>a_max}
        t_min = t_min.last
        t_max = t_max.first
        d1 = t_min.nil? ? MAX_INT : a_min - t_min
        d2 = t_max.nil? ? MAX_INT : t_max - a_max

        if d2 <= d1
            a[:elements] = elements + [t_max]*ff[t_max]
            a[:diameter] += d2
        elsif d1 < d2
            a[:elements] = ([t_min]*ff[t_min]) + elements
            a[:diameter] += d1
        end
    end
    l+=1
end

min = areas.min_by {|el|  el[:elements].count >= n ? el[:diameter] : MAX_INT }
puts min[:diameter]

n, m = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i).sort
ret = 1000
for i in 0...a.size-n+1
  ret = [a[i+n-1] - a[i], ret].min
end
puts ret

def run
  n, m = $stdin.gets.split.map(&:to_i)
  f = $stdin.gets.split.map(&:to_i)
  f.sort!

  min = 1 << 31
  for i in 0..(m - n)
    d = f[i,n].max - f[i,n].min
    min = [d, min].min
  end

  puts min
end

run if $0 == __FILE__

n, m = gets.split.map &:to_i
arr = gets.split.map &:to_i
arr = arr.sort
min = arr.max
(m - n + 1).times do |fig|
  min = arr[fig + n - 1] - arr[fig] if min > arr[fig + n - 1] - arr[fig]
end
puts min

students, puzzles = gets.chomp.split(/ /).map(&:to_i)
pieces = gets.chomp.split(/ /).map(&:to_i)
pieces.sort!
min = -1
pos = -1
puzzles.times do |i|
    break if i + (students - 1) >= puzzles
    first = pieces[i]
    last = pieces[i + (students - 1)]
    diff = last - first
    min = diff if min == -1
    next if diff > min
    min = [min, diff].min
    pos = i
end
puts pieces[pos + (students - 1)] - pieces[pos]

a,b=gets.split.map{|e| e.to_i}
x=gets.split.map{|e| e.to_i}.sort
ans=x[a-1]-x[0]
0.upto(x.size-a){|i|
	ans=[ans,x[i+a-1]-x[i]].min
}
puts ans

n, m = gets.split.map(&:to_i)
f = gets.split.map(&:to_i).sort
min_diff = 1001

(0..m-n).each do |i|
	if f[i+n-1]-f[i] < min_diff
		min_diff = f[i+n-1] - f[i]
	end
end
puts min_diff

n, m = gets.chomp.split(' ').map(&:to_i)
f = gets.chomp.split(' ').map(&:to_i).sort

mins = []
(0..m-n).each do |i|
	mins << f[i+n-1] - f[i]
end

puts mins.min

n, m = gets.strip.split(' ').map &:to_i
array = gets.strip.split(' ').map(&:to_i).sort

min = array.last
0.upto(m - n) do |index|
  min = [array[index + n - 1] - array[index], min].min
end

puts min

nm = gets.chomp
nm = nm.split
students = nm[0].to_i
puzzles = nm[1].to_i
quantities = gets.chomp
quantities = quantities.split

for i in (0..puzzles-1)
	for x in (i..puzzles-1)
		if i != x
			if quantities[i].to_i > quantities[x].to_i
				temp = quantities[i].to_i
				quantities[i] = quantities[x].to_i
				quantities[x] = temp
			end
		end
	end
end

minimum = 0
for i in (0..puzzles-1)
	if quantities[i+students-1].to_i - quantities[i].to_i < minimum && i > 0 && i+students-1 <= puzzles - 1
		minimum = quantities[i+students-1].to_i - quantities[i].to_i
	elsif i == 0 && i+students-1 <= puzzles - 1
		minimum = quantities[i+students-1].to_i - quantities[i].to_i
	end
end

print minimum

#!/usr/bin/env ruby

# Solves http://codeforces.com/problemset/problem/337/A

n, m = $stdin.gets.split.map { |s| s.to_i }
nums = $stdin.gets.split.map { |s| s.to_i }
nums.sort!
diffs = (0..(m-n)).map { |i| nums[n + i - 1] - nums[i] }
puts diffs.sort![0]

m,n = gets.split(" ").map(&:to_i)
arr = gets.split(" ").map(&:to_i)
min_diff = arr.max
arr.sort!
for i in (m-1..n-1)
  diff = arr[i] - arr[i- m +1]
  min_diff = diff if diff < min_diff
end
puts min_diff

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

min = p[-1] - p[0]

for i in (a-1..b-1)
  min = [min, p[i] - p[i - a + 1]].min
end

puts min

def solution(n, pices)
  pices.sort!
  min_diff = 2 << 2048

  for i in n-1...pices.size do
    min_diff = [min_diff, pices[i] - pices[i - n + 1]].min
  end

  min_diff
end

n, m = gets.strip.split().map { |i| i.to_i }
pices = gets.strip.split().map { |i| i.to_i }

puts solution(n, pices)

n, m = gets.split.map{|x| x.to_i}
a = gets.split.map{|x| x.to_i}.sort
p (m - n + 1).times.map{|i| a[i + n - 1] - a[i]}.min

n,m = gets.split(" ").map(&:to_i)
a = gets.split(" ").map(&:to_i).sort
min = 99999
for i in 0..(m-n)
    if(min>a[i+n-1]-a[i])
        min = a[i+n-1]-a[i]
    end
end
print(min)

n,m=gets.split.map(&:to_i)
a=gets.split.map(&:to_i).sort
r=1001
(m-n+1).times {|i|r=[r,a[i+n-1]-a[i]].min}
p r

n, m = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i).sort

min = 2000
while a.size >= n
  min = [min, a[n-1]-a.first].min
  a.shift
end

puts min

input = ARGV ? $< : File(ARGV[0])

n, m = input.gets.split(' ').map &:to_i
arr = input.gets.split(' ').map &:to_i

arr.sort!()

diff = arr[n-1] - arr[0]
stop = m - n
for i in (1..stop)
	local = arr[n-1+i] - arr[i]
	diff = [diff, local].min
end

puts diff

m, n = gets.chomp.split.map { |x| x.to_i }
a = gets.chomp.split.map { |x| x.to_i }.sort
min = 1000
for i in 0..n - m
  diff = a[i + m - 1] - a[i]
  min = diff if diff < min
end
puts min

n, m = gets.chomp.split(' ').map!(&:to_i)

ary = gets.chomp.split(' ').map!(&:to_i).sort!.reverse!

min = ary.first - ary.last

for i in 0..(ary.size - n) do
  if ary[i] - ary[i + n - 1] < min
    min =  ary[i] - ary[i + n - 1]
  end
end

p min

#!ruby

n, m = gets.split.map{|e| e.to_i}

p = gets.split.map{|e| e.to_i}

ans = 9999

p.sort!

(m-n+1).times do |i|
  ans = [ans, p[i+n-1]-p[i]].min
end

puts ans

def main
    n = gets.chomp.to_i
    fi = gets.chomp.split(" ").map{ |e| e.to_i }.sort

    r = 0
    r_s = fi[n-1]-fi[0]
    i = 1
    k = fi.size - n
    while  i<k
        s = fi[i+n-1]-fi[i]
        if (s<r_s)
            r = i
            r_s = s
        end
        i += 1
    end
    puts r_s
end

main()

# cook your code here
n,m=gets.split(/ /).map! {|e| e=e.to_i}
sa=gets.split(/ /).map! {|e| e=e.to_i}
sa = sa.sort { |x,y| x<=>y  }
puts (sa[n-1]-sa[0])

n_m = gets.split.map &:to_i
n = n_m[0]
m = n_m[1]

puzzles = gets.split.map(&:to_i).sort

min_difficulty = Float::INFINITY

(m - n).times do |i|
  difficulty = puzzles[i+n-1] - puzzles[i]
  min_difficulty = difficulty if difficulty < min_difficulty
end

puts min_difficulty

#!/usr/bin/ruby
n=gets.to_i
p gets.split.map(&:to_i).sort.each_cons(n).min{|e|e.last-e.first}

tmp = gets.chomp.split(" ")
a = gets.chomp.split(" ").map {|x| x.to_i}
a = a.sort
puts a[tmp[0].to_i-1]-a[0]
#puts array[0] + ", " + array[n]

inp = STDIN.gets <<-EOF
EOF

inp = inp.split("\n")

stu_num = inp[0].split(" ")[0].to_i
puz_num = inp[0].split(" ")[1].to_i

puz_difs = inp[1].split(" ").map(&:to_i).sort
min_dif_div = puz_difs.first(puz_difs.length - stu_num).inject([]){|divs,i| divs << (puz_difs[puz_difs.index(i) + stu_num - 1] - i)}.first
puts min_dif_div

inp = STDIN.gets <<-EOF
EOF

inp = inp.split("\n")

stu_num = inp[0].split(" ")[0].to_i
puz_num = inp[0].split(" ")[1].to_i
puz_difs = inp[1].split(" ").map(&:to_i).sort

min_dif_div = if stu_num < puz_num
                puz_difs.first(puz_difs.length - stu_num).inject([]){|divs,i| divs << (puz_difs[puz_difs.index(i) + stu_num - 1] - i)}.first
              else
                puz_difs.max - puz_difs.min
              end

puts min_dif_div

MAX_INT = 1<<31

n, m = $stdin.readline.split.map(&:to_i)
f = $stdin.readline.split.map(&:to_i)

class Array
    def diameter
        m = 0
        for i in 0...self.count
            for j in i+1...self.count
                t = (self[i]-self[j]).abs
                if t>m
                    m = t
                end
            end
        end
        m
    end

    def complect_and_count
        self.dup.complect_and_count!
    end

    def complect_and_count!
        a = self.shift
        h = {a => 1}
        k = 1
        while self.size>0
            b = self.shift
            if a != b
                h[a] = k
                h[b] = 1
                k = 0
            end
            a = b
            k += 1
        end
        h[b]=k
        h
    end
end

f.sort!
#p f
f_uniq = f.uniq
#p f_uniq
ff = f.complect_and_count
#p ff

# t_s = ff.collect do |key,value|
#   [key]*value
# end

# t = t_s.dup

# идея алгоритма: вокруг каждого элемента начинаю образовывать круг минимального радиуса
# когда будет построен круг содержащий более n элементов - начинаю смотреть какой из кругов лучший

# for each f_uniq we build an area
areas = []
for i in 0...f_uniq.count
    elem = f_uniq[i]
    areas[i] = {elements: [elem]*ff[elem], diameter: 0}
end

def area_found?(areas,n)
    a_with_max_count = areas.max_by {|e| e.count}
    a_with_max_count[:elements].count >= n
end

l = 1
until area_found?(areas,n)
    # add one elem to each area
    areas.each do |a|
        elements = a[:elements]

        next if elements.count >= l

        a_min = elements.min
        a_max = elements.max
        t_min, _ = f_uniq.partition {|el| el<a_min}
        t_max, _ = f_uniq.partition {|el| el>a_max}
        t_min = t_min.last
        t_max = t_max.first
        d1 = t_min.nil? ? MAX_INT : a_min - t_min
        d2 = t_max.nil? ? MAX_INT : t_max - a_max

        if d2 <= d1
            a[:elements] = elements + [t_max]*ff[t_max]
            a[:diameter] += d2
        elsif d1 < d2
            a[:elements] = ([t_min]*ff[t_min]) + elements
            a[:diameter] += d1
        end
    end
    l+=1
end

min = areas.min_by {|el| el[:diameter]}
puts min[:diameter]

    MAX_INT = 1<<31

    n, m = $stdin.readline.split.map(&:to_i)
    f = $stdin.readline.split.map(&:to_i)

    class Array
        def diameter
            m = 0
            for i in 0...self.count
                for j in i+1...self.count
                    t = (self[i]-self[j]).abs
                    if t>m
                        m = t
                    end
                end
            end
            m
        end

        def complect_and_count
            self.dup.complect_and_count!
        end

        def complect_and_count!
            a = self.shift
            h = {a => 1}
            k = 1
            while self.size>0
                b = self.shift
                if a != b
                    h[a] = k
                    h[b] = 1
                    k = 0
                end
                a = b
                k += 1
            end
            h[b]=k
            h
        end
    end

    f.sort!
    #p f
    f_uniq = f.uniq.sort
    #p f_uniq
    ff = f.complect_and_count
    #p ff

    t_s = ff.collect do |key,value|
        [key]*value
    end

    t = t_s.dup

    diameters = Array.new(t_s.count, 0)

    loop do

        min_d = MAX_INT
        min_d_count = 0
        min_i = nil

        for i in 0...t.count
            elem = t[i]
            elem_d = elem.diameter
            if elem_d <= min_d && (elem.count>=n || elem.count>=min_d_count)
                min_d = elem_d
                min_d_count = elem.count
                min_i = i
            end
        end

        #p t[min_i]
        #puts "total count = #{t.count}, d = #{min_d}, count = #{min_d_count}"

        if t[min_i].count >= n
            p t[min_i].diameter
            break
        else
            tt = []
            for i in 0...t.count
                t_elem = t[i]
                ttt = f_uniq - t_elem
                t_elem_min = t_elem.min
                t_elem_max = t_elem.max

                tmp1,_ = ttt.partition {|el| el<t_elem_min}
                tmp1_max = tmp1.max
                count1 = tmp1_max.nil? ? 0 : ff[tmp1_max]
                d1 = tmp1_max.nil? ? MAX_INT : tmp1_max - t_elem_min

                tmp2,_ = ttt.partition {|el| el>t_elem_max}
                tmp2_min = tmp2.min
                count2 =tmp2_min.nil? ? 0 : ff[tmp2_min]
                d2 = tmp2_min.nil? ? MAX_INT : t_elem_max - tmp2_min

                to_add = nil
                if d2 < d1
                    tt << t_elem + ([tmp2_min]*count2)
                elsif d1 < d2
                    tt << ([tmp1_max]*count1) + t_elem
                elsif d1==d2 && d1!=MAX_INT
                    tt << ([tmp1_max]*count1) + t_elem
                    tt << t_elem + ([tmp2_min]*count2)
                end

                # if count1+count2>0
                #   tmp3 = ([tmp1_max]*count1) + t_elem + ([tmp2_min]*count2)
                #   tt << tmp3.compact
                # end
            end

            t = tt
        end

    end

    MAX_INT = 1<<31

    n, m = $stdin.readline.split.map(&:to_i)
    f = $stdin.readline.split.map(&:to_i)

    class Array
        def diameter
            m = 0
            for i in 0...self.count
                for j in i+1...self.count
                    t = (self[i]-self[j]).abs
                    if t>m
                        m = t
                    end
                end
            end
            m
        end

        def complect_and_count
            self.dup.complect_and_count!
        end

        def complect_and_count!
            a = self.shift
            h = {a => 1}
            k = 1
            while self.size>0
                b = self.shift
                if a != b
                    h[a] = k
                    h[b] = 1
                    k = 0
                end
                a = b
                k += 1
            end
            h[b]=k
            h
        end
    end

    f.sort!
    #p f
    f_uniq = f.uniq.sort
    #p f_uniq
    ff = f.complect_and_count
    #p ff

    t_s = ff.collect do |key,value|
        [key]*value
    end

    t = t_s.dup

    diameters = Array.new(t_s.count, 0)

    loop do

        min_d = MAX_INT
        min_d_count = 0
        min_i = nil

        for i in 0...t.count
            elem = t[i]
            elem_d = elem.diameter
            if elem_d <= min_d && (elem.count>=n || elem.count>=min_d_count)
                min_d = elem_d
                min_d_count = elem.count
                min_i = i
            end
        end

        #p t[min_i]
        #puts "total count = #{t.count}, d = #{min_d}, count = #{min_d_count}"

        if t[min_i].count >= n
            p t[min_i].diameter
            break
        else
            tt = []
            for i in 0...t.count
                t_elem = t[i]
                ttt = f_uniq - t_elem
                t_elem_min = t_elem.min
                t_elem_max = t_elem.max

                tmp1,_ = ttt.partition {|el| el<t_elem_min}
                tmp1_max = tmp1.max

                count1 = 0
                unless tmp1_max.nil?
                    count1 = ff[tmp1_max]
                end

                tmp2,_ = ttt.partition {|el| el>t_elem_max}
                tmp2_min = tmp2.min
                count2 = 0
                unless tmp2_min.nil?
                    count2 = ff[tmp2_min]
                end

                # if count1>0
                #   tmp3 = ([tmp1_max]*count1) + t_elem
                #   tt << tmp3.compact
                # end

                # if count2>0
                #   tmp3 = t_elem + ([tmp2_min]*count2)
                #   tt << tmp3.compact
                # end

                if count1+count2>0
                    tmp3 = ([tmp1_max]*count1) + t_elem + ([tmp2_min]*count2)
                    tt << tmp3.compact
                end
            end

            t = tt
        end

    end

MAX_INT = 1<<31

n, m = $stdin.readline.split.map(&:to_i)
f = $stdin.readline.split.map(&:to_i)

class Array
	def diameter
		m = 0
		for i in 0...self.count
			for j in i+1...self.count
				t = (self[i]-self[j]).abs
				if t>m
					m = t
				end
			end
		end
		m
	end

	def complect_and_count
		self.dup.complect_and_count!
	end

	def complect_and_count!
		a = self.shift
		h = {a => 1}
		k = 1
		while self.size>0
			b = self.shift
			if a != b
				h[a] = k
				h[b] = 1
				k = 0
			end
			a = b
			k += 1
		end
		h[b]=k
		h
	end
end

f.sort!
#p f
f_uniq = f.uniq
#p f_uniq
ff = f.complect_and_count
#p ff

# t_s = ff.collect do |key,value|
# 	[key]*value
# end

# t = t_s.dup

# идея алгоритма: вокруг каждого элемента начинаю образовывать круг минимального радиуса
# когда будет построен круг содержащий более n элементов - начинаю смотреть какой из кругов лучший

# for each f_uniq we build an area
areas = []
for i in 0...f_uniq.count
	elem = f_uniq[i]
	areas[i] = {elements: [elem]*ff[elem], diameter: 0}
end

def area_found?(areas,n)
	a_with_max_count = areas.max_by {|e| e.count}
	a_with_max_count[:elements].count >= n
end

until area_found?(areas,n)
	# add one elem to each area
	areas.each do |a|
		elements = a[:elements]
		a_min = elements.min
		a_max = elements.max
		t_min, _ = f_uniq.partition {|el| el<a_min}
		t_max, _ = f_uniq.partition {|el| el>a_max}
		t_min = t_min.last
		t_max = t_max.first
		d1 = t_min.nil? ? MAX_INT : a_min - t_min
		d2 = t_max.nil? ? MAX_INT : t_max - a_max

		if d2 <= d1
			a[:elements].push(t_max)
			a[:diameter] += d2
		elsif d1 < d2
			a[:elements].unshift(t_min)
			a[:diameter] += d1
		end
	end

end

min = areas.min_by {|el| el[:diameter]}
puts min[:diameter]

    MAX_INT = 1<<31

    n, m = $stdin.readline.split.map(&:to_i)
    f = $stdin.readline.split.map(&:to_i)

    class Array
        def diameter
            m = 0
            for i in 0...self.count
                for j in i+1...self.count
                    t = (self[i]-self[j]).abs
                    if t>m
                        m = t
                    end
                end
            end
            m
        end

        def complect_and_count
            self.dup.complect_and_count!
        end

        def complect_and_count!
            a = self.shift
            h = {a => 1}
            k = 1
            while self.size>0
                b = self.shift
                if a != b
                    h[a] = k
                    h[b] = 1
                    k = 0
                end
                a = b
                k += 1
            end
            h[b]=k
            h
        end
    end

    f.sort!
    p f
    f_uniq = f.uniq.sort
    p f_uniq
    ff = f.complect_and_count
    p ff

    t_s = ff.collect do |key,value|
        [key]*value
    end

    t = t_s.dup

    diameters = Array.new(t_s.count, 0)

    loop do

        min_d = MAX_INT
        min_d_count = 0
        min_i = nil

        for i in 0...t.count
            elem = t[i]
            elem_d = elem.diameter
            if elem_d <= min_d && (elem.count>=n || elem.count>=min_d_count)
                min_d = elem_d
                min_d_count = elem.count
                min_i = i
            end
        end

        #p t[min_i]
        #puts "total count = #{t.count}, d = #{min_d}, count = #{min_d_count}"

        if t[min_i].count >= n
            puts t[min_i].diameter
            break
        else
            tt = []
            for i in 0...t.count
                t_elem = t[i]
                ttt = f_uniq - t_elem
                t_elem_min = t_elem.min
                t_elem_max = t_elem.max

                tmp1,_ = ttt.partition {|el| el<t_elem_min}
                tmp1_max = tmp1.max

                count1 = 0
                unless tmp1_max.nil?
                    count1 = ff[tmp1_max]
                end

                tmp2,_ = ttt.partition {|el| el>t_elem_max}
                tmp2_min = tmp2.min
                count2 = 0
                unless tmp2_min.nil?
                    count2 = ff[tmp2_min]
                end

                # if count1>0
                #   tmp3 = ([tmp1_max]*count1) + t_elem
                #   tt << tmp3.compact
                # end

                # if count2>0
                #   tmp3 = t_elem + ([tmp2_min]*count2)
                #   tt << tmp3.compact
                # end

                if count1+count2>0
                    tmp3 = ([tmp1_max]*count1) + t_elem + ([tmp2_min]*count2)
                    tt << tmp3.compact
                end
            end

            t = tt
        end

    end

MAX_INT = 1<<31

n, m = $stdin.readline.split.map(&:to_i)
f = $stdin.readline.split.map(&:to_i)

class Array
    def diameter
        m = 0
        for i in 0...self.count
            for j in i+1...self.count
                t = (self[i]-self[j]).abs
                if t>m
                    m = t
                end
            end
        end
        m
    end

    def complect_and_count
        self.dup.complect_and_count!
    end

    def complect_and_count!
        a = self.shift
        h = {a => 1}
        k = 1
        while self.size>0
            b = self.shift
            if a != b
                h[a] = k
                h[b] = 1
                k = 0
            end
            a = b
            k += 1
        end
        h[b]=k
        h
    end
end

f.sort!
#p f
f_uniq = f.uniq
#p f_uniq
ff = f.complect_and_count
#p ff

# t_s = ff.collect do |key,value|
#   [key]*value
# end

# t = t_s.dup

# идея алгоритма: вокруг каждого элемента начинаю образовывать круг минимального радиуса
# когда будет построен круг содержащий более n элементов - начинаю смотреть какой из кругов лучший

# for each f_uniq we build an area
areas = []
for i in 0...f_uniq.count
    elem = f_uniq[i]
    areas[i] = {elements: [elem]*ff[elem], diameter: 0}
end

def area_found?(areas,n)
    a_with_max_count = areas.max_by {|e| e.count}
    a_with_max_count[:elements].count >= n
end

until area_found?(areas,n)
    # add one elem to each area
    areas.each do |a|
        elements = a[:elements]
        a_min = elements.min
        a_max = elements.max
        t_min, _ = f_uniq.partition {|el| el<a_min}
        t_max, _ = f_uniq.partition {|el| el>a_max}
        t_min = t_min.last
        t_max = t_max.first
        d1 = t_min.nil? ? MAX_INT : a_min - t_min
        d2 = t_max.nil? ? MAX_INT : t_max - a_max

        if d2 <= d1
            a[:elements] = elements + [t_max]*ff[t_max]
            a[:diameter] += d2
        elsif d1 < d2
            a[:elements] = ([t_min]*ff[t_min]) + elements
            a[:diameter] += d1
        end
    end

end

min = areas.min_by {|el| el[:diameter]}
puts min[:diameter]

MAX_INT = 1<<31

n, m = $stdin.readline.split.map(&:to_i)
f = $stdin.readline.split.map(&:to_i)

class Array
	def diameter
		m = 0
		for i in 0...self.count
			for j in i+1...self.count
				t = (self[i]-self[j]).abs
				if t>m
					m = t
				end
			end
		end
		m
	end
end

def solve(n,f)
	if n == 1
		f
	else
		md = MAX_INT
		mf = []
		for i in 0...f.count
			tf = f[0...i] + f[(i+1)..-1] # f \ f[i]
			td = tf.diameter
			if td < md
				ff = solve(n-1, tf)
				md = td
				mf = ff + [f[i]]
			end
		end
		mf
	end
end

t = solve(n,f)[0...n]
#p t
puts t.diameter

n, m = $stdin.readline.split.map(&:to_i)
f = $stdin.readline.split.map(&:to_i)

f.sort!
t = f[0...n]
puts t.max - t.min

    MAX_INT = 1<<31

    n, m = $stdin.readline.split.map(&:to_i)
    f = $stdin.readline.split.map(&:to_i)

    class Array
        def diameter
            m = 0
            for i in 0...self.count
                for j in i+1...self.count
                    t = (self[i]-self[j]).abs
                    if t>m
                        m = t
                    end
                end
            end
            m
        end

        def complect_and_count
            self.dup.complect_and_count!
        end

        def complect_and_count!
            a = self.shift
            h = {a => 1}
            k = 1
            while self.size>0
                b = self.shift
                if a != b
                    h[a] = k
                    h[b] = 1
                    k = 0
                end
                a = b
                k += 1
            end
            h[b]=k
            h
        end
    end

    f.sort!
    p f
    f_uniq = f.uniq.sort
    p f_uniq
    ff = f.complect_and_count
    p ff

    t_s = ff.collect do |key,value|
        [key]*value
    end

    t = t_s.dup

    diameters = Array.new(t_s.count, 0)

    loop do

        min_d = MAX_INT
        min_d_count = 0
        min_i = nil

        for i in 0...t.count
            elem = t[i]
            elem_d = elem.diameter
            if elem_d <= min_d && (elem.count>=n || elem.count>=min_d_count)
                min_d = elem_d
                min_d_count = elem.count
                min_i = i
            end
        end

        p t[min_i]
        puts "total count = #{t.count}, d = #{min_d}, count = #{min_d_count}"

        if t[min_i].count >= n
            p t[min_i].diameter
            break
        else
            tt = []
            for i in 0...t.count
                t_elem = t[i]
                ttt = f_uniq - t_elem
                t_elem_min = t_elem.min
                t_elem_max = t_elem.max

                tmp1,_ = ttt.partition {|el| el<t_elem_min}
                tmp1_max = tmp1.max

                count1 = 0
                unless tmp1_max.nil?
                    count1 = ff[tmp1_max]
                end

                tmp2,_ = ttt.partition {|el| el>t_elem_max}
                tmp2_min = tmp2.min
                count2 = 0
                unless tmp2_min.nil?
                    count2 = ff[tmp2_min]
                end

                # if count1>0
                #   tmp3 = ([tmp1_max]*count1) + t_elem
                #   tt << tmp3.compact
                # end

                # if count2>0
                #   tmp3 = t_elem + ([tmp2_min]*count2)
                #   tt << tmp3.compact
                # end

                if count1+count2>0
                    tmp3 = ([tmp1_max]*count1) + t_elem + ([tmp2_min]*count2)
                    tt << tmp3.compact
                end
            end

            t = tt
        end

    end

n, m = gets.split.map &:to_i
arr = gets.split.map &:to_i
if arr.size - arr.uniq.size == n - 1
  puts "0"
else
  arr = arr.sort
  puts arr[n - 1] - arr.first
end

n, m = gets.split.map &:to_i
arr = gets.split.map &:to_i
arr = arr.sort
puts arr[n - 1] - arr[0]

n, m = gets.split.map &:to_i
arr = gets.split.map &:to_i
arr = arr.sort
if arr.uniq.size == arr.size
  puts arr[n - 1] - arr[0]
else
  puts 0
end

students = gets.chomp.split(/ /).map(&:to_i)[0]
pieces = gets.chomp.split(/ /).map(&:to_i)
pieces.sort!
puts pieces[students - 1] - pieces[0]

#!/usr/bin/env ruby

# Solves http://codeforces.com/problemset/problem/337/A

n, m = $stdin.gets.split.map { |s| s.to_i }
nums = $stdin.gets.split.map { |s| s.to_i }
nums.sort!
diffs = (0..(m-n)).map { |i| nums[n + i - 1] - nums[0] }
puts diffs.sort![0]

n,m = gets.split(" ").map(&:to_i)
a = gets.split(" ").map(&:to_i).sort
min = 99999
for i in 0..(m-n-1)
    if(min>a[i+n-1]-a[i])
        min = a[i+n-1]-a[i]
    end
end
print(min)

n, m = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i).sort

min = 2000
while a.size >= m
  min = [min, a[n-1]-a.first].min
  a.shift
end

puts min


Let's denote a function $$$f(x)$$$ in such a way: we add $$$1$$$ to $$$x$$$, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,   $$$f(599) = 6$$$: $$$599 + 1 = 600 \rightarrow 60 \rightarrow 6$$$;  $$$f(7) = 8$$$: $$$7 + 1 = 8$$$;  $$$f(9) = 1$$$: $$$9 + 1 = 10 \rightarrow 1$$$;  $$$f(10099) = 101$$$: $$$10099 + 1 = 10100 \rightarrow 1010 \rightarrow 101$$$. We say that some number $$$y$$$ is reachable from $$$x$$$ if we can apply function $$$f$$$ to $$$x$$$ some (possibly zero) times so that we get $$$y$$$ as a result. For example, $$$102$$$ is reachable from $$$10098$$$ because $$$f(f(f(10098))) = f(f(10099)) = f(101) = 102$$$; and any number is reachable from itself.You are given a number $$$n$$$; your task is to count how many different numbers are reachable from $$$n$$$.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

Print one integer: the number of different numbers that are reachable from $$$n$$$.

require "set"

def f(n)
	s = (n+1).to_s
	s[...(s =~ /0+$/)].to_i
end

n = gets.to_i
s = Set.new
while !s.include?(n)
	s.add(n)
	n = f(n)
end
p s.size

# your code goes here

$store = {}

def trim_trailing_zeroes(y)
	y_string = y.to_s
	i = y_string.length - 1
	index_non_zero = 0
	while i >= 1 do
		if y_string[i] != "0"
			index_non_zero = i
			break
		end
		i -= 1
	end

	return y_string[0..index_non_zero]
end

def cal(x)
	if !$store[x].nil?
		return
	end
	$store[x] = 1
	execute_for = trim_trailing_zeroes(x + 1)
	cal(execute_for.to_i)
end

value = gets.to_i
cal(value)

p $store.keys.size

N = gets.to_i
n = N
checked = {}

while n > 9
  checked[n] = true
  n += 1
  n = n.to_s.reverse.to_i.to_s.reverse.to_i
end

puts checked.keys.count + 9

require 'set'

n = gets.strip.to_i
seen = Set.new

while !seen.include?(n)
  seen.add(n)
  begin
    n += 1
    seen.add(n) if !seen.include?(n) && n % 10 != 0
  end while n % 10 != 0
  while n % 10 == 0
    n /= 10
  end
end

puts seen.size

n = gets.to_i
a = Hash.new(false)
while !a[n]
    a[n] = true
    n += 1
    n /= 10 while n%10 == 0
end
puts a.size

n = gets.to_i
a = Hash.new(false)
a[n] = true
while !a[1]
    n += 1
    n /= 10 while n%10 == 0
    a[n] = true
end
puts a.size

n = gets.to_i
ans = 1
while n > 1
    n += 1
    n /= 10 while n%10 == 0
    ans += 1
end
puts ans

n = gets.to_i
a = Hash.new(false)
a[n] = true
while n > 1
    n += 1
    n /= 10 while n%10 == 0
    a[n] = true
end
puts a.size


The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.

The only line of input contains one integer n (1 ≤ n ≤ 55) — the maximum length of a number that a door-plate can hold.

Output one integer — the maximum number of offices, than can have unique lucky numbers not longer than n digits.

n = gets.chomp.to_i;
ans = 0;
n.times{|i| ans += 2**(i+1)}
p ans

x = gets.chomp.to_i
sum = (0)
for i in 1 .. x
  sum = sum + 2**i
end

print sum

n = gets.chomp.to_i

ans = 0

(1..n).each do |i|
ans = ans + (2**i)
end

puts ans

n = gets.to_i

k = 2
s = 0
n.times do
   s += k
   k *= 2
end

puts s

#!/usr/bin/ruby

# Get one number at a time
N = STDIN.gets.to_i

res = 0

(1..N).each do |x|
	res += 2 ** x
end

puts res

n = gets.strip.to_i
puts (1..n).inject(0){|r, el| r + 2**el}

n = gets.to_i

k = 2
s = 2
(n-1).times do
   s += 6
   k *= 2
end

puts n == 1 ? 2 : s

n = gets.to_i

k = 2
s = 0
(n-1).times do
   s += k*3
   k *= 2
end

puts n == 1 ? 2 : s


Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequence), or all pressed buttons return to the initial position. When all buttons are pressed into the lock at once, the lock opens.Consider an example with three buttons. Let's say that the opening sequence is: {2, 3, 1}. If you first press buttons 1 or 3, the buttons unpress immediately. If you first press button 2, it stays pressed. If you press 1 after 2, all buttons unpress. If you press 3 after 2, buttons 3 and 2 stay pressed. As soon as you've got two pressed buttons, you only need to press button 1 to open the lock.Manao doesn't know the opening sequence. But he is really smart and he is going to act in the optimal way. Calculate the number of times he's got to push a button in order to open the lock in the worst-case scenario.

A single line contains integer n (1 ≤ n ≤ 2000) — the number of buttons the lock has.

In a single line print the number of times Manao has to push a button in the worst-case scenario.

NoteConsider the first test sample. Manao can fail his first push and push the wrong button. In this case he will already be able to guess the right one with his second push. And his third push will push the second right button. Thus, in the worst-case scenario he will only need 3 pushes.

n = gets.to_i
ar = (1...n).to_a
puts n + ar.reverse.zip(ar).map{|x,y| x*y}.inject(:+) if n>1
puts 1 if n==1

x=gets.chomp.to_i
y=1
z=x
ans=0
while y!=x do
  ans=ans+((z-1)*y)
  y=y+1
  z=z-1
end
puts ans+x

def func(x, h)
    y = x+(x-1)*h
    return y
end

n = gets.to_i

result = 0

i = n
while i > 0 do
    result += func(i, n-i)
    i -= 1
end

puts result

val = gets.to_i ;
val = (val**3 + 5*val)/6 ;
puts val ;

#!/usr/bin/ruby
n=gets.to_i
p (n*n+5)*n/6

sum, multi = gets.chomp.to_i, 1
(sum-1).downto 1 do |i|
	sum += (i*multi)
	multi += 1
end
puts sum

n = gets.to_i
k = n
sum = 0
while k > 0 do
  sum += (n-k + 1) * (k - 1) + 1
  k -= 1
end
puts sum

n = gets.to_i
sum = n
for k in 1..n do
  sum += (n-k + 1) * (k - 1)
end
puts sum

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i

prefix = 0
total = 0
(1..n).reverse_each do |k|
	total += (prefix+1)*(k-1) + 1
	prefix += 1
end

puts total

n = gets.to_i
i = 1
r = 0
while i<=n-1 do
	r = r + (i * (n-i))
	i=i+1
end
puts r+n

x = gets.chomp.to_i

total = x

x.downto(1).each_with_index do |i, ind|
  total += i*ind
end

puts total

n = $stdin.readline.to_i

def s(n)
    n*(n-1)/2
end

def k(n,l)
    if n == 1
        return 1+l
    else
        if l > 0
            return n*l + k(n-1, l+1)
        else
            return n-1 + k(n-1, l+1)
        end
    end
end

puts k(n,0)

def run
  n = ARGF.readline.to_i

  sum = 0
  n.times do |i|
    sum += (n - i - 1) * (i + 1) + 1
  end

  puts sum
end

run if $0 == __FILE__

n = gets.to_i
sum = 0
n.times do |j|
  sum += n - j + j * (n - j - 1)
end
puts sum

n = gets.to_i
s = 0
n.times do |time|
  s += (n - time - 1) * (time + 1) + 1
end
puts s

n=gets.to_i
i=0
ans=n+n-1
while n>1
	n=n-1
	ans=ans+n*i+i
	i=i+1
end
puts ans

n = gets.to_i
r = 0
n.downto(1) do |i|
	r += i + (i - 1)*(n - i)
end
puts r

n=gets.to_i
count=0
2.upto(n){|i| count+=(i-1)*(n-i)+(i-1)}
puts(count+n)

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

if n == 1 then
  print 1
  exit
end

result = n + 1
2.upto(n - 1) do |value|
  result += 1
  result += value * (n - value)
end

print result

n=gets.to_i
res=n
for i in 1..n-1
    res+=i*(n-i)
end
puts res

n = Integer(gets)
a = 0
for i in 1..n
	a = a + n*i - i * i + 1
end
puts a

a = c = gets.chomp.to_i

b = 0; sum = 0

while a > 1 do
    a -= 1
    b += 1
    sum += b * a
end

puts sum + c

number = gets.to_i
count = 0

(number-1).times do |i|
  k = i+1
  count += (number-k)*k
end

p count + number

n = gets.chomp.to_i
s = 0
(1..n).each{ |k|
  s += (k*(n-k)+1)
}
puts s

n = gets.to_i
i = 1
ans = 0
for i in 1..n do
    ans = ans + (i * (n-i))
end
puts ans+n

n = gets.to_i
ans = n
i = 1
while n-i > 0 do
  ans += (n-i)*i
  i+=1
end
puts ans

n = gets.to_i
need = [0]
n.times do |i|
    need << need[-1] + (n - i - 1) * (i + 1) + 1
end
puts need[n]

#!/usr/bin/env ruby

n = gets.to_i
puts n + (n - 1) * n * (n + 1) / 6;

$i=0;
$sum=0;
gets.chomp.to_i.-(1).times do
    $i+=1
    $sum+=$i*($_.to_i-$i)
end
puts $sum+$_.to_i

n = gets.to_i

result = 0
t = []

1.upto(n)do |i|
	result += (n-i)*i
end
puts result + n

n = gets.to_i
ans = n
n.times do |i|
	ans += (i + 1) * (n - i - 1)
end
puts ans

def func(x)
    y = x+(x-1)
    return y
end

n = gets.to_i

result = n
i = n-1
while i > 0 do
    result += func(i)
    i -= 1
end

puts result

def Click(n)
  return 1 if n == 1
  return 3 if n == 2
  return n - 1 + 2 * Click(n - 1) - 1
end

puts Click(gets.to_i)

n = $stdin.readline.to_i

def k(n)
    if n == 1
        return 1
    else
        return 2*(n-1) + k(n-1)
    end
end

puts k(n)

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i

result = n + 1
2.upto(n - 1) do |value|
  result += 1
  result += value * (n - value)
end

print result

require 'set'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i
if n == 1 then
  print 1
else
  result = 0
  n.times do |p|
    result+=2**p
  end

  print result
end

n = gets.to_i

result = 0
t = []

if n > 3
	n.downto(1) do |i|
		if i > 1
			n.downto(i+1) do |j|
				t[j] += i
			end
		end
		t[i] = i

	end
	t.each{|x| result += x == nil ? 0 : x}
	puts result
elsif n == 3
	print 7
else
	print 3
end

def sum(n)
	n + [0, n*n/2 - n].max
end

n = gets.to_i

result = 0

n.times do |i|
	result += sum(i+1)
end

puts result


Recently Vasya found a golden ticket — a sequence which consists of $$$n$$$ digits $$$a_1a_2\dots a_n$$$. Vasya considers a ticket to be lucky if it can be divided into two or more non-intersecting segments with equal sums. For example, ticket $$$350178$$$ is lucky since it can be divided into three segments $$$350$$$, $$$17$$$ and $$$8$$$: $$$3+5+0=1+7=8$$$. Note that each digit of sequence should belong to exactly one segment.Help Vasya! Tell him if the golden ticket he found is lucky or not.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of digits in the ticket. The second line contains $$$n$$$ digits $$$a_1 a_2 \dots a_n$$$ ($$$0 \le a_i \le 9$$$) — the golden ticket. Digits are printed without spaces.

If the golden ticket is lucky then print "YES", otherwise print "NO" (both case insensitive).

NoteIn the first example the ticket can be divided into $$$7$$$, $$$34$$$ and $$$52$$$: $$$7=3+4=5+2$$$.In the second example it is impossible to divide ticket into segments with equal sum.

n = gets.to_i
ary = gets.strip.split('').map(&:to_i)

if ary.uniq == [0]
  puts "YES"
  exit 0
end

# lim = (n * 9) + 10
lim = ary.inject(:+) - 1

def poss?(ary, ss)
  i=0
  sum = 0
  sz = ary.size
  while i<sz do
    sum += ary[i]
    if sum == ss
      sum = 0
    elsif sum > ss
      return false
    end
    i += 1
  end
  sum == 0
end

1.upto(lim).each do |ss|
  if poss?(ary, ss)
    # puts ss
    puts "YES"
    exit 0
  end
end

puts "NO"

n = gets.to_i
ary = gets.strip.split('').map(&:to_i)

# lim = (n * 9) + 10
lim = ary.inject(:+) - 1

# def poss?(ary, ss)
#   i=j=0
#   sum = ary[0]
#   return false if sum > ss
#   sz = ary.size
#   while i<sz && j<sz do
#     if sum == ss
#       j = j+1
#       i = j
#       return true if j >= sz
#       sum = ary[j]
#     end
#   end
# end

def poss?(ary, ss)
  i=0
  sum = 0
  sz = ary.size
  while i<sz do
    sum += ary[i]
    if sum == ss
      sum = 0
    elsif sum > ss
      return false
    end
    i += 1
  end
  sum == 0
end

1.upto(lim).each do |ss|
  if poss?(ary, ss)
    # puts ss
    puts "YES"
    exit 0
  end
end

puts "NO"


Berland Football Cup starts really soon! Commentators from all over the world come to the event.Organizers have already built $$$n$$$ commentary boxes. $$$m$$$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.If $$$n$$$ is not divisible by $$$m$$$, it is impossible to distribute the boxes to the delegations at the moment.Organizers can build a new commentary box paying $$$a$$$ burles and demolish a commentary box paying $$$b$$$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $$$m$$$)?

The only line contains four integer numbers $$$n$$$, $$$m$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n, m \le 10^{12}$$$, $$$1 \le a, b \le 100$$$), where $$$n$$$ is the initial number of the commentary boxes, $$$m$$$ is the number of delegations to come, $$$a$$$ is the fee to build a box and $$$b$$$ is the fee to demolish a box.

Output the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $$$m$$$). It is allowed that the final number of the boxes is equal to $$$0$$$.

NoteIn the first example organizers can build $$$5$$$ boxes to make the total of $$$14$$$ paying $$$3$$$ burles for the each of them.In the second example organizers can demolish $$$2$$$ boxes to make the total of $$$0$$$ paying $$$7$$$ burles for the each of them.In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get $$$5$$$ boxes.

n,m,a,b=gets.split.map &:to_i
p [n%m*b,(m-n%m)*a].min

n, m, a, b = gets.strip.split.map(&:to_i)
td = n % m
tb = m - td
puts [td*b, tb*a].min

n, m, a, b = gets.split.map{|e| e.to_i }
mod = n % m
puts [mod*b, ((m-mod)%m)*a].min

n,m,a,b=gets.split.map &:to_i
x=n%m
puts [x*b, (m-x)*a].min

n, m, a, b = gets.split.map &:to_i
x = [n / m - 1, 0].max
ans = Float::INFINITY
x.upto(x + 2) do |i|
  ans = [ans, i * m < n ? (n - i * m) * b : (i * m - n) * a].min
end
puts ans

n, m, a, b = gets.split.map(&:to_i)
d = n % m
if d == 0
    puts 0
    exit
end
puts [b * d, a * (m - d)].min

def delegate_boxes
  n, m, a, b = gets.split.map(&:to_i)
  l = n % m
  return 0 if l == 0

  if n < m
    return min(n * b, (m - n) * a)
  end

  min(l * b, (m - l) * a)
end

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

puts delegate_boxes

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

div, mod = n.divmod(m)

puts [mod * b, (m - mod) * a].min


You are given a sequence of integers $$$a_1, a_2, \dots, a_n$$$. You need to paint elements in colors, so that:   If we consider any color, all elements of this color must be divisible by the minimal element of this color.  The number of used colors must be minimized. For example, it's fine to paint elements $$$[40, 10, 60]$$$ in a single color, because they are all divisible by $$$10$$$. You can use any color an arbitrary amount of times (in particular, it is allowed to use a color only once). The elements painted in one color do not need to be consecutive.For example, if $$$a=[6, 2, 3, 4, 12]$$$ then two colors are required: let's paint $$$6$$$, $$$3$$$ and $$$12$$$ in the first color ($$$6$$$, $$$3$$$ and $$$12$$$ are divisible by $$$3$$$) and paint $$$2$$$ and $$$4$$$ in the second color ($$$2$$$ and $$$4$$$ are divisible by $$$2$$$). For example, if $$$a=[10, 7, 15]$$$ then $$$3$$$ colors are required (we can simply paint each element in an unique color).

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$), where $$$n$$$ is the length of the given sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$). These numbers can contain duplicates.

Print the minimal number of colors to paint all the given numbers in a valid way.

NoteIn the first example, one possible way to paint the elements in $$$3$$$ colors is:  paint in the first color the elements: $$$a_1=10$$$ and $$$a_4=5$$$,  paint in the second color the element $$$a_3=3$$$,  paint in the third color the elements: $$$a_2=2$$$, $$$a_5=4$$$ and $$$a_6=2$$$. In the second example, you can use one color to paint all the elements.In the third example, one possible way to paint the elements in $$$4$$$ colors is:  paint in the first color the elements: $$$a_4=4$$$, $$$a_6=2$$$ and $$$a_7=2$$$,  paint in the second color the elements: $$$a_2=6$$$, $$$a_5=3$$$ and $$$a_8=3$$$,  paint in the third color the element $$$a_3=5$$$,  paint in the fourth color the element $$$a_1=7$$$.

n = gets.to_i
a = gets.split.map(&:to_i).sort

ans = 0
while !a.empty?
  ans += 1
  t = a.shift
  idx = []
  a.length.times do |i|
    if a[i] % t == 0
      idx << i
    end
  end
  idx.reverse.each do |v|
    a.delete_at(v)
  end
end
p ans

n = gets.to_i
arr = gets.split(' ').collect(&:to_i).sort
arr_used = Array.new(n)

arr.each_with_index do |elem_1, idx_1|
	arr.each_with_index do |elem_2, idx_2|
		next unless arr_used[idx_2].nil?
		next unless elem_2 % elem_1 == 0 && elem_1 <= elem_2
		arr_used[idx_2] = idx_1
	end
end

p arr_used.uniq.count

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

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

require 'prime'

n = inp[0]
t = inp
t = t.sort
h = {}
ans = 0
t.each do |d|
   (t).each do |i|
    if(d%i == 0)
      h[i] = true
      break
    end
  end
end

p ((h.to_a.size))

n = gets.to_i
a = gets.split.map(&:to_i).sort
painted = Array.new(n, false)
colors = 0
for i in 0...n do
  if !painted[i]
    colors += 1
    painted[i] = true
    for j in (i+1)...n do
      if !painted[j] && a[j] % a[i] == 0
        painted[j] = true
      end
    end
  end
end
puts colors

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

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

require 'prime'

n = inp[0]
t = inp
t = t.sort.reverse
h = {}
ans = 0
t.each do |d|
   ((t.min)..100).each do |i|
    if(d%i == 0)
      h[i] = true
      break
    end
  end
end

p ((h.to_a.size))

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

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

require 'prime'

n = inp[0]
t = inp
t = t.sort.reverse
h = {}
ans = 0
t.each do |d|
   (2..100).each do |i|
    if(d%i == 0)
      h[i] = true
      break
    end
  end
end
p h.to_a.size

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

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

require 'prime'

n = inp[0]
t = inp
t = t.sort.reverse
h = {}
ans = 0
t.size.times do |i|
  f = false
  next if(h[t[i]])
  ((i+1)...(t.size)).each do |j|
    if(t[i]%t[j]==0)
      h[t[j]] = true
    end
  end
  ans += 1
end
p ans

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

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

require 'prime'
n = inp[0]
t = inp
t = t.sort
h = {}
ans = 0
t.size.times do |i|
  f = false
  ((i+1)...(t.size)).each do |j|
    if(t[j]%t[i]==0)
      f = true
      break
    end
  end
  ans += 1 unless f
end
p ans


A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than n matchboxes so that the total amount of matches in them is maximal.

The first line of the input contains integer n (1 ≤ n ≤ 2·108) and integer m (1 ≤ m ≤ 20). The i + 1-th line contains a pair of numbers ai and bi (1 ≤ ai ≤ 108, 1 ≤ bi ≤ 10). All the input numbers are integer.

Output the only number — answer to the problem.

ns,ms = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i
ar = Array.new(m)
for i in 0..m-1
	s = gets.chomp
	ar[i] = s.split(/ /).map! {|x| x.to_i }
end

ar.sort! { |a,b| b[1] <=> a[1] }

ret = 0
wk = n
for i in 0..m-1
	break if wk <= 0
	t = [wk, ar[i][0]].min
	ret += t * ar[i][1]
	wk -= t
end

puts ret

s = 0
n, m = gets.split.map{|i| i.to_i}
m.times.to_a.map{gets.split.map{|i| i.to_i}.reverse}.sort.reverse.each do |i|
	t = [n, i[1]].min
	n -= t
	s += i[0] * t
end
p s

s = 0
n, m = gets.split.map{|i| i.to_i}
m.times{$*<<gets.split.map(&:to_i)}
$*.sort{|a, b| b[1] <=> a[1]}.each do |a, b|
	t = [n, a].min
	n -= t
	s += b * t
end
p s

__END__
# 	When 	Who 	Problem 	Lang 	Verdict 	Time 	Memory
212857 	Dec 9, 2010 9:59:45 PM 	watashi 	B - Burglar and Matches 	Ruby 	Accepted 	80 ms 	2992 KB

n,m=gets.split.map(&:to_i)
cnt=Array.new(11,0)
m.times{
        a,b=gets.split.map(&:to_i)
        cnt[b]+=a
}
ans=0
10.downto(1){|i|
        if(n>=cnt[i]) then
                n-=cnt[i]
                ans+=cnt[i]*i
        else
                ans+=n*i
                n=0
        end
}
p ans

#!/usr/bin/ruby

n, m = gets.chomp.split.map{|e| e.to_i}

matches = []
m.times do
  a, b = gets.chomp.split.map{|e| e.to_i}
  matches.push [a, b]
end

matches.sort! {|l, r|
  r[1] <=> l[1]
}

rest = n
cur_box = 0
acc = 0
while (true)
  break if cur_box >= m
  if (matches[cur_box][0] <= rest)
    acc += matches[cur_box][0] * matches[cur_box][1]
    rest -= matches[cur_box][0]
    cur_box += 1
    next
  else
    acc += matches[cur_box][1] * rest
    break
  end
end
puts acc

result = 0
n, m = gets.split.map(&:to_i)
elements = m.times.to_a.map{ gets.split.map(&:to_i).reverse }
elements.sort.reverse.each{ |x, y| t = [n, y].min; n -= t; result += x * t; break if n == 0 }
puts result

n,m=gets().chomp().split(' ').map(&:to_i) ;h={}
h = m.times.to_a.map{ gets.split.map(&:to_i) }
(h=h.sort_by {|_key, value| value}).reverse! ;count=0
h.each do |key, value|
  count+=(key>n)?((n)*value):(key*value) ;n-=key ;break if (n<=0)
end
p count

n, m = gets.split.map(&:to_i)
b = {}
m.times do
	x, y = gets.split.map(&:to_i)
	b.has_key?(y) ? b[y] += x : b[y] = x
end
tot, cc = 0, 0
b.sort.reverse.each do |v, i|
	tot += [n - cc, i].min * v
	cc += i
	break if cc > n
end
puts tot

n,m=gets.split.map(&:to_i)
s=0
m.times{$*<<gets.split.map(&:to_i)}
$*.sort{|c,d|d[1]<=>c[1]}.each{|a,b|if n>a
s+=a*b
n-=a
else
s+=n*b
break
end}
p s

tab=[]; result=0
n, m = gets.split.map(&:to_i)
m.times{tab << gets.split.map(&:to_i)}
tab.sort!{|a, b| a[1] <=> b[1]}.reverse!
tab.each do |x|
	result += [x[0], n].min * x[1]
	n -= [x[0], n].min
end

puts result

class Box
	attr_accessor :count, :value

	def initialize(count, value)
		@count, @value = count, value
	end
end

t = gets.split.collect{|x| x.to_i}
n,m = t[0], t[1]

a = []

m.times do |i|
	t = gets.split.collect{|x| x.to_i}
	a << Box.new(t[0], t[1])
end

a.sort!{|x,y| y.value <=> x.value}

result = 0
a.each do |b|
	if b.count <= n
		result += b.count * b.value
		n-=b.count
	else
		result += n * b.value
		n = 0
	end
end

puts result

result = 0
n, m = gets.split.map(&:to_i)
elements = m.times.to_a.map{ gets.split.map(&:to_i).reverse }
elements.sort.reverse.each{ |x, y| puts x; puts y; t = [n, y].min; puts t; n -= t; puts n; result += x * t; break if n == 0 }
puts result

n,m=gets().chomp().split(' ').map(&:to_i) ;h=Hash.new
m.times { a,b=gets().chomp().split(' ').map(&:to_i); h[a]=b; }
(h=h.sort_by {|_key, value| value}).reverse! ;count=0
h.each do |key, value|
  count+=(key>n)?((n)*value):(key*value) ;n-=key ;break if (n<=0)
end
p count


Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.  Barney woke up in the morning and wants to eat the pineapple, but he can't eat it when it's barking. Barney plans to eat it at time x (in seconds), so he asked you to tell him if it's gonna bark at that time.

The first and only line of input contains three integers t, s and x (0 ≤ t, x ≤ 109, 2 ≤ s ≤ 109) — the time the pineapple barks for the first time, the pineapple barking interval, and the time Barney wants to eat the pineapple respectively.

Print a single "YES" (without quotes) if the pineapple will bark at time x or a single "NO" (without quotes) otherwise in the only line of output.

NoteIn the first and the second sample cases pineapple will bark at moments 3, 13, 14, ..., so it won't bark at the moment 4 and will bark at the moment 3.In the third and fourth sample cases pineapple will bark at moments 3, 11, 12, 19, 20, 27, 28, 35, 36, 43, 44, 51, 52, 59, ..., so it will bark at both moments 51 and 52.

t,s,x = gets.chomp.split

t = t.to_i
x = x.to_i
s = s.to_i

if x<t or x==(t+1)
  puts "NO"
elsif (x-t)%s==0 or (x-t-1)%s==0
  puts "YES"
else
  puts "NO"
end

I =->{gets.split.map &:to_i}
t, s, x = I[]
if x == t || x >= s + t && ((x - t) % s == 0 || ((x - t - 1)) % s == 0)
  print 'YES'
else
  print 'NO'
end

t,s,x = gets.split(" ").map(&:to_i)
x -= t
puts ((x>=0 and x%s < 2 and x!=1) ? "YES" :"NO")

t,s,x=gets.split.map{|e| e.to_i}
if (x-t)%s==0 && (x-t)/s>=0 then
	puts "YES"
elsif (x-t-1)%s==0 && (x-t-1)/s>0 then
	puts "YES"
else
	puts "NO"
end

#!/usr/bin/env ruby

t, s, x = ARGF.gets.chomp.split(" ").map { |s| s.to_i }

if t == x
    puts "YES"
    exit
end
if x == t + 1 or x < t
    puts "NO"
    exit
end

if (x - t).modulo(s) == 0 or (x - t - 1).modulo(s) == 0
    puts "YES"
else
    puts "NO"
end

t,s,x = gets.split(' ').map(&:to_i)
a = x - t
b = x - t - 1
if a%s == 0 && (a >= 0)
  puts 'YES'
elsif b%s == 0 && (b > 0)
  puts 'YES'
else
  puts 'NO'
end

input1 = gets.chomp
num = input1.split(" ").map(&:to_i)
if num[2]>=num[0] && num[2]!= (num[0]+1) && ((num[2]-num[0])%num[1] == 0 || (num[2] - num[0] - 1)%num[1] == 0)
  print "YES"
else
  print "NO"
end

t, s, x = gets.split.map { |x| x.to_i }

if x >= t and (x - t) % s == 0
	puts 'YES'
elsif x >= t + s + 1 and (x - t - 1) % s == 0
	puts 'YES'
else
	puts 'NO'
end

t, s, x = gets.chomp.split(' ').map(&:to_i)

n = (x - t) / s
num = t + n * s

first = true if (n == 0)
oneTime = (n > 0)

#puts "n : #{n}"

if n < 0
	puts 'NO'
	exit
end

until num >= x
	num += s if first
	num += (s - 1) if !oneTime && !first
	num += 1 if oneTime

	oneTime = !oneTime
	first = false

	#puts "Num : #{num}"
end

if num == x
	puts 'YES'
else
	puts 'NO'
end

t,s,x = gets.chomp.split

t = t.to_i
x = x.to_i
s = s.to_i

if x<t
  puts "NO"
elsif (x-t)%s==0 or (x-t-1)%s==0
  puts "YES"
else
  puts "NO"
end

t,s,x = gets.split(" ").map(&:to_i)
x -= t
puts (x>=0 and x%s < 2 and x!=1 ? "YES" :"NO")

t, s, x = gets.split.map(&:to_i)

puts (x-t) % s < 2 && t+1 != x ? 'YES' : 'NO'

t, s, x = gets.split.map(&:to_i)

puts (x-t) % s < 2 ? 'YES' : 'NO'

#!/usr/bin/env ruby

t, s, x = ARGF.gets.chomp.split(" ").map { |s| s.to_i }

if t == x
    puts "YES"
    exit
end
if x == t + 1
    puts "NO"
    exit
end

if ((r1 = (x - t).modulo(s)) == 0 and r1 >= t) or ((r2 = (x - t - 1).modulo(s)) == 0 and r2 >= t)
    puts "YES"
else
    puts "NO"
end

#!/usr/bin/env ruby

t, s, x = ARGF.gets.chomp.split(" ").map { |s| s.to_i }

if t == x
    puts "YES"
    exit
end
if x == t + 1
    puts "NO"
    exit
end

if (x - t).modulo(s) == 0 or (x - t - 1).modulo(s) == 0
    puts "YES"
else
    puts "NO"
end

t,s,x = gets.split(' ').map(&:to_i)
a = x - t
b = x - t - 1
if a%s == 0
  puts 'YES'
elsif b%s == 0 && (b%s > 0)
  puts 'YES'
else
  puts 'NO'
end

t,s,x = gets.split(' ').map(&:to_i)
a = x - t
b = x - t - 1
if a%s == 0
  puts 'YES'
elsif b%s == 0 && (b > 0)
  puts 'YES'
else
  puts 'NO'
end

t, s, x = gets.chomp.split(' ').map(&:to_i)

n = (x - t) / s
num = t + n * s

first = true if (n == 0)
oneTime = (n > 0)

until num >= x
	num += s if first
	num += (s - 1) if !oneTime && !first
	num += 1 if oneTime

	oneTime = !oneTime
	first = false

	#puts "Num : #{num}"
end

if num == x
	puts 'YES'
else
	puts 'NO'
end


Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks?

The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100), separated by a space.

Print a single integer — the answer to the problem.

NoteIn the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two.In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day.

n, m = gets.split.map(&:to_i)
i = 0
ans = 0
while n > 0
	i += 1
	if i % m == 0
		ans += 1
		next end
	n -= 1
	ans += 1 end
puts ans

input=gets.split(" ")
n=input[0].to_i
m=input[1].to_i
k=n
days=0
while k>0
  days+=1
  k=k-1
  if days % m == 0
    k=k+1
  end
end
puts days

n, m = gets.chomp.split.map{|x| x.to_i}

div = n/m
days = n + div

while((div+=1) * m <= days)
    days += 1
end

puts days

n, m = gets.split.map &:to_i

i = 0
while n > 0
    i += 1
    n -= 1 if i % m != 0
end

p i

a, b = gets.split(' ').map &:to_i
total = 0
tmp = 0
while a > 0
  total += 1
  tmp += 1
  a -= 1
  if tmp == b
    tmp = 0
    a += 1
  end
end
puts total

n, m = gets.split.map(&:to_i)
puts n + (n - 1) / (m - 1)

a,b = gets.split.map(&:to_i)
sum = a
while a>=b
    tmp = a
    a = tmp/b
    sum+=a
    a += tmp%b
end
p sum

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

i = 0
loop do
  i += 1
  n -= 1
  n += 1 if i % m == 0
  break if n == 0
end

puts i

n, m = gets.split(/\s+/).map(&:to_i)
a = 0

while n > 0
  a += 1
  n -= 1
  if a%m == 0
    n+=1
  end
end

p a

n,m = gets.split.map(&:to_i)
day = 0
while n > 0
  day += 1
  n -= 1 if day % m != 0
end
puts day

s = gets.split(' ')	#Танцы с бубном

n = s[0].to_i
m = s[1].to_i

i = 0
res = 0
until n == 0
	res += 1
	n -= 1
	i += 1
	if i == m
		n += 1
		i = 0
	end
end

puts res

n, m = *(gets.split(' ').collect { |n| n.to_i })
day = 0
until n == 0 do
  day += 1
  n -= 1 unless day % m == 0
end
puts day

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

x=n
while (x<n+x/m) do
    x+=1
end

puts x

n, m = gets.split(" ").map {|x| x.to_i}
i = 0
while n > 0
  n -= 1
  i += 1
  if i % m == 0
    n += 1
  end
end
puts(i)

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

day = 0
while n > 0
  day += 1
  n -= 1
  n += 1 if day % m == 0
end

puts day

input = gets.split.map(&:to_i)
n = input[0]
m = input[1]
days = 0
while n != 0
  days += 1
  if days % m == 0
    n += 1
  end
  n -= 1
end
puts days

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

(1..100000).each do |i|
  #puts "#{i}, #{a}"
  if a == 0
    puts i-1
    break
  end

  a -= 1

  if i % b == 0
    a += 1
  end

end

n, m = gets.chomp.split(' ').map { |i| i.to_i }
ans = 1
until n == 0 do
    n -= 1
    n += 1 if ans % m == 0
    ans += 1
end

puts ans - 1

n,m=gets.split.map &:to_i

day=0

while n>0
    day+=1
    n-=1
    if day%m==0
        n+=1
    end
end

p day

#!/usr/bin/env ruby

#n = ARGV[0].to_i
#m = ARGV[1].to_i

inp = $stdin.gets.chomp.split
n = inp[0].to_i
m = inp[1].to_i

day = 0

while n > 0
  day += 1
  n -= 1 unless day%m==0
end

puts day

n, m = gets.split.map!{ |s| s.to_i }

res = 0
day = 0

while n > 0
    res += 1
    n -= 1
    day += 1
    if day >= m
        n += 1
        day = 0
    end
end

p res

n,m = gets.split.map{|r| r.to_i}

k = n
i = 1
while i<=n
  if i%m == 0
      n+=1
  end
  i+=1
end
puts n

a, b = $stdin.readline.split.map(&:to_i)

n = 0
r = 0
while a>0
    n+= a
    t = r+a
    a = t/b
    r = t%b
end

puts n

a, b = gets.split.map(&:to_i); p (a*b-1)/(b-1)

a, b = gets.split.map &:to_i
total = a
while a / b > 0
  total += a / b
  if a % b == 0
    a = a / b
  else
    a = a / b + a % b
  end
end
puts total

ARGF.lines do |line|
    n, m = line.split.map(&:to_i)
    sol = n+(n-1)/(m-1)
    puts sol
end

n,m=gets.split.map{|e| e.to_i}
c=1
1.upto(10000000){|i|
	if i%m==0 then
		c=c+1
	end
	if n<=i then
		c=c-1
		if c<=0 then
			puts i
			break
		end
	end
}

n, m = gets.split.map(&:to_i)
c = n
c += n = n / m while n >= m
puts c

a,b = gets.split.map(&:to_i)
sum = a
while a!=0
    a = a/b
    sum+=a
end
p sum

n, m = gets.split(/\s+/).map(&:to_i)
a = n

while n >= m
  a += n/m
  n /= m
end

p a

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

x=(m*n)/(m-1)
if (x==n+x/m)
    puts x
else
    puts x-1
end

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

result = n
while n > 0
  n /= m
  result += n
end

puts result

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

result = n
while n > 0
  result += n % m
  n /= m
  result += n
end

puts result - 1

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

(1..100000).each do |i|
  #puts "day #{i} socks #{a}"
  if a == 0
    puts i
    break
  end
  a -= 1
  if (i-1) % b == 0
    a += 1
  end

end

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

(1..100000).each do |i|
  if a == 0
    puts i
    break
  end

  a -= 1

  if (i-1)%b == 0 && i != 1
    a += 1
  end

end

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

if a == 1

  puts "1"

else

  a -= 1
  (1..100000).each do |i|
    #puts "day #{i} socks #{a}"
    if a == 0
      puts i
      break
    end
    a -= 1
    if (i-1) % b == 0
      a += 1
    end

  end

end

#!/usr/bin/env ruby

n = ARGV[0].to_i
m = ARGV[1].to_i

day = 0

while n > 0
  day += 1
  n -= 1 unless day%m==0
end

puts day

n,m = gets.split.map{|r| r.to_i}

for i in 1..n
  if i%m == 0
      n+=1
  end
end
puts n+1

a, b = gets.split.map &:to_i
if a < b
  puts a
  exit
end
total = a
while a != 1
  total += a % b == 0 ? a / b : a / b + 1
  a /= b
end
puts total

a, b = gets.split.map &:to_i
total = a
while a / b > 0
  total += a / b
  if a % b == 0
    a = a / b
  else
    a = a / b + 1
  end
end
puts total

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


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.Petya decided to introduce the sum operation on the set of permutations of length n. Let's assume that we are given two permutations of length n: a1, a2, ..., an and b1, b2, ..., bn. Petya calls the sum of permutations a and b such permutation c of length n, where ci = ((ai - 1 + bi - 1) mod n) + 1 (1 ≤ i ≤ n).Operation  means taking the remainder after dividing number x by number y.Obviously, not for all permutations a and b exists permutation c that is sum of a and b. That's why Petya got sad and asked you to do the following: given n, count the number of such pairs of permutations a and b of length n, that exists permutation c that is sum of a and b. The pair of permutations x, y (x ≠ y) and the pair of permutations y, x are considered distinct pairs.As the answer can be rather large, print the remainder after dividing it by 1000000007 (109 + 7).

The single line contains integer n (1 ≤ n ≤ 16).

In the single line print a single non-negative integer — the number of such pairs of permutations a and b, that exists permutation c that is sum of a and b, modulo 1000000007 (109 + 7).


A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.A substring $$$s[l \ldots r]$$$ ($$$1 \leq l \leq r \leq |s|$$$) of a string $$$s = s_{1}s_{2} \ldots s_{|s|}$$$ is the string $$$s_{l}s_{l + 1} \ldots s_{r}$$$.Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $$$s$$$ is changed into its longest substring that is not a palindrome. If all the substrings of $$$s$$$ are palindromes, she skips the word at all.Some time ago Ann read the word $$$s$$$. What is the word she changed it into?

The first line contains a non-empty string $$$s$$$ with length at most $$$50$$$ characters, containing lowercase English letters only.

If there is such a substring in $$$s$$$ that is not a palindrome, print the maximum length of such a substring. Otherwise print $$$0$$$. Note that there can be multiple longest substrings that are not palindromes, but their length is unique.

Note"mew" is not a palindrome, so the longest substring of it that is not a palindrome, is the string "mew" itself. Thus, the answer for the first example is $$$3$$$.The string "uffuw" is one of the longest non-palindrome substrings (of length $$$5$$$) of the string "wuffuw", so the answer for the second example is $$$5$$$.All substrings of the string "qqqqqqqq" consist of equal characters so they are palindromes. This way, there are no non-palindrome substrings. Thus, the answer for the third example is $$$0$$$.

s = gets.chomp
if s == s[0] * s.length
    puts "0"
else
    puts "#{s.length - (s == s.reverse ? 1 : 0)}"
end

s = gets
if s == s[0] * s.length
    puts"0"
else
    puts "#{s.length - (s == s.reverse ? 1 : 0)}"
end

s = gets
if s == s[0] * s.length
    puts "0"
else
    puts "#{s.length - (s == s.reverse ? 1 : 0)}"
end


Given a positive integer n, find k integers (not necessary distinct) such that all these integers are strictly greater than 1, and their product is equal to n.

The first line contains two integers n and k (2 ≤ n ≤ 100000, 1 ≤ k ≤ 20).

If it's impossible to find the representation of n as a product of k numbers, print -1. Otherwise, print k integers in any order. Their product must be equal to n. If there are multiple answers, print any of them.

n, k = gets.chomp.split().map { |e|  e.to_i }
LIMIT = Math.sqrt(n)
factors = []
for i in 2 .. LIMIT
	while n % i == 0 && k != 1
		factors << i
		n /= i
		k -= 1
	end
end

if k != 1 or n == 1
	puts "-1"
else
	for i in factors
		print(i," ")
	end
	puts n
end

require 'prime'
n,k=gets.split.map(&:to_i)
a=n.prime_division.flat_map{|n,p|[n]*p}
puts a.size<k ? -1 : (a[0,k-1]+[a[k-1..-1].reduce(:*)])*' '

require 'prime'

n, k = gets.chomp.split.map(&:to_i)
a = n.prime_division
sum = (a.map do | x | x[1] end).inject(0, :+)

if sum < k
  puts -1
else
  for x in a
    for i in 1..x[1]
      if k == 1
        break
      end
      print x[0], ' '
      k -= 1
      n /= x[0]
    end
  end
  puts n
end

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

n,k = ascan

require 'prime'

aa = Prime.prime_division(n).map{|e,c| [e]*c}.inject(:+)

if aa.size < k
    p -1
elsif k==1
    p n
else
    r = aa.shift(k-1)
    r << aa.inject(:*)
    puts r*" "
end

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

data = []
for i in (2..n)
    while n % i == 0
        data.push(i)
        n /= i
    end
end

if data.length < k
    puts -1
else
    data[(k-1..-1)] = data[(k-1..-1)].reduce(:*)
    puts data.map(&:to_s).join(' ')
end

n, k = gets.chomp.split().map { |e|  e.to_i }
LIMIT = Math.sqrt(n)
factors = []
for i in 2 .. LIMIT
	while n % i == 0 && k != 1
		factors << i
		n /= i
		k -= 1
	end
end

if k != 1 and n != 1
	puts "-1"
else
	for i in factors
		print(i," ")
	end
	puts n
end

n, k = gets.chomp.split().map { |e|  e.to_i }
LIMIT = Math.sqrt(n)
factors = []
for i in 2 .. LIMIT
	while n % i == 0 && k != 1
		factors << i
		n /= i
		k -= 1
	end
end

if k != 1
	puts "-1"
else
	for i in factors
		print(i," ")
	end
	puts n
end


Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of other denominations. Of course, Gerald likes it when he gets money without the change. And all buyers respect him and try to give the desired sum without change, if possible. But this does not always happen.One day an unlucky buyer came. He did not have the desired sum without change. Then he took out all his coins and tried to give Gerald a larger than necessary sum with as few coins as possible. What is the maximum number of coins he could get?The formal explanation of the previous paragraph: we consider all the possible combinations of coins for which the buyer can not give Gerald the sum of n marks without change. For each such combination calculate the minimum number of coins that can bring the buyer at least n marks. Among all combinations choose the maximum of the minimum number of coins. This is the number we want.

The single line contains a single integer n (1 ≤ n ≤ 1017). 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.

In a single line print an integer: the maximum number of coins the unlucky buyer could have paid with.

NoteIn the first test case, if a buyer has exactly one coin of at least 3 marks, then, to give Gerald one mark, he will have to give this coin. In this sample, the customer can not have a coin of one mark, as in this case, he will be able to give the money to Gerald without any change.In the second test case, if the buyer had exactly three coins of 3 marks, then, to give Gerald 4 marks, he will have to give two of these coins. The buyer cannot give three coins as he wants to minimize the number of coins that he gives.

a = gets.to_i.to_s(3)
a.chop! while a[-1, 1] == '0'
puts a.chop!.to_i(3) + 1

a = gets.to_i.to_s(3).split('')
a.pop while a.last == '0'
a.pop
puts a.join.to_i(3) + 1

a = gets.to_i
a /= 3 while a%3 == 0
puts a/3+1

n = gets.to_i
t = 1
while n%t==0
    t *= 3
end
ans = n/t+1
puts ans

#!/usr/bin/env ruby
n = gets.to_i
k = 0
loop do
  if n % (3**k) != 0
    ret = n / (3**k)
    ret += 1 if ret * (3**k) != n
    puts ret
    break
  end
  k += 1
end

n = gets.chomp.to_i

k = 1

while (n % 3**k == 0)
    k+=1
end

puts n / 3 ** k + 1

n=gets.to_i
p=3
while p < n
  break if n%p>0
  p*=3
end
if n%p>0
  p n/p+1
else
  p 1
end

n = gets.to_i
t = 1
while n%t==0
    t *= 3
end
ans = n/t+n%t
puts ans

#!/usr/bin/env ruby
n = gets.to_i
k = 0
loop do
  if n % (3**k) != 0
    puts((n / (3.0**k)).ceil)
    break
  end
  k += 1
end


Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th problem.Limak's friends organize a New Year's Eve party and Limak wants to be there at midnight or earlier. He needs k minutes to get there from his house, where he will participate in the contest first.How many problems can Limak solve if he wants to make it to the party?

The only line of the input contains two integers n and k (1 ≤ n ≤ 10, 1 ≤ k ≤ 240) — the number of the problems in the contest and the number of minutes Limak needs to get to the party from his house.

Print one integer, denoting the maximum possible number of problems Limak can solve so that he could get to the party at midnight or earlier.

NoteIn the first sample, there are 3 problems and Limak needs 222 minutes to get to the party. The three problems require 5, 10 and 15 minutes respectively. Limak can spend 5 + 10 = 15 minutes to solve first two problems. Then, at 20:15 he can leave his house to get to the party at 23:57 (after 222 minutes). In this scenario Limak would solve 2 problems. He doesn't have enough time to solve 3 problems so the answer is 2.In the second sample, Limak can solve all 4 problems in 5 + 10 + 15 + 20 = 50 minutes. At 20:50 he will leave the house and go to the party. He will get there exactly at midnight.In the third sample, Limak needs only 1 minute to get to the party. He has enough time to solve all 7 problems.

n, k = gets.chomp.split().map { |x| x.to_i }

def cuadratic( d )
    return ( -5 + Math.sqrt( 25 + 40*d ) ) / 10
end

puts [ cuadratic(240-k).to_i, n ].min

#bismillahir rahmanir rahim

n,k = gets.split.map {|x| x.to_i }

k = 240-k
c = 0

for i in 1..10
    q = 5*i*(i+1)
    q = q/2
    if k>=q
        c = c+1
    end
end

c=n if c>n

puts c

n, k = gets.chomp.split.map(&:to_i)
t = 240 - k
idx = 0
sum = 0
(1..n).each do |i|
  sum += i * 5
  if sum <= t
    idx = i
  else
    break
  end
end
puts idx

n,k = gets.split().map(&:to_i)
i = 0
t = 0
until t > 240-k
	i += 1
	t += i*5
end

puts [i-1,n].min

n,k = gets.split.map &:to_i
available_time = 240-k
counter = 0
problem = 1
n.times do
  time_taken = problem * 5
  available_time-= time_taken
  if available_time >=0 then
    problem+=1
    counter +=1
  else
    break
  end
end
puts counter

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

rem = 240 - k

ans = 0
(1..n).each do |i|
  rem -= i * 5
  if rem < 0
    break
  end
  ans += 1
end
puts ans

total_time = 4 * 60
n, k = gets.strip.split.map(&:to_i)
total_time -= k
time = 0
ans = 0
(1..n).each do |i|
    curr_time = 5 * i
    break if time + curr_time > total_time
    ans += 1
    time += curr_time
end
puts ans

n,m=gets.split.map{|e| e.to_i}
m=240-m
ans=0
sum=0
n.times{|i|
	sum+=((i+1)*5)
	break if sum>m
	ans+=1
}
puts ans

n, k = gets.split.map(&:to_i)
k = 240 - k
1.upto(n) do |i|
	k -= i * 5
	if k < 0
		puts i - 1
		break
	end
end
if k >= 0
	puts n
end

n,k=gets.split.map &:to_i
k=240-k
res=0
while res<n and k>=5*(res+1)
    res+=1
    k-=5*res;
end
puts res

nk = gets.chomp
nk = nk.split
problems = nk[0].to_i
minutes = nk[1].to_i

solved = 0
for i in (1..problems)
	if minutes + (i * 5) <= 240
		minutes += (i*5)
		solved += 1
	else
		break
	end
end

print solved

n, k = gets.split.map(&:to_i)
c = 0
t = 60 * 4 - k
while t >= (c + 1) * 5 && c < n
  c += 1
  t -= c * 5
end
puts c

n, k = gets.split(' ').map(&:to_i)
k = 240 - k

result = n

1.upto(n) do |x|
  if (1..x).inject(&:+)*5 > k
    result = x-1
    break
  end
end

puts result

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

rem = 240 - k

ans = 0
(1..n).each do |i|
  if rem <= 0
    break
  end
  rem -= i * 5
  ans += 1
end
puts ans

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

rem = 240 - k

ans = 0
(1..n).each do |i|
  rem -= i * 5
  if rem <= 0
    break
  end
  ans += 1
end
puts ans

total_time = 4 * 60
n, k = gets.strip.split.map(&:to_i)
total_time -= k
time = 5
ans = 0
(1..n).each do |i|
    curr_time = 5 * i
    ans += 1
    break if time + curr_time > total_time
    time += curr_time
end
puts ans

n, k = gets.split.map(&:to_i)
c = 0
t = 60 * 4 - k
while t > (c + 1) * 5 && c < n
  c += 1
  t -= c * 5
end
puts c


Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one. Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the pair (a, c) is coprime. You want to find a counterexample for your friend's statement. Therefore, your task is to find three distinct numbers (a, b, c), for which the statement is false, and the numbers meet the condition l ≤ a < b < c ≤ r. More specifically, you need to find three numbers (a, b, c), such that l ≤ a < b < c ≤ r, pairs (a, b) and (b, c) are coprime, and pair (a, c) is not coprime.

The single line contains two positive space-separated integers l, r (1 ≤ l ≤ r ≤ 1018; r - l ≤ 50).

Print three positive space-separated integers a, b, c — three distinct numbers (a, b, c) that form the counterexample. If there are several solutions, you are allowed to print any of them. The numbers must be printed in ascending order.  If the counterexample does not exist, print the single number -1.

NoteIn the first sample pair (2, 4) is not coprime and pairs (2, 3) and (3, 4) are. In the second sample you cannot form a group of three distinct integers, so the answer is -1. In the third sample it is easy to see that numbers 900000000000000009 and 900000000000000021 are divisible by three.

l,r=gets.split.map &:to_i
a=l+l%2
puts a+2<=r ?[a,a+1,a+2].join(" ") :-1

l,r=gets.chomp.split.map(&:to_i)
if l==r
	puts "-1"
	exit
end
while l<r

	if l%2!=0
		l+=1
	end
	if l+2>r
		puts "-1"
		break
	else
		puts l.to_s+' '+(l+1).to_s+' '+(l+2).to_s
		break
	end
end

l, r = gets.chomp.split(/ /).map(&:to_i)
if (l % 2 != 0)
    l += 1
end
if (l + 2 > r)
    puts "-1"
else
    puts "#{l} #{l + 1} #{l + 2}"
end

def test(l,r)
l.upto(r-2){|a|
	(a+1).upto(r-1){|b|
		next if a.gcd(b)!=1
		(b+1).upto(r){|c|
			next if b.gcd(c)!=1
			next if a.gcd(c)==1
			return [a,b,c]
		}
	}
}
return [-1]
end
l,r=gets.split.map{|e| e.to_i}
puts test(l,r)*" "

# coding: utf-8

l, r = gets.split.map(&:to_i)

def euclidean(a, b)
    while b > 0
        c = a % b
        a = b
        b = c
    end

    a
end
# counter example
# if (a,b) is coprime and (b, c) is coprime,  then (a,c) is also coprime
# if possible, print a b c
# if not possible, print -1
# l과 r사이 간격은 최대 50
if r - l < 2
    puts "-1"
else
    # 두 수의 관계이므로 유클리드 호제법을 이용한다
    # 나눠 떨어지는 시점이 최대공약수(GCD)인데 1이 나오면 서로소이다.
    printed = false

    catch :found do
        for a in l...r
            for b in (a+1)...r
                for c in (b+1)..r
                    if euclidean(a, b) == 1 && euclidean(b, c) == 1 && euclidean(a, c) != 1
                        puts "#{a} #{b} #{c}"
                        printed = true
                        throw :found
                    end
                end
            end
        end
    end

    if !printed
        puts "-1"
    end
end

def isCoprime(a,b)
  if b != 0
    return isCoprime(b,a%b)
  end
  return (a == 1)
end

def counter(l, r)
  for a in (l..r+1)
    for b in (a+1)..(r)
      for c in (b+1)..(r)
        if isCoprime(a,b)
          if isCoprime(b,c)
            unless isCoprime(a,c)
               return "#{a} #{b} #{c}"
            end
          end
        end
      end
    end
  end
  -1
end

l, r = gets.chomp.split
l = l.to_i
r = r.to_i

print counter(l, r)

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

coprime = false
req_a = 0
req_b = 0
req_c = 0
l,h = gets.split(" ").map(&:to_i)
(l..h).each do |a|
  (a+1..h).each do |b|
    (b+1..h).each do |c|
      # puts "#{a} #{b} #{c}"
      # puts "#{gcd(b,a)} #{gcd(c,b)} #{gcd(c,a)}"
      if gcd(a,b) == 1 &&  gcd(b,c) == 1 && gcd(a,c) != 1
        req_a = a
        req_b = b
        req_c = c
        coprime = true
        break
      end

    end
    break if coprime
  end
  break if coprime
end

puts coprime ? "#{req_a} #{req_b} #{req_c}" :-1

=begin
data = gets.chomp.split(/\s/).map {|n| n.to_i}
#p data
puts data.inject(:+) / data.length
=end

def nod(x,y)
  if x == y
    return x
  end
  if x == 0
    return y
  end
  if y == 0
    return x
  end
  if x > y
    return nod(y, x % y)
  else
    return nod(x, y % x)
  end
end

data = gets.chomp.split(/\s/).map{|n| n.to_i}
l = data[0]
r = data[1]

a = l
b = a + 1
c = b + 1
res = -1

while a < r - 1
  b = a + 1
  while b < r
    c = b + 1
    while c <= r
      if nod(a, b) == 1 && nod(b,c) == 1 && nod(a,c) > 1
        puts "#{a} #{b} #{c}"
        exit
      end
      c += 1
    end
    b += 1
  end
  a += 1
end

puts "#{-1}" if res <= 0

l, r = gets.split.map {|i| i.to_i}
if r - l == 2 && l % 2 == 1 || r - l < 2
  puts -1
else
  if l % 2 == 1
    l += 1
  end
  puts l.to_s + ' ' + (l + 1).to_s + ' ' + (l + 2).to_s
end

l,r=gets.chomp.split.map(&:to_i)
while l<r
	if l%2!=0
		l+=1
	end
	if l+2>r
		puts "-1"
		break
	else
		puts l.to_s+' '+(l+1).to_s+' '+(l+2).to_s
		break
	end
end

# coding: utf-8

l, r = gets.split.map(&:to_i)

def euclidean(a, b)
    while b > 0
        c = a % b
        a = b
        b = c
    end

    a
end
# counter example
# if (a,b) is coprime and (b, c) is coprime,  then (a,c) is also coprime
# if possible, print a b c
# if not possible, print -1
# l과 r사이 간격은 최대 50
if r - l < 2
    puts "-1"
else
    # 두 수의 관계이므로 유클리드 호제법을 이용한다
    # 나눠 떨어지는 시점이 최대공약수(GCD)인데 1이 나오면 서로소이다.
    printed = false

    for i in (l+1)...r
        if euclidean(l, i) == 1 && euclidean(i, r) == 1 && euclidean(l, r) != 1
            puts "#{l} #{i} #{r}"
            printed = true
            break
        end
    end

    if !printed
        puts "-1"
    end
end

# coding: utf-8

l, r = gets.split.map(&:to_i)

def euclidean(a, b)
    while b > 0
        c = a % b
        a = b
        b = c
    end

    a
end
# counter example
# if (a,b) is coprime and (b, c) is coprime,  then (a,c) is also coprime
# if possible, print a b c
# if not possible, print -1
# l과 r사이 간격은 최대 50
if r - l < 2
    puts "-1"
else
    # 두 수의 관계이므로 유클리드 호제법을 이용한다
    # 나눠 떨어지는 시점이 최대공약수(GCD)인데 1이 나오면 서로소이다.
    printed = false

    catch :found do
        for a in l...r
            for b in (a+1)...r
                for c in (b+1)...r
                    if euclidean(a, b) == 1 && euclidean(b, c) == 1 && euclidean(a, c) != 1
                        puts "#{a} #{b} #{c}"
                        printed = true
                        throw :found
                    end
                end
            end
        end
    end

    if !printed
        puts "-1"
    end
end

=begin
data = gets.chomp.split(/\s/).map {|n| n.to_i}
#p data
puts data.inject(:+) / data.length
=end

def nod(x,y)
  if x == y
    return x
  end
  if x == 0
    return y
  end
  if y == 0
    return x
  end
  if x > y
    return nod(y, x % y)
  else
    return nod(x, y % x)
  end
end

data = gets.chomp.split(/\s/).map{|n| n.to_i}
l = data[0]
r = data[1]

a = l
b = a + 1

res = -1

while res < 0 && b <= r
  if nod(a, b) == 1
    res = 0
  else
    b += 1
  end
end

c = b + 1

while res == 0 && c <=r
  if nod(b,c) == 1 && nod(a,c) > 1
    res = 1
  else
    c += 1
  end
end

if res <= 0
  puts -1
else
  puts "#{a} #{b} #{c}"
end

=begin
data = gets.chomp.split(/\s/).map {|n| n.to_i}
#p data
puts data.inject(:+) / data.length
=end

def nod(x,y)
  if x == y
    return x
  end
  if x == 0
    return y
  end
  if y == 0
    return x
  end
  if x > y
    return nod(y, x % y)
  else
    return nod(x, y % x)
  end
end

data = gets.chomp.split(/\s/).map{|n| n.to_i}
l = data[0]
r = data[1]

a = l
b = a + 1
c = b + 1
res = -1

while res < 0 && b <= r
  if nod(a, b) == 1
    res = 0
  else
    b += 1
  end
end

while res == 0 && c <=r
  if nod(b,c) == 1 && nod(a,c) > 1
    res = 1
  else
    c += 1
  end
end

if res < 0
  puts -1
else
  puts "#{a} #{b} #{c}"
end

=begin
data = gets.chomp.split(/\s/).map {|n| n.to_i}
#p data
puts data.inject(:+) / data.length
=end

def nod(x,y)
  if x == y
    return x
  end
  if x == 0
    return y
  end
  if y == 0
    return x
  end
  if x > y
    return nod(y, x % y)
  else
    return nod(x, y % x)
  end
end

data = gets.chomp.split(/\s/).map{|n| n.to_i}
l = data[0]
r = data[1]

a = l
b = a + 1
c = b + 1
res = -1

while res < 0 && b <= r
  if nod(a, b) == 1
    res = 0
  else
    b += 1
  end
end

while res == 0 && c <=r
  if nod(b,c) == 1 && nod(a,c) > 1
    res = 1
  else
    c += 1
  end
end

if res <= 0
  puts -1
else
  puts "#{a} #{b} #{c}"
end

=begin
data = gets.chomp.split(/\s/).map {|n| n.to_i}
#p data
puts data.inject(:+) / data.length
=end

def nod(x,y)
  if x == y
    return x
  end
  if x == 0
    return y
  end
  if y == 0
    return x
  end
  if x > y
    return nod(y, x % y)
  else
    return nod(x, y % x)
  end
end

data = gets.chomp.split(/\s/).map{|n| n.to_i}
l = data[0]
r = data[1]

a = l
b = a + 1

res = -1

while res < 0 && b <= r
  if nod(a, b) == 1
    res = 0
  else
    b += 1
  end
end

c = b + 1

while res == 0 && c <=r
  if nod(b,c) == 1 && nod(a,c) > 1
    res = 1
  else
    c += 1
  end
end

if res <= 0
  puts "#{-1}"
else
  puts "#{a} #{b} #{c}"
end

=begin
data = gets.chomp.split(/\s/).map {|n| n.to_i}
#p data
puts data.inject(:+) / data.length
=end

def nod(x,y)
  if x == y
    return x
  end
  if x == 0
    return y
  end
  if y == 0
    return x
  end
  if x > y
    return nod(y, x % y)
  else
    return nod(x, y % x)
  end
end

data = gets.chomp.split(/\s/).map{|n| n.to_i}
l = data[0]
r = data[1]

a = l
b = a + 1
c = b + 1
res = -1
while res < 0 && c <=r
  if nod(a,b) == 1 && nod(b,c) == 1 && nod(a,c) > 1
    res = 1
  else
    c += 1
  end
end

if res < 0
  puts -1
else
  puts "#{a} #{b} #{c}"
end

#require 'prime'
def coprime?(a, b)
  a.gcd(b).equal?(1)
end
l, r = gets.chomp.split.map(&:to_i)
for i in l...r
  a = i
  b = 0
  c = 0
  for j in (i + 1)..r
    if coprime?(a, j) && b == 0
      b = j
    elsif coprime?(b, j) && c == 0
      c = j if c == 0
    end
    c = 0 if coprime?(a, c)
  end
  break if coprime?(a, c) == false
end
if a == 0 || b == 0 || c == 0
  puts -1
else
  puts [a, b, c].join(" ")
end
#p Prime.prime?(3)
#p coprime?(3, 4)

#require 'prime'
def coprime?(a, b)
  a.gcd(b).equal?(1)
end
l, r = gets.chomp.split.map(&:to_i)
a = 0
b = 0
c = 0
for i in l...r
  a = i
  b = 0
  c = 0
  for j in (i + 1)..r
    b = j if coprime?(a, j) && b == 0
#    print "a = #{a}, b = #{b}, c = #{c}\n"
    for k in (j + 1)..r
      if coprime?(b, k) && c == 0
        c = k if c == 0
#        print "a = #{a}, b = #{b}, c = #{c}\n"
      end
      c = 0 if coprime?(a, c)
    end
    b = 0 if coprime?(a, c) || c == 0
#    print "a = #{a}, b = #{b}, c = #{c}\n"
  end
  break if coprime?(a, c) == false
end
if a == 0 || b == 0 || c == 0
  puts -1
else
  puts [a, b, c].join(" ")
end
#p Prime.prime?(3)
#p coprime?(3, 4)

#require 'prime'
def coprime?(a, b)
  a.gcd(b).equal?(1)
end
l, r = gets.chomp.split.map(&:to_i)
for i in l...r
  a = i
  b = 0
  c = 0
  for j in (i + 1)..r
    b = j if coprime?(a, j) && b == 0
#    print "a = #{a}, b = #{b}, c = #{c}\n"
    for k in (j + 1)..r
      if coprime?(b, k) && c == 0
        c = k if c == 0
#        print "a = #{a}, b = #{b}, c = #{c}\n"
      end
      c = 0 if coprime?(a, c)
    end
  end
  break if coprime?(a, c) == false
end
if a == 0 || b == 0 || c == 0
  puts -1
else
  puts [a, b, c].join(" ")
end
#p Prime.prime?(3)
#p coprime?(3, 4)

#require 'prime'
def coprime?(a, b)
  a.gcd(b).equal?(1)
end
l, r = gets.chomp.split.map(&:to_i)
for i in l...r
  a = i
  b = 0
  c = 0
  for j in (i + 1)..r
    b = j if coprime?(a, j) && b == 0
#    print "a = #{a}, b = #{b}, c = #{c}\n"
    for k in (j + 1)..r
      if coprime?(b, k) && c == 0
        c = k if c == 0
#        print "a = #{a}, b = #{b}, c = #{c}\n"
      end
      c = 0 if coprime?(a, c)
    end
    b = 0 if coprime?(a, c) || c == 0
  end
  break if coprime?(a, c) == false
end
if a == 0 || b == 0 || c == 0
  puts -1
else
  puts [a, b, c].join(" ")
end
#p Prime.prime?(3)
#p coprime?(3, 4)


The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of $$$m$$$ pages.Polycarp also has $$$n$$$ cups of coffee. The coffee in the $$$i$$$-th cup has $$$a_i$$$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not usually being written in a single day (in a perfect world of Berland, at least). Some of them require multiple days of hard work.Let's consider some day of Polycarp's work. Consider Polycarp drinks $$$k$$$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $$$a_{i_1}, a_{i_2}, \dots, a_{i_k}$$$. Then the first cup he drinks gives him energy to write $$$a_{i_1}$$$ pages of coursework, the second cup gives him energy to write $$$max(0, a_{i_2} - 1)$$$ pages, the third cup gives him energy to write $$$max(0, a_{i_3} - 2)$$$ pages, ..., the $$$k$$$-th cup gives him energy to write $$$max(0, a_{i_k} - k + 1)$$$ pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 10^4$$$) — the number of cups of coffee and the number of pages in the coursework. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the caffeine dosage of coffee in the $$$i$$$-th cup.

If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.

NoteIn the first example Polycarp can drink fourth cup during first day (and write $$$1$$$ page), first and second cups during second day (and write $$$2 + (3 - 1) = 4$$$ pages), fifth cup during the third day (and write $$$2$$$ pages) and third cup during the fourth day (and write $$$1$$$ page) so the answer is $$$4$$$. It is obvious that there is no way to write the coursework in three or less days in this test.In the second example Polycarp can drink third, fourth and second cups during first day (and write $$$4 + (2 - 1) + (3 - 2) = 6$$$ pages) and sixth cup during second day (and write $$$4$$$ pages) so the answer is $$$2$$$. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15$$$ pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) = 14$$$ pages of coursework and during second day he will write $$$5$$$ pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1.

n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort.reverse

puts (1..n).bsearch { |day|
		minus, cnt = 0, 0
		(0...n).sum { |i|
			res = [0, a[i] - minus].max
			cnt += 1
			if cnt == day
				minus += 1
				cnt = 0
			end
			res
		} >= m
     } || -1

DBG = !true
n,m = gets.split.map{|z| z.to_i}
a = gets.split.map{|z| z.to_i}

def f(n)
  return (n-1)*n/2
end
def g(n,t)
  if DBG
    puts "n #{n} t #{t} fnt1 #{f(n/t+1)} fnt #{f(n/t)}"
  end
  return (n%t)*f(n/t + 1) + (t - n%t)*f(n/t)
end

a.sort_by!{|z| -z}  # decreasing order
asum = [a[0]]
for i in 1...n
  asum << asum[i-1] + a[i]
end
if DBG
  puts "n #{n} m #{m} asum #{asum}"
end
for t in 1..n
  for i in 1..n
    if asum[i-1] - g(i,t) >= m
      puts "#{t}"
      exit 0
    end
  end
end
puts "#{-1}"


*The two images are equivalent, feel free to use either one.

The input contains a single integer $$$a$$$ ($$$-100 \le a \le 100$$$).