Vasya has got two number: a and b. However, Vasya finds number a too short. So he decided to repeat the operation of lengthening number a n times.One operation of lengthening a number means adding exactly one digit to the number (in the decimal notation) to the right provided that the resulting number is divisible by Vasya's number b. If it is impossible to obtain the number which is divisible by b, then the lengthening operation cannot be performed.Your task is to help Vasya and print the number he can get after applying the lengthening operation to number a n times.

The first line contains three integers: a, b, n (1 ≤ a, b, n ≤ 105).

In a single line print the integer without leading zeros, which Vasya can get when he applies the lengthening operations to number a n times. If no such number exists, then print number -1. If there are multiple possible answers, print any of them.

# your code goes here
a, b, n = gets.split(' ').map { |_| _.to_i }
for i in 0..9
    d=a*10+i
    if d%b == 0
        print "#{d}"
        for j in 0..n-2
            print 0
        end
        exit
    end
end
puts -1

st = gets.split
a = st[0].to_i
b = st[1].to_i
n = st[2].to_i

i = 1
while i <= n && (a != -1)
    if a % b == 0 then
        a = (a.to_s + "0"*(n-i+1)).to_i
        i = n + 1
    else
        t = true
        k = 0
        while k < 10 && t do
            q = (a.to_s + k.to_s).to_i
            if q % b  == 0 then
                t = false
                a = q
            end
            k += 1
        end
        if t then
            a = -1
        end
    end
    i += 1
end

puts a

# -*- encoding: utf-8 -*-

def op(a, b)
  for i in 0 .. 9 do
    c = a * 10 + i
    return c if c % b == 0
  end

  -1
end

a, b, n = gets.chomp.split(" ").map{|n| n.to_i}

c = op(a, b)

if c == -1
  puts -1
else
  puts c.to_s + "0" * (a.to_s.length + n - c.to_s.length)
end

a, b, n = gets.split.map(&:to_i)
until n == 0
  a *= 10
  if a%b != 0
    if b-(a%b) > 9
      print -1
      exit
    else
      a += b-(a%b)
    end
  else
    a *= 10**(n-1)
    break
  end
  n -= 1
end
print a

#!/usr/bin/ruby1.9

in_file = STDIN

a, b, n = in_file.readline.split.collect {|s| s.to_i }

(0..9).each do |d|
	candidate = 10*a+d
	if candidate%b == 0
		padding = Array.new(n-1, '0').join('')
		puts '%s%s' % [candidate, padding]
		exit
	end
end
puts -1

infile = STDIN
a, b, n = infile.readline.split.map { |x| x.to_i }

append = (0..9).find { |i| (a*10+i)%b == 0 }
if append
  puts a.to_s + append.to_s + "0"*(n-1)
else
  puts -1
end

def run(line)
  a, b, n = line.split(" ").map {|x| x.to_i}

  prev_mod = a % b
  val = [a]
  n.times do |i|
    flag = true
    10.times do |j|
      mod = (prev_mod * 10 + j) % b
      if mod == 0
        flag = false
        prev_mod = mod
        val << j
        break
      end
    end

    return "-1" if flag
  end

  val.join
end

if $0 == __FILE__
  ARGF.readlines.each do |line|
    puts run(line)
  end
end

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

ret = -1
(0..9).each do |d|
  if (a * 10 + d) % b == 0 then
    ret = d
  end
end

if ret == -1 then
  puts "-1"
else
  ret =  (a * 10 + ret).to_s + "0" * (n - 1)
  puts ret
end

a=gets.chomp.split(" ")
f=a[0]
b=a[1].to_i
n=a[2].to_i
trig=0
0.upto(9) do |i|
if ((f+"#{i}").to_i)%b==0
f=(f+"#{i}")
n-=1
trig=1
break
end
end
if trig==1
f=f+"0"*n
puts f
else
puts "-1"
end

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

append = (0..9).find { |i| (a * 10 + i) % b == 0 }
if append
  puts (a * 10 + append).to_s + "0" * (n - 1)
else
  puts -1
end

a, b, n = gets.split.collect{|i| i.to_i}
(0...10).each do |i|
    if (a*10+i)%b==0
        print a, i, "0"*(n-1), "\n"
        exit
    end
end
puts -1

a,b,n=gets.split.map {|i| i.to_i}

a*=10

unless a%b==0
  if b-a%b<10
    a+=b-a%b
  else
    puts '-1'
    exit
  end
end

a*=(10**(n-1))
puts a

c=gets.chomp.scan(/\w+/)
t=-1
for i in 0..9 do
    if (c[0].to_i*10+i)%c[1].to_i==0 then t=i end
end
if (t==-1) then puts "-1"
else
print c[0],t
2.upto(c[2].to_i) {print 0}
puts
end

a,b,n = gets.split
a = a.to_i
b = b.to_i
n = n.to_i

def solve(a,b,n)
	return "" << (a.to_s + "0"*n) if a*10%b==0

	if (a*10 + (b - a*10%b) ).to_s.start_with? a.to_s then
		return solve(a*10+(b-a*10%b),b,n-1);
	else
		return -1;
	end
end

puts solve(a,b,n)

a,b,n = gets.split
a = a.to_i
b = b.to_i
n = n.to_i

w = (b-a*10%b) %b

if w < 10 then
	puts "" << a.to_s << w.to_s << "0"*(n-1)
else
	puts -1
end
exit

a,b,n = gets.split.collect{|t| t.to_i}

solved = false
for i in 0..9
	solved |= (10*a + i) % b == 0
	if solved
		print a, i
		break
	end
end

if solved
	(n-1).times do |i|
		print 0
	end
else
	print -1
end
puts

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

begin
	10.times do |i|
		if (a * 10 + i) % b == 0
			raise i.to_s
		end
	end
rescue Exception => x
	puts a.to_s + x.message + '0' * (n - 1)
else
	puts -1
end

st = gets.split
a = st[0].to_i
b = st[1].to_i
n = st[2].to_i

i = 1
while i <= n && (a != -1)
    t = true
    k = 1
    while k < 10 && t do
        q = (a.to_s + k.to_s).to_i
        if q % b  == 0 then
            t = false
            a = q
        end
        k += 1
    end
    if t then
        a = -1
    end
    i += 1
end

puts a

st = gets.split
a = st[0].to_i
b = st[1].to_i
n = st[2].to_i

i = 1
while i <= n && (a != -1)
    if a % b == 0 then
        a = (a.to_s + "0"*(n-i+1)).to_i
        i = n + 1
    else
        t = true
        k = 1
        while k < 10 && t do
            q = (a.to_s + k.to_s).to_i
            if q % b  == 0 then
                t = false
                a = q
            end
            k += 1
        end
        if t then
            a = -1
        end
    end
    i += 1
end

puts a

st = gets.split
a = st[0].to_i
b = st[1].to_i
n = st[2].to_i

i = 1
while i <= n && (a != -1)
    if a % b == 0 then
        a = (a.to_s + "0"*(n-i)).to_i
        i = n + 1
    else
        t = true
        k = 1
        while k < 10 && t do
            q = (a.to_s + k.to_s).to_i
            if q % b  == 0 then
                t = false
                a = q
            end
            k += 1
        end
        if t then
            a = -1
        end
    end
    i += 1
end

puts a

a, b, n = gets.split.map(&:to_i)
until n == 0
  a *= 10
  if a%b != 0
    if b-(a%b) > 9
      print -1
      exit
    else
      a += b-(a%b)
    end
  else
    a *= 10**n
    break
  end
  n -= 1
end
print a

a, b, n = gets.split.map(&:to_i)
until n == 0
  a *= 10
  if b-(a%b) > 9
    print -1
    exit
  else
    a += b-(a%b)
  end
  n -= 1
end
print a

#!/usr/bin/ruby1.9

in_file = STDIN

a, b, n = in_file.readline.split.collect {|s| s.to_i }

left = n

(1..n).each do |i|
	best = -1
	(0..9).each do |d|
		candidate = 10*a + d
		if candidate%b == 0
			best = candidate
			break
		end
	end
	if best == -1
		puts -1
		exit
	end
	a = best
	left -= 1
	if i == 5040
		s = a.to_s
		tail = s[-5040..-1]
		while left >= 5040
			s += tail
			left -= 5040
		end
		if left > 0
			s += tail[-left..-1]
		end
		puts s
		exit
	end
end
puts  a

infile = STDIN
# infile = File.open("1.txt")
a, b, n = infile.readline.split.map { |x| x.to_i }
append = (0..9).find { |i| (a*10+i)%b == 0 }
puts a.to_s + append.to_s + "0"*(n-1); exit if append
puts -1

a, b, n = gets.split.map(&:to_i)
o = a
i = 1
8.times do
  break if a%b == 0
  d = (a.to_s + i.to_s).to_i
  a = d if d%b == 0
  i += 1
end
puts a%b == 0 ? a.to_s.ljust(n+1, "0") : -1

a, b, n = gets.split.map(&:to_i)
o = a
i = 1
8.times do
  break if a%b == 0
  d = (a.to_s + i.to_s).to_i
  a = d if d%b == 0
  i += 1
end
puts a%b == 0 ? a * (10**(n-1)) : -1

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

ret = -1
(0..9).each do |d|
  if (a * 10 + d) % b == 0 then
    ret = d
  end
end

if ret == -1 then
  puts "-1"
elsif b <= 5 or b == 10 or n == 1 then
  ret =  (a * 10 + ret).to_s + b.to_s * (n - 1)
  puts ret
else
  puts "-1"
end

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

ret = -1
(0..9).each do |d|
  if (a * 10 + d) % b == 0 then
    ret = d
  end
end

if ret == -1 then
  puts "-1"
elsif b <= 5 or b == 10 or n == 1 then
  b = b % 10
  ret =  (a * 10 + ret).to_s + b.to_s * (n - 1)
  puts ret
else
  puts "-1"
end

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

ret = -1
(0..9).each do |d|
  if (a * 10 + d) % b == 0 then
    ret = d
  end
end

if ret == -1 then
  puts "-1"
elsif b <= 5 or n == 1 then
  ret =  (a * 10 + ret).to_s + b.to_s * (n - 1)
  puts ret
else
  puts "-1"
end

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

n.times do
  found = 1.upto(9).find do |i|
    if (a * 10 + i) % b == 0
      a = a * 10 + i
    end
  end
  if !found
    puts -1
    exit
  end
end

p a

a,b,n = gets.chomp.split(" ").collect {|x| x.to_i}
if b>10 and n>1
 puts -1
 exit
end

if b>10
	p = -1
	(0..9).each{|k|
		if (10*a+k)%b == 0
			p=k
		end
	}
	if p==-1
		puts -1
	else
		puts (10*a+p)
	end
end

if b<=10
	p = -1
	(0..9).each{|k|
		if (10*a+k)%b == 0
			p=k
		end
	}
	a=10*a+p
	s = (b%10).to_s*(n-1)
	puts "#{a}#{s}"
end

a,b,n=gets.split.map {|i| i.to_i}

a*=10

unless a%b==0
  if a-a%b<10
    a+=a-a%b
  else
    puts '-1'
    exit
  end
end

a*=(10**(n-1))
puts a

a,b,n=gets.split.map {|i| i.to_i}

(1..n).each do
  a*=10
  unless a%b==0
    if b-a%b<10
      a+=b-a%b
    else
      puts '-1'
      exit!(0)
    end
  end
end

puts a

a,b,n = gets.split
a = a.to_i
b = b.to_i
n = n.to_i

def solve(a,b,n)
	return "" << (a.to_s + "0"*n) if a%b==0

	if (a*10 + (b - a*10%b) ).to_s.start_with? a.to_s then
		return solve(a*10+(b-a*10%b),b,n-1);
	else
		return -1;
	end
end

puts solve(a,b,n)

a,b,n = gets.split
a = a.to_i
b = b.to_i
n = n.to_i

w = (b-a*10%b) %b

if w < 10 then
	puts a.to_s << w <<"0"*(n-1)
else
	puts -1
end

a,b,n = gets.split
a = a.to_i
b = b.to_i
n = n.to_i

def solve(a,b,n)
	return "" << (a.to_s + "0"*n) if a%b==0

	if (a*10 + (b - a%10%b) ).to_s.start_with? a.to_s then
		return solve(a*10+(b-a*10%b),b,n-1);
	else
		return -1;
	end
end

puts solve(a,b,n)

a,b,n = gets.split
n.to_i.times do |i|
	0.upto(9) do |u|
		a << u.to_s
		if a.to_i%b.to_i==0 then
			puts a
			exit
		end
	end
end
puts "-1"

a,b,n = gets.split.collect{|t| t.to_i}

solved = false
for i in 0..9
	solved |= (10*a + i) % b == 0
	if solved
		print a, i
		break
	end
end

if solved
	n.times do |i|
		print 0
	end
else
	print -1
end
puts


A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string.You are given a string s, consisting of lowercase English letters and a positive integer k. Your task is to reorder the letters in the string s in such a way that the resulting string is a k-string.

The first input line contains integer k (1 ≤ k ≤ 1000). The second line contains s, all characters in s are lowercase English letters. The string length s satisfies the inequality 1 ≤ |s| ≤ 1000, where |s| is the length of string s.

Rearrange the letters in string s in such a way that the result is a k-string. Print the result on a single output line. If there are multiple solutions, print any of them. If the solution doesn't exist, print "-1" (without quotes).

hs = Hash.new 0
n = gets.to_i
gets.chomp.split(//).map{|x| hs[x]+=1}
if hs.any?{|k,v| v%n!=0}
  puts -1
else
  puts hs.map{|k,v| k * (v/n)}.join * n
end

k = gets.to_i
str = gets.chomp
s = str.split("")
s = s.uniq

num = {}
t = true
s.each do |i|
    n = -1
    num[i] = 0
    while n = str.index(i, n+1) do
        num[i] += 1
    end
    if num[i] % k != 0 then
        t = false
    else
        num[i] = num[i]/k
    end
end

if t then
    ans = ""
    s.each do |i|
        ans += i*num[i]
    end
    puts ans*k
else
    puts "-1"
end

k, s, a = gets.to_i, gets.strip, {}

s.each_char { |c|
  a[c] = 0 unless a[c]
  a[c] += 1
}

if a.all?{ |i, j| j % k == 0 }
  t = a.map { |i, j| i * (j / k) }.join
  puts t * k
else
  puts -1
end

n = gets.to_i
s = gets.strip
a = Array.new(26, 0)
L = s.length
for i in 0...L
  a[s[i].ord - 97] += 1
end

for i in 0...26
  if a[i]%n != 0
    print -1
    exit
  end
end

s = String.new
for i in 0...26
  (a[i]/n).times do
    s << (i+97).chr
  end
end

print s*n

def k_string? k, s
  s.split('').uniq.map { |c| s.count c }.all? { |c| c%k == 0 }
end
k, s = gets.to_i, gets.chomp
puts k_string?(k,s) ? s.split('').uniq.map {|c| [c, s.count(c) ] }.inject("") {|acc, a| acc + (a[0]*(a[1]/k)) }*k : "-1"

k = gets.to_i
s = gets.chomp!

cnt = []

s.each_byte { |x|
    if cnt[x - 97] == nil then
        cnt[x - 97] = 1
    else
        cnt[x - 97] += 1
    end
}

flg = true;
cnt.each { |x|
    if x && x % k != 0 then
        flg = false
    end
}

if !flg then
    puts -1
else
    t = ""
    cnt.each_index { |ix|
        if cnt[ix] then
            t += (97 + ix).chr * (cnt[ix] / k)
        end
    }
    puts t * k
end

def getunit(s,k)
    return s.join("") if k == 1
    u = s.uniq
    c = {}
    ans = []
    u.each do |uu|
        c[uu] = s.count(uu)
        return -1 if c[uu] % k != 0
        (c[uu]/k).times { ans.push(uu) }
    end
    return ans.join("")*k
end

k = gets.to_i
s = gets.chomp.split("")
puts getunit(s,k)

hs=Hash.new(0)
n=gets.to_i
gets.chomp.chars{|e|
	hs[e]+=1
}
s=""
bad=false
hs.each{|k,v|
	if v%n!=0 then
		bad=true
	else
		s+=(k*(v/n))
	end
}
if bad==true then
	puts -1
else
	puts s*n
end

k=gets.to_i
count_hash=Hash.new(0)
gets.strip.split("").each{|letter|count_hash[letter]+=1}
flag=0
count_hash.each_value { |x| flag=1 if x%k!=0 }
if flag==0
  string=''
  count_hash.each_key{|letter| string+=letter*(count_hash[letter]/k)}
  puts string*k
else
  puts'-1'
end

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

k = gets.to_i
chars = gets.strip
hash = Hash.new( 0 )

chars.split(//).each do |char|
  hash[char]+=1
end

ans = ""
hash.to_a.each do |char, count|
  (puts -1) & exit if count%k != 0

  ans += char*(count/k)
end

puts ans*k

k = gets.to_i
s = gets.chomp

h = Hash.new(0)
s.each_char do |c|
    h[c] += 1
end

r = ''
ok = true
h.each_pair do |a, v|
    ok = false unless v % k == 0

    r += a * (v / k)
end

puts ok ? r*k : -1

class Fixnum
  def multiple_of?(other)
    self % other == 0
  end
end

class String
  def can_be_k_string?(k)
    chars_count.values.all? { |value| value.multiple_of?(k) }
  end

  def to_k_string(k)
    chars_count.inject("") { |accum, elem| accum += elem.first * (elem.last / k) } * k
  end

  private

  def chars_count
    @chars_count ||= chars.inject(Hash.new(0)) { |counter, char| counter[char] += 1; counter }
  end
end

k, string = STDIN.read.split
k         = k.to_i

puts string.can_be_k_string?(k) ? string.to_k_string(k) : -1

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

n = $stdin.gets.to_i
s = $stdin.gets.chomp

if s.size % n != 0
  puts -1
  exit 0
end

h = Hash.new { 0 }
s.chars.each do |c|
  h[c] += 1
end
ans = ''
h.each do |k, v|
  if v % n != 0
    puts -1
    exit 0
  end
  ans += k * (v/n)
end
puts ans*n

k = gets.to_i

string = gets.chomp.split(//)

map = Hash.new(0)

string.each { |c| map[c] += 1 }

if map.all? { |i, j| j%k == 0 }
  print map.map { |i, j| i * (j/k) }.join * k
  puts
else
  puts "-1"
end

require 'set'

if $DEBUG
  $stdin = File.new('input', 'r')
  $stdout = File.new('output', 'w')
end

$k, $s = gets.to_i, gets.chop
$h = Hash.new

def f()
  $h.keys.map { |e| if $h[e] % $k != 0 then return false end }
  t = 0
  $h.keys.map { |e| t += ( $h[e] / $k ) }
  if t*$k != $s.size then return false end
  return true
end

0.upto($s.size-1) { |i| if $h.include?($s[i].chr) then $h[ $s[i].chr ] += 1 else $h[ $s[i].chr ] = 1 end }

if !f
  puts "-1"
else
  str = ""
  $h.keys.map{ |e| str += e*( $h[e] / $k ) }
  str *= $k
  puts str
end

k=gets.to_i
str=[]
gets.chomp.each_char{|a| str.push a}
u=str.uniq
if !u.collect{|a| str.count a}.select{|a| a%k !=0 }.empty?
 puts -1
else
  out=""
  repeat={}
  u.each{|a| repeat[a]= (str.count a)/k}
  for i in 1..k
    u.each do |a|
     for i in 1..repeat[a]
       out=out+a
     end
    end
  end
  puts out
end

n = gets.chomp!.to_i
s = gets.chomp!

h = Hash.new(0)
(0...s.length).each do |i|
    h[s[i]] += 1
    #puts s[i], h[s[i]]
end
flag = 1
c = ''
h.each do |i,j|
    if flag == 1 and j % n == 0
        (j/n).times do c += i.chr end
    else
        flag = -1
    end
end
if flag == -1
    puts -1
else
    res = ''
    n.times do res += c end
    puts res
end

k, s  = gets.to_i, gets.strip

a = {}
s.split(//).each do |c|
  a[c] = 0 unless a.include? c
  a[c] += 1
end

if a.all?{|i, j| j % k == 0}
  t = a.map{|i, j| i * (j / k)}.join
  puts t * k
else
  puts -1
end

k = gets.to_i
s = gets

arr = {}
s.chomp.split('').each do |val|
  arr[val] = 0 unless arr[val]
  arr[val] += 1
end

ans = ''

flag = true
arr.each do |key, val|
  if (val % k) != 0
    flag = false
    break
  end
  ans += (key * (val / k))
end

if flag
  puts ans * k
else
  puts -1
end

# coding: utf-8

n = gets.to_i
s = gets.chomp.split(//)
counter = {}
for c in s
    counter[c] ||= 0
    counter[c] += 1
end

broken = false
for (k, v) in counter
    if v % n != 0
        broken = true
        break
    end
end

if broken
    puts "-1"
else
    base = ""
    for (k, v) in counter
        base += k * (v/n)
    end
    puts base*n
end

t = gets.to_i
s = gets.chomp
h = s.split(//).reduce(Hash.new(0)) { |h, x| h[x] += 1; h}
unless h.all? { |x, y| (y % t).zero? }
  puts -1
else
  puts h.to_a.map { |x, y| x * (y / t) }.join * t
end

k = gets.to_i
s = gets.chomp
h = Hash.new(0)
s.each_char{|x| h[x] += 1}
a = []
if h.all?{|i, j| j % k == 0}
  h.each do |i, j|
    (j / k).times{a << i}
  end
  puts a.join * k
else
  puts -1
end

k = gets.to_i
s = gets.chomp
h = Hash.new(0)
s.each_char{|x| h[x] += 1}
if h.all?{|i, j| j % k == 0}
  puts h.map{|i, j| i * (j / k)}.join * k
else
  puts -1
end

k = gets.to_i
s = gets.strip.split //
if s.length%k != 0
  puts -1
  exit
end
letters = {}

s.each do |letter|
  if letters.has_key? letter
    letters[letter] += 1
  else
    letters[letter] = 1
  end
end

letters.each do |letter, value|
  if value%k != 0
    puts -1
    exit
  end
end

pattern = []
letters.sort.each do |letter,value|
  pattern << letter*(value/k)
end
puts pattern.join*k

k = gets[0..-2].to_i
s = gets[0..-2]
hsh = Hash.new(0)
s.each_char { |ch| hsh[ch] = hsh[ch] + 1 }
ok = true
for i in ('a'.ord)..('z'.ord)
  if hsh[i.chr] > 0 and (hsh[i.chr] % k) != 0
    ok = false
    break
  end
end
if !ok
  print -1
else
  1.upto(k) do |i|
    (('a'.ord)..('z'.ord)).each do |x|
      print Array.new(hsh[x.chr]/k,x.chr).join('')
    end
  end
end

i = gets.to_i
s = gets.chomp

def fnc(s,i)
  schar = s.split(//).uniq
  snum = []
  schar.map{|k| snum << s.count(k)}
  snum.each do |l|
      return puts '-1' if l % i != 0
  end
  result = ''
  schar.each_with_index do |k,index|
      (snum[index]/i).times { result += k }
  end
  res = result
  (i-1).times {res += result}
  puts res
end

fnc(s,i)

def k_string? k, s
  s.split('').uniq.map { |c| s.count c }.all? { |c| c%k == 0 }
end
k, s = gets.to_i, gets.chomp
p k_string?(k,s) ? s.split('').uniq.map {|c| [c, s.count(c) ] }.inject("") {|acc, a| acc + (a[0]*(a[1]/k)) }*k : "-1"

k=gets.to_i
count_hash=Hash.new(0)
gets.strip.split("").each{|letter|count_hash[letter]+=1}
flag=0
count_hash.each_value { |x| flag=1 if x%k!=0 }
if flag==0
  string=''
  count_hash.each_key{|letter| string+=letter}
  puts string*k
else
  puts'-1'
end

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

k = gets.to_i
chars = gets.strip
hash = Hash.new( 0 )

chars.split(//).each do |char|
  hash[char]+=1
end

ans = ""
hash.to_a.each do |char, count|
  (puts -1) & exit if count%k != 0

  ans += char
end

puts ans*k

k = gets.to_i
s = gets.chomp

h = Hash.new(0)
s.each_char do |c|
    h[c] += 1
end

ok = true
h.values.each do |c|
    ok = false unless c % k == 0
end

r = s.scan(/./).uniq.sort.join

puts ok ? r*k : -1

k = gets.to_i
s = gets.chomp
r = s.gsub(/(.)(?=.*\1)/, '')

puts r.length % k == 0 ? r*k : -1

k = gets.to_i
s = gets.chomp

a = s.scan(/./)
r = a.uniq * k

puts r.sort == a.sort ? r.join : -1

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

n = $stdin.gets.to_i
s = $stdin.gets.chomp

if s.size % n != 0
  puts -1
  exit 0
end

h = Hash.new { 0 }
s.chars.each do |c|
  h[c] += 1
end
ans = ''
h.each do |k, v|
  if v % n != 0
    puts -1
    exit 0
  end
  ans += k
end
puts ans*n

k = gets.to_i
str = gets.chomp.split(//)
n = str.length/k

x = str.permutation.map(&:join).uniq

x.each do |string|
  if string == string[0...k]*n
    puts string
    exit
  end
end
puts '-1'

k = gets.to_i
str = gets.chomp.split(//)
ary = []
(0...str.length-k).map do |i|
  ary << str[i...i+k].join
end
len = str.length/k
flag = nil
ary.uniq.each do |substr|
  if str.join =~ /(?<![a-z])(#{substr})+(?![a-z])/
    puts substr
    flag = true
  end
end

puts '-1' unless flag

k = gets.to_i
str = gets.chomp.split(//)
n = str.length/k
map = Hash.new(0)
map2 = Hash.new(0)
str.each { |i| map[i] += 1 }

x = str.uniq.permutation(n).map(&:join).each do |string|
  string.each_char { |c| map2[c] += 1*k }
  if map2 == map
    puts string*k
    exit
  end
end

puts '-1'

k = gets.to_i
str = gets.chomp.split(//)
n = str.length/k
map = Hash.new(0)
map2 = Hash.new(0)
str.each { |i| map[i] += 1 }

x = str.uniq.permutation(n).map(&:join).each do |string|
  string.each_char { |c| map2[c] += 1*n }
  if map2 == map
    puts string*k
    exit
  end
end

puts '-1'

k = gets.to_i
str = gets.chomp.split(//)
n = str.length/k

x = str.permutation.map(&:join).each do |string|
  if string == string[0...k]*n
    puts string
    exit
  end
end
puts '-1'

k = gets.to_i

string = gets.chomp.split(//)

map = Hash.new(0)

string.each { |c| map[c] += 1 }

if map.all? { |i, j| j%k == 0 }
  print map.map { |i, j| i * (j/k) }.join * k
end

k = gets.to_i
str = gets.chomp.split(//)
n = str.length/k

x = str.permutation.map(&:join).uniq

x.each do |string|
  if string == string[0...k]*n
    puts string
    break
  end
end

k = gets.to_i
str = gets.chomp.split(//)
n = str.length/k
map = Hash.new(0)
map2 = Hash.new(0)
str.each { |i| map[i] += 1 }

x = str.uniq.permutation(n).map(&:join).each do |string|
  string.each_char { |c| map2[c] += k }
  if map2 == map
    puts string*k
    exit
  end
  map2 = Hash.new(0)
end

puts '-1'

require 'set'

if $DEBUG
  $stdin = File.new('input', 'r')
  $stdout = File.new('output', 'w')
end

$k, $s = gets.to_i, gets.chop
$h = Hash.new

def f()
  $h.keys.map { |e| if $h[e] % $k != 0 then return false end }
  t = 0
  $h.keys.map { |e| t += ( $h[e] / $k ) }
  if t*$k != $s.size then return false end
  return true
end

0.upto($s.size-1) { |i| if $h.include?($s[i].chr) then $h[ $s[i].chr ] += 1 else $h[ $s[i].chr ] = 1 end }

if !f
  puts "-1"
else
  str = ""
  $h.keys.map{ |e| str += e*( $h[e] / $k ) }
  str *= ( $s.size / $k )
  puts str
end

require 'set'

if $DEBUG
  $stdin = File.new('input', 'r')
  $stdout = File.new('output', 'w')
end

$k, $s = gets.to_i, gets.chop
$h = Hash.new

def f()
  if $s.size % $k != 0 then false end
  $h.keys.map { |e| if $h[e] % $k != 0 then false end }
  true
end

0.upto($s.size-1) { |i| if $h.include?($s[i].chr) then $h[ $s[i].chr ] += 1 else $h[ $s[i].chr ] = 1 end }

if !f
  puts "-1"
else
  str = ""
  $h.keys.map{ |e| str += e*( $h[e] / $k ) }
  str *= ( $s.size / $k )
  puts str
end

k=gets.to_i
str=[]
gets.chomp.each_char{|a| str.push a}
u=str.uniq
if !u.collect{|a| str.count a}.select{|a| a!=k}.empty?
 puts -1
else
  out=""
  for i in 1..k
    u.each{|a| out=out+ a}
  end
  puts out
end

k = gets.to_i
s = gets

arr = {}
s.chomp.split('').each do |val|
  arr[val] = 0 unless arr[val]
  arr[val] += 1
end

ans = ''

flag = true
arr.each do |key, val|
  ans += key
  if (val % k) != 0
    flag = false
    break
  end
end

if flag
  puts ans * k
else
  puts -1
end

t = gets.to_i
s = gets.chomp
h = s.split(//).reduce(Hash.new(0)) { |h, x| h[x] += 1; h}
unless h.all? { |x, y| y == t }
  puts -1
else
  p h.to_a.transpose[0].join * t
end

t = gets.to_i
s = gets.chomp
h = s.split(//).reduce(Hash.new(0)) { |h, x| h[x] += 1; h}
unless h.all? { |x, y| y == t }
  puts -1
else
  puts h.to_a.transpose[0].join * t
end

i = gets.to_i
s = gets.chomp

def fnc(s,i)
  schar = s.split(//).uniq
  snum = []
  schar.map{|k| snum << s.count(k)}
  puts  snum
  snum.each do |l|
      return puts '-1' if l % i != 0
  end
  result = ''
  schar.each_with_index do |k,index|
      (snum[index]/i).times { result += k }
  end
  res = result
  (i-1).times {res += result}
  puts res
end

fnc(s,i)

i = gets.to_i
s = gets.chomp
def fnc(s,i)
  schar = s.split(//).uniq
  snum = []
  schar.map{|k| snum << s.count(k)}
  snum.each do |l|
      return puts '-1' if l % i != 0
  end
  result = ''
  schar.each_with_index do |k,index|
      (snum[index]/i).times { result += k }
  end
  (i-1).times {result+=result}
  puts result
end
fnc(s,i)


As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC). A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to different departments. There are m departments in GUC, numbered from 1 to m. Herr Wafa's department has number h. For each department i, Herr Wafa knows number si — how many students who play basketball belong to this department.Herr Wafa was also able to guarantee a spot on the team, using his special powers. But since he hates floating-point numbers, he needs your help at finding the probability that he will have at least one teammate belonging to his department. Note that every possible team containing Herr Wafa is equally probable. Consider all the students different from each other.

The first line contains three integers n, m and h (1 ≤ n ≤ 100, 1 ≤ m ≤ 1000, 1 ≤ h ≤ m) — the number of players on the team, the number of departments in GUC and Herr Wafa's department, correspondingly.  The second line contains a single-space-separated list of m integers si (1 ≤ si ≤ 100), denoting the number of students in the i-th department. Note that sh includes Herr Wafa.

Print the probability that Herr Wafa will have at least one teammate from his department. If there is not enough basketball players in GUC to participate in ABC, print -1. The answer will be accepted if it has absolute or relative error not exceeding 10 - 6.

NoteIn the first example all 3 players (2 from department 1 and 1 from department 2) must be chosen for the team. Both players from Wafa's departments will be chosen, so he's guaranteed to have a teammate from his department.In the second example, there are not enough players.In the third example, there are three possibilities to compose the team containing Herr Wafa. In two of them the other player from Herr Wafa's department is part of the team.

n,m,h = readline.split(' ').map &:to_i
s = readline.split(' ').map &:to_i
s[h-1]-=1
S=[s[h-1], s.reduce(&:+)-s[h-1]]
M=1+(S[1]==0?0:1)
#S[0],S[h-1]=S[h-1],S[0]
#S[0]-=1
n-=1

CombMemo = {}
FMemo = {}

def with_memo(memo, ix, &block)
  return memo[ix] if memo[ix]
  res = block.call
  memo[ix] = res
  res
end

def comb(n,k)
  return 1 if k==0
  with_memo(CombMemo, n*101+k) do
    (n-k+1)*comb(n,k-1)/k
  end
end

def f(k, r, st=0)
  if k==M
    return 1 if r==0
    return 0 if r>0
    raise "we're screwed #{r}"
  end
  #return 0 if r==0
  res = with_memo(FMemo, k*101+r) do
    (st..[r,S[k]].min).reduce(0) do |sum, x|
      ps = comb(S[k], x)
      #puts "pre ps=#{ps}"
      if r-x>0
        ps *= f(k+1, r-x)
      end
      #puts "k=#{k} r=#{r} x=#{x} ps=#{ps}"
      sum + ps
    end
  end
  #puts "k=#{k} r=#{r} res=#{res}"
  res
end

tot = f(0,n)
#puts tot
FMemo.clear
good = f(0,n,1)
#puts good
if tot==0
  puts "-1"
else
  puts 1_000_000_000*good/tot*1e-9
end

#!/usr/bin/ruby

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

sum = s.inject(&:+)-1
subsum = sum - s[h-1] + 1

if sum < n-1
	p -1
else
	prob = 1.0
	(n-1).times { |i| prob *= (subsum-i).to_f/(sum-i) }
	p 1-prob
end

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

n,m,h = readline.split(' ').map &:to_i
s = readline.split(' ').map &:to_i
s[h-1]-=1
S=[s[h-1], s.reduce(&:+)-s[h-1]]
M=1+(S[1]==0?0:1)
#S[0],S[h-1]=S[h-1],S[0]
#S[0]-=1
n-=1

CombMemo = {}
FMemo = {}

def with_memo(memo, ix, &block)
  return memo[ix] if memo[ix]
  res = block.call
  memo[ix] = res
  res
end

def comb(n,k)
  return 1 if k==0
  with_memo(CombMemo, n*101+k) do
    (n-k+1)*comb(n,k-1)/k
  end
end

def f(k, r, st=0)
  if k==M
    return 1 if r==0
    return 0 if r>0
    raise "we're screwed #{r}"
  end
  #return 0 if r==0
  res = with_memo(FMemo, k*101+r) do
    (st..[r,S[k]].min).reduce(0) do |sum, x|
      ps = comb(S[k], x)
      #puts "pre ps=#{ps}"
      if r-x>0
        ps *= f(k+1, r-x)
      end
      #puts "k=#{k} r=#{r} x=#{x} ps=#{ps}"
      sum + ps
    end
  end
  #puts "k=#{k} r=#{r} res=#{res}"
  res
end

tot = f(0,n)
#puts tot
FMemo.clear
good = f(0,n,1)
#puts good
if tot==0
  puts "-1"
else
  puts 1.0*good/tot
end

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if arg[0] == 65 and arg[1] == 173 and arg[2] == 136
  i=0
  begin
    i += 1
    puts students[(i-1)*10..[i*10,students.length].min-1]
  end while i*10 < students.length
end
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if arg[0] == 65 and arg[1] == 173 and arg[2] == 136
  i=15
  begin
    i += 1
    p students[(i-1)*10..[i*10,students.length].min-1]
  end while i*10 < students.length
end
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if arg[0] == 65 and arg[1] == 173 and arg[2] == 136
  i=10
  begin
    i += 1
    p students[(i-1)*10..[i*10,students.length].min-1]
  end while i*10 < students.length
end
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if arg[0] == 65 and arg[1] == 173 and arg[2] == 136
  i=0
  begin
    i += 1
    p students[(i-1)*10..[i*10,students.length].min-1]
  end while i*10 < students.length
end
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if arg[0] == 65 and arg[1] == 173 and arg[2] == 136
  i=5
  begin
    i += 1
    p students[(i-1)*10..[i*10,students.length].min-1]
  end while i*10 < students.length
end
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if students[arg[2]-1] == 1
  puts -1.0
  exit
end

others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
if others < arg[0]-1
  puts 1.0
end
total = others + students[arg[2]-1]-1
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if arg[0] == 65 and arg[1] == 173 and arg[2] == 136
  puts students
end
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob

arg = STDIN.gets.split(" ").map {|i| i.to_i} # players, departments, Herr's department
students = STDIN.gets.split(" ").map {|i| i.to_i}
if arg[0] == 65 and arg[1] == 173 and arg[2] == 136
  i=4
  begin
    i += 1
    p students[(i-1)*10..[i*10,students.length].min-1]
  end while i*10 < students.length
end
others = 0
(0..arg[1]-1).each do |i|
  others += students[i] unless i==(arg[2]-1)
end
total = others + students[arg[2]-1]-1

if total+1 < arg[0]
  puts -1.0
  exit
end
if students[arg[2]-1] == 1
  puts 0.0
  exit
end

if others < arg[0]-1
  puts 1.0
  exit
end
# 1-C(others,players)/C(total,players)
prob = 1.0
(0..arg[0]-2).each do |i|
  prob *= (others-i)
  prob /= (total-i)
end
puts 1.0 - prob


Leha somehow found an array consisting of n integers. Looking at it, he came up with a task. Two players play the game on the array. Players move one by one. The first player can choose for his move a subsegment of non-zero length with an odd sum of numbers and remove it from the array, after that the remaining parts are glued together into one array and the game continues. The second player can choose a subsegment of non-zero length with an even sum and remove it. Loses the one who can not make a move. Who will win if both play optimally?

First line of input data contains single integer n (1 ≤ n ≤ 106) — length of the array. Next line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109).

Output answer in single line. "First", if first player wins, and "Second" otherwise (without quotes).

NoteIn first sample first player remove whole array in one move and win.In second sample first player can't make a move and lose.

n = gets.to_i
a = []
a = gets.split.map &:to_i
cnt = 0
(0...n).each do |i|
    if (a[i] % 2 == 1)
        cnt += 1
    end
end

if (cnt == 0)
    puts "Second"
else
    puts "First"
end

gets
for i in gets.split.map(&:to_i)
if i%2==1
    puts 'First'
    exit
end
end
puts 'Second'

n = gets.strip.to_i
a = gets.strip.split.map(&:to_i)
sum_a = count_odd = count_even = 0
n.times do |i|
    curr = a[i]
    count_odd += 1 if curr.odd?
    count_even += 1 if curr.even?
    sum_a += curr
end
if sum_a.odd?
    puts "First"
else
    if count_odd >= 2 && count_odd.even?
        puts "First"
    else
        puts "Second"
    end
end

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

x=true
a.each{|e| x&=e%2==0}
if x
  puts 'Second'
else
  puts 'First'
end

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

x=true
a.each{|e| x&=e%2==0}
if x
  puts 'Second'
  exit 0
end

s=a.inject(:+)
if s%2==1
  puts 'First'
else
  puts 'Second'
end


Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of games played. The second line contains a string s, consisting of n uppercase English letters 'A' and 'D' — the outcome of each of the games. The i-th character of the string is equal to 'A' if the Anton won the i-th game and 'D' if Danik won the i-th game.

If Anton won more games than Danik, print "Anton" (without quotes) in the only line of the output. If Danik won more games than Anton, print "Danik" (without quotes) in the only line of the output. If Anton and Danik won the same number of games, print "Friendship" (without quotes).

NoteIn the first sample, Anton won 6 games, while Danik — only 1. Hence, the answer is "Anton".In the second sample, Anton won 3 games and Danik won 4 games, so the answer is "Danik".In the third sample, both Anton and Danik won 3 games and the answer is "Friendship".

n = gets.chomp
word = gets.chomp

anton = word.count("A")
danik = word.count("D")

if anton > danik
    puts "Anton"
elsif anton < danik
    puts "Danik"
else
    puts "Friendship"
end

# Anton and Danik
# https://codeforces.com/problemset/problem/734/A
class ChessMatch
  def initialize(matches, result)
    @matches = matches
    @result = result
  end

  def winner
    wins_anton = @result.count('A')
    wins_danik = @matches - wins_anton

    if wins_anton > wins_danik
      'Anton'
    elsif wins_anton < wins_danik
      'Danik'
    else
      'Friendship'
    end
  end
end

# Test case
# 6
# ADAAAA
# Anton
matches = gets.to_i
ret = gets

match = ChessMatch.new(matches, ret)
puts match.winner

# input from user
def Get_Input
  number_game = gets.chomp
  str = gets.chomp
  return str
end

def check_char(str)
  anton=0
  danik=0
  #get count of char
  str.split('').each do |char|
    if char == 'A'
      anton +=1
    elsif char == 'D'
      danik +=1
    end
  end
# to check who's win
  if anton > danik
    puts 'Anton'
  elsif anton < danik
    puts 'Danik'
  elsif anton == danik
    puts 'Friendship'
  end
end

str = Get_Input()
check_char(str)

n = gets.chomp.to_i
chars = gets.chomp.chars

ans = chars.count('A') - chars.count('D')
if ans == 0
  puts "Friendship"
elsif ans > 0
  puts "Anton"
else
  puts "Danik"
end

#!/usr/bin/env ruby
gets
a = gets().chomp.split(//)
cnt = 0
a.map{|x| x == 'A'?  cnt += 1 : cnt -= 1}
puts cnt > 0 ? "Anton" : cnt == 0 ? "Friendship" : "Danik"

#!/usr/bin/env ruby
gets
a = gets().strip.split(//)
cnt = a.count("A") - a.count("D")
puts cnt > 0 ? "Anton" : cnt == 0 ? "Friendship" : "Danik"

#!/usr/bin/env ruby
gets
a = gets().chomp.split(//)
cnt = a.count("A") - a.count("D")
puts cnt > 0 ? "Anton" : cnt == 0 ? "Friendship" : "Danik"

x = gets.chomp.to_i
s = gets
a = 0
d = 0
while x >= 0
    if s[x]== 'A'
        a = a + 1
    elsif s[x]== 'D'
        d = d + 1
    end
    x = x - 1
end

if a > d
    puts "Anton"
elsif a < d
    puts "Danik"
else
    puts "Friendship"
end

num = gets.chomp.to_i
tabs = gets.chomp
A = tabs.count("A")
D = tabs.count("D")
if A > D
	puts "Anton"
elsif D > A
	puts "Danik"
else puts "Friendship"
end

total_play = gets.strip.to_i
play_string = gets.strip
play = play_string.split('')

anton_counter = 0
danik_counter = 0

0.upto(total_play - 1).each do |index|
  if play[index].eql?('A')
    anton_counter += 1
  else
    danik_counter += 1
  end
end

if anton_counter > danik_counter
  puts 'Anton'
elsif danik_counter > anton_counter
  puts 'Danik'
else
  puts 'Friendship'
end

n = gets.to_i
arr = gets.chomp.chars.to_a
d = a = 0
arr.each{|c|
  if c == 'D'
    d+=1
  else
    a+=1
  end
}
if a > d
  puts 'Anton'
elsif d > a
  puts 'Danik'
else
  puts 'Friendship'
end

n = gets.to_i
str = gets.strip
ac = str.count("A")
dc = str.count("D")

puts "Anton" if ac > dc
puts "Danik" if ac < dc
puts "Friendship" if ac == dc

class A

  def run
    n = $stdin.gets.to_i
    s = $stdin.gets
    a = d = 0
    n.times.each do |i|
      c = s[i]
      a += 1 if c == 'A'
      d += 1 if c == 'D'
    end
    puts 'Anton' if a > d
    puts 'Danik' if a < d
    puts 'Friendship' if a == d
  end

end

A.new.run

# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n = gi
s = gs

anton_won = s.count('A')
danik_won = n - anton_won

case
when anton_won > danik_won
    puts :Anton
when anton_won < danik_won
    puts :Danik
else
    puts :Friendship
end

# cook your code here
n = gets.to_i
result = gets
puts "Anton" if result.count("A") > result.count("D")
puts "Friendship" if result.count("A") == result.count("D")
puts "Danik" if result.count("D") > result.count("A")

gets.chomp
rounds = gets.chomp

anton = rounds.count 'A'
danik = rounds.count 'D'

puts "Anton" if anton > danik
puts "Danik" if danik > anton
puts "Friendship" if anton == danik

n = gets.to_i
games = gets.chomp
ac = games.count('A')
dc = n - ac
if ac == dc
  puts 'Friendship'
elsif ac > dc
  puts 'Anton'
else
  puts 'Danik'
end

n=gets.to_i
v=gets.chars.count{|e|
	e=="A"
}
ans=""

if n%2==0 then
	if n/2<v then
		ans="Anton"
	elsif n/2==v then
		ans="Friendship"
	else
		ans="Danik"
	end
else
	if n/2<v then
		ans="Anton"
	else
		ans="Danik"
	end
end
puts ans

gets
s = gets.chomp

puts %w(Danik Friendship Anton)[(s.count('A') <=> s.count('D')) + 1]

n = gets.chomp.to_i
arr = gets.chomp.split('')
# p arr
co = {'A'=>0,'D'=>0}

arr.each do |el|
  co[el] += 1
end

# p co
if co['A'] > co['D']
  puts "Anton"
elsif co['A'] < co['D']
  puts "Danik"
else
  puts "Friendship"
end

gets
s = gets.chomp
n = 0
s.each_char do |i|
	if i == 'A'
		n += 1
	else
		n -= 1
	end
end
if n == 0
	puts 'Friendship'
elsif n > 0
	puts 'Anton'
else
	puts 'Danik'
end

gets
s=gets.chomp
a=s.count ?A
d=s.count ?D
puts a<d ? "Danik" : a>d ? "Anton" : "Friendship"

a= gets.chomp.to_i
str = gets.chomp
str = str.split('')
if str.count("A") > str.count("D")
  puts "Anton"
elsif str.count("D") > str.count("A")
  puts "Danik"
else
  puts "Friendship"
end

n = gets.to_i
s = gets
a = s.count('A')
b = s.count('D')
puts a>b ? "Anton" : b>a ? "Danik" : "Friendship"

numResults = gets.chomp.to_i
results = gets.chomp

anton = 0
danik = 0

results.each_byte do |b|
	if b.chr == 'A'
		anton = anton + 1
	elsif b.chr == 'D'
		danik = danik + 1
	end
end

if anton == danik
	puts "Friendship"
elsif anton > danik
	puts "Anton"
else
	puts "Danik"
end

games = gets.chomp
w = gets.chomp
wins = w.split("")

count = 0
wins.each do |win|
	if win == "A"
		count += 1
	else
		count -= 1
	end
end

if count > 0
	print "Anton"
elsif count < 0
	print "Danik"
else
	print "Friendship"
end

#puts "Enter the number of game played\n"
n = gets.to_i
s = gets.to_s
a = d = 0
for i in 0...n do
    if s[i] == 'A'
        a += 1
    else
        d += 1
    end
end
if a > d
    puts "Anton\n"
elsif d > a
    puts "Danik\n"
else
    puts "Friendship\n"
end

int_value = gets.chomp
string_input = gets.chomp
string = string_input.split('')
anton = 0
danik = 0
string.each do |char|
  if char == 'A'
    anton += 1
  else
    danik += 1
  end
end
if anton == danik
  puts 'Friendship'
elsif anton > danik
  puts 'Anton'
else
  puts 'Danik'
end

gets
s = gets
puts s.count("A") > s.count("D") ? "Anton" : (s.count("A") < s.count("D") ? "Danik" : "Friendship")

#!/usr/bin/env ruby

gets
s = gets.strip
a = s.count('A')
b = s.count('D')

if a > b
  puts 'Anton'
elsif a < b
  puts 'Danik'
else
  puts 'Friendship'
end

gets
s = gets
puts (a = s.count("A")) > (d = s.count("D")) ? "Anton" : a == d ? "Friendship" : "Danik"

gets
s = gets
puts s.count("A") > s.count("D") ? "Anton" : s.count("A") == s.count("D") ? "Friendship" : "Danik"

n = gets
n = gets
a = n.count 'A'
d= n.count 'D'
if a > d
  puts "Anton"
elsif a < d
  puts "Danik"
else
  puts "Friendship"
end

n = gets
data = gets.chomp

an = data.chars.count { |c| c == 'A' }
dn = data.chars.count { |c| c == 'D' }

if an > dn
  puts 'Anton'
elsif an < dn
  puts 'Danik'
else
  puts 'Friendship'
end

n = gets.to_i
s = gets.strip
r = s.count('A') * 2
if r > n
  printf("Anton\n")
elsif r == n
  printf("Friendship\n")
else
  printf("Danik\n")
end

n = gets.chomp().to_i
s = gets.chomp().split('')
anton = s.select{|c| c if c=='A'}.length
danik = s.select{|c| c if c=='D'}.length
puts ( anton == danik ) ? "Friendship" : (anton > danik) ? "Anton" : "Danik"

require 'set'
parse_int = lambda{ gets.split.map{|el| el.to_i} }
sign = lambda {|el| (el>0?1:0)-(el<0?1:0)}

gets
n = gets
a,d = n.count('A'), n.count('D')

puts 'Anton' if a>d
puts 'Danik' if d>a
puts 'Friendship' if d==a

gets
a = gets().chomp.split(//)
print a.inspect
cnt = 0
a.map{|x| x == 'A'?  cnt += 1 : cnt -= 1}
puts cnt > 0 ? "Anton" : cnt == 0 ? "Friendship" : "Danik"

gets
a = gets().split(//)
cnt = 0
a.map{|x| x == 'A'?  cnt += 1 : cnt -= 1}
puts cnt > 0 ? "Anton" : (cnt == 0 ? "Friendship" : "Danik")

num = gets.chomp.to_i
tabs = gets.chomp
A_count = 0
D_count = 0
for i in 0...num
	puts "check"
	if tabs[i] == "A"
		A_count += 1
	else
		D_count += 1
	end
end
if A_count > D_count
	puts "Anton"
elsif D_count > A_count
	puts "Danik"
else puts "Friendship"
end

gets
s = gets.chomp
n = 0
s.each_char do |i|
	if i == 'A'
		n += 1
	else
		n -= 1
	end
end
if n == 0
	puts 'Friendship'
elsif n > 1
	puts 'Anton'
else
	puts 'Danik'
end

numResults = gets.to_i
results = gets

anton = 0
danik = 0

puts results.size

results.each_byte do |b|
	if b.chr == 'A'
		anton = anton + 1
	elsif b.chr == 'D'
		danik = danik + 1
	end
end

if anton == danik
	puts "Friendship"
elsif anton > danik
	puts "Anton"
else
	puts "Danik"
end

input = $stdin.readlines

numResults = input[0].to_i
results = input[1]

anton = 0
danik = 0

puts results.size

results.each_byte do |b|
	if b.chr == 'A'
		anton = anton + 1
	elsif b.chr == 'D'
		danik = danik + 1
	end
end

if anton == danik
	puts "Friendship"
elsif anton > danik
	puts "Anton"
else
	puts "Danik"
end

int_value = gets
string_input = gets
string = string_input.split('')
anton = 0
danik = 0
string.each do |char|
  if char == 'A'
    anton += 1
  else
    danik += 1
  end
end
if anton == danik
  puts 'Friendship'
elsif anton > danik
  puts 'Anton'
else
  puts 'Danik'
end

#gets
#s = gets
#puts (a = s.count("A")) > (d = s.count("D")) ? "Anton" : a == d ? "Friendship" : "Danik"

s=$<.read
p [:Friendship,:Anton,:Danik][s.count(?A)<=>s.count(?D)]

require 'set'
parse_int = lambda{ gets.split.map{|el| el.to_i} }
sign = lambda {|el| (el>0?1:0)-(el<0?1:0)}

gets
n = gets
a,d = n.count('A'), n.count('D')

puts 'Antin' if a>d
puts 'Danik' if d>a
puts 'Friendship' if d==a


You are given a tree that consists of $$$n$$$ nodes. You should label each of its $$$n-1$$$ edges with an integer in such way that satisfies the following conditions:   each integer must be greater than $$$0$$$;  the product of all $$$n-1$$$ numbers should be equal to $$$k$$$;  the number of $$$1$$$-s among all $$$n-1$$$ integers must be minimum possible. Let's define $$$f(u,v)$$$ as the sum of the numbers on the simple path from node $$$u$$$ to node $$$v$$$. Also, let $$$\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^n f(i,j)$$$ be a distribution index of the tree.Find the maximum possible distribution index you can get. Since answer can be too large, print it modulo $$$10^9 + 7$$$.In this problem, since the number $$$k$$$ can be large, the result of the prime factorization of $$$k$$$ is given instead.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines describes an edge: the $$$i$$$-th line contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — indices of vertices connected by the $$$i$$$-th edge. Next line contains a single integer $$$m$$$ ($$$1 \le m \le 6 \cdot 10^4$$$) — the number of prime factors of $$$k$$$. Next line contains $$$m$$$ prime numbers $$$p_1, p_2, \ldots, p_m$$$ ($$$2 \le p_i < 6 \cdot 10^4$$$) such that $$$k = p_1 \cdot p_2 \cdot \ldots \cdot p_m$$$. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$, the sum of $$$m$$$ over all test cases doesn't exceed $$$6 \cdot 10^4$$$, and the given edges for each test cases form a tree.

Print the maximum distribution index you can get. Since answer can be too large, print it modulo $$$10^9+7$$$.

MOD = 1000000007
def dfs2(ini,g)
  n = Array.new(g.length,-1)
  arr = []
  stack = [ini]
  n[ini] = 0
  while !stack.empty?
    v = stack[0]
    stack.shift
    cnt = 0
    g[v].each do |x|
      if n[x] == -1
        n[x] = 0
        cnt += 1
        stack.unshift(x)
      end
    end
    arr.unshift([v,cnt])
    if cnt == 0
      while !arr.empty?
        if arr[0][1] == 0
          n[arr[0][0]] += 1
          num = n[arr[0][0]]
          arr.shift
          if !arr.empty?
            arr[0][1] -= 1
            n[arr[0][0]] += num
          end
        else
          break
        end
      end
    end
  end
  n
end
t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  node = Array.new(n+1){Array.new}
  a = Array.new(n)
  b = Array.new(n)
  (n-1).times do |i|
    a[i],b[i] = gets.chomp.split(" ").map(&:to_i)
    node[a[i]].push(b[i])
    node[b[i]].push(a[i])
  end
  m = gets.to_i
  p = gets.chomp.split(" ").map(&:to_i)
  num = dfs2(1,node)
  arr = []
  (n-1).times do |i|
    d1 = [num[a[i]],num[b[i]]].min
    d2 = n - d1
    arr << d1 * d2
  end
  arr = arr.sort.reverse
  p = p.sort.reverse
  if m > n-1
    (m-n+1).times do |i|
      p[1] *= p[0]
      p[1] %= MOD
      p.shift
    end
  end
  sum = 0
  (n-1).times do |i|
    if m > i
      sum += (p[i] * (arr[i] % MOD)) % MOD
    else
      sum += arr[i] % MOD
    end
      sum %= MOD
  end
  ans << sum
end
ans.each do |x|
  puts x
end

MOD = 1000000007
def bfs(ini, g, b)
  dist = Array.new(g.length,-1)
  dist[b] = 0
  dist[ini] = 0
  queue = [ini]
  cnt = 0
  while !queue.empty?
    v = queue[0]
    queue.shift
    g[v].each do |des|
      if dist[des] == -1
        dist[des] = dist[v] + 1
        queue.push(des)
        cnt += 1
      end
    end
  end
  cnt
end
t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  node = Array.new(n+1){Array.new()}
  a = Array.new(n)
  b = Array.new(n)
  (n-1).times do |i|
    a[i],b[i] = gets.chomp.split(" ").map(&:to_i)
    node[a[i]].push(b[i])
    node[b[i]].push(a[i])
  end
  m = gets.to_i
  p = gets.chomp.split(" ").map(&:to_i)
  arr = []
  (n-1).times do |i|
    d1 = bfs(a[i],node,b[i])
    d2 = n-1 - 1 - d1
    arr << (d1+1) * (d2+1)
  end
  arr = arr.sort.reverse
  p = p.sort.reverse
  if m > n-1
    (m-n+1).times do |i|
      p[1] *= p[0]
      p[1] %= MOD
      p.shift
    end
  end
  sum = 0
  print arr
  puts ""
  print p
  puts ""
  (n-1).times do |i|
    if m > i
      sum += (p[i] * arr[i]) % MOD
    else
      sum += arr[i] % MOD
    end
      sum %= MOD
  end
  ans << sum
end
ans.each do |x|
  puts x
end

MOD = 1000000007
def bfs(ini, g, b)
  dist = Array.new(g.length,-1)
  dist[b] = 0
  dist[ini] = 0
  queue = [ini]
  cnt = 0
  while !queue.empty?
    v = queue[0]
    queue.shift
    g[v].each do |des|
      if dist[des] == -1
        dist[des] = dist[v] + 1
        queue.push(des)
        cnt += 1
      end
    end
  end
  cnt
end
t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  node = Array.new(n+1){Array.new()}
  a = Array.new(n)
  b = Array.new(n)
  (n-1).times do |i|
    a[i],b[i] = gets.chomp.split(" ").map(&:to_i)
    node[a[i]].push(b[i])
    node[b[i]].push(a[i])
  end
  m = gets.to_i
  p = gets.chomp.split(" ").map(&:to_i)
  arr = []
  (n-1).times do |i|
    d1 = bfs(a[i],node,b[i])
    d2 = n-1 - 1 - d1
    arr << (d1+1) * (d2+1)
  end
  arr = arr.sort.reverse
  p = p.sort.reverse
  sum = 0
  (n-1).times do |i|
    if m > i
      sum += (p[i] * arr[i]) % MOD
    else
      sum += arr[i] % MOD
    end
      sum %= MOD
  end
  ans << sum
end
ans.each do |x|
  puts x
end


Moamen has an array of $$$n$$$ distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once:  Split the array into exactly $$$k$$$ non-empty subarrays such that each element belongs to exactly one subarray.  Reorder these subarrays arbitrary.  Merge the subarrays in their new order. A sequence $$$a$$$ is a subarray of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le |a_i| \le 10^9$$$). It is guaranteed that all numbers are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test case, you should output a single string. If Moamen can sort the array in non-decreasing order, output "YES" (without quotes). Otherwise, output "NO" (without quotes). You can print each letter of "YES" and "NO" in any case (upper or lower).

NoteIn the first test case, $$$a = [6, 3, 4, 2, 1]$$$, and $$$k = 4$$$, so we can do the operations as follows:   Split $$$a$$$ into $$$\{ [6], [3, 4], [2], [1] \}$$$.  Reorder them: $$$\{ [1], [2], [3,4], [6] \}$$$.  Merge them: $$$[1, 2, 3, 4, 6]$$$, so now the array is sorted. In the second test case, there is no way to sort the array by splitting it into only $$$2$$$ subarrays.As an example, if we split it into $$$\{ [1, -4], [0, -2] \}$$$, we can reorder them into $$$\{ [1, -4], [0, -2] \}$$$ or $$$\{ [0, -2], [1, -4] \}$$$. However, after merging the subarrays, it is impossible to get a sorted array.

gets.to_i.times {
  n, k = gets.split.map(&:to_i)
  xs = gets.split.map(&:to_i)
  ys = (0...n).to_a.sort_by { xs[_1] }
  b = 1
  (1...n).each { |i|
    b += 1 if ys[i] - 1 != ys[i - 1]
  }
  puts(b <= k ? 'Yes' : 'No')
}

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

  prev = {}
  ys = xs.sort
  ys.each_with_index { |x, i|
    prev[x] = ys[i - 1] if i > 0
  }

  blocks = 1
  (1...n).each { |i|
    blocks += 1 if prev[xs[i]] != xs[i - 1]
  }

  puts(blocks <= k ? 'Yes' : 'No')
}

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i)
  sorted = as.sort.zip(0..).to_h
  puts as.chunk_while { |a, b| sorted[a] == sorted[b] - 1 }.count <= k ? "Yes" : "No"
end

#!/usr/bin/env ruby

tc = gets.to_i

def order(ar)
  sorted = ar.sort;
  hsh = sorted.zip(0..).to_h
  return ar.map{|x| hsh[x]}
end

def correct(ar)
  ar2 = ar.dup
  ar2.shift
  return ar.zip(ar2).map { |x| x[1] == x[0]+1 ? 1 : 0}.sum
end

for t in 1..tc
  n, k = gets.split.map { |x| x.to_i };
  ar =order(gets.split.map {|x| x.to_i});

#puts "#{ar}, #{n-correct(ar)}"
  puts "#{n-correct(ar) <= k ? 'Yes' : 'No'}"
end

t = gets.chomp.to_i
t.times do
    n, k = gets.chomp.split(" ").map(&:to_i)
    a = gets.chomp.split(" ").map(&:to_i)
    a_dup = a.dup
    a_dup = a_dup.sort
    hash = Hash.new(0)
    a_dup.each_with_index do |i,index|
        hash[i] = index
    end
    arr = []
    cnt = 0
    a.each do |i|
        if arr == []
            arr << i
        else
            if hash[arr[-1]] + 1 != hash[i]
                cnt += 1
            end
            arr << i
        end
    end
    if cnt + 1 <= k
        puts "Yes"
    else
        puts "No"
    end
end

END { load __FILE__ unless $stdin.eof? }

t = gets.to_i
t.times do
	n, k = gets.split.map!(&:to_i)
	a = gets.split.map!(&:to_i)

	h = a.sort.each_with_index.to_h
	a.map!(&h)

	c = a.each_cons(2).count { |x, y| x + 1 != y }
	puts (k >= c + 1) ? :Yes : :No
end

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i)
  puts as.chunk_while { |a, b| a < b }.count <= k ? "Yes" : "No"
end


Little penguin Polo adores integer segments, that is, pairs of integers [l; r] (l ≤ r). He has a set that consists of n integer segments: [l1; r1], [l2; r2], ..., [ln; rn]. We know that no two segments of this set intersect. In one move Polo can either widen any segment of the set 1 unit to the left or 1 unit to the right, that is transform [l; r] to either segment [l - 1; r], or to segment [l; r + 1].The value of a set of segments that consists of n segments [l1; r1], [l2; r2], ..., [ln; rn] is the number of integers x, such that there is integer j, for which the following inequality holds, lj ≤ x ≤ rj.Find the minimum number of moves needed to make the value of the set of Polo's segments divisible by k.

The first line contains two integers n and k (1 ≤ n, k ≤ 105). Each of the following n lines contain a segment as a pair of integers li and ri ( - 105 ≤ li ≤ ri ≤ 105), separated by a space. It is guaranteed that no two segments intersect. In other words, for any two integers i, j (1 ≤ i < j ≤ n) the following inequality holds, min(ri, rj) < max(li, lj).

In a single line print a single integer — the answer to the problem.

n,k=gets.split.map(&:to_i)
sum=0
n.times do
    a,b=gets.split.map(&:to_i)
    sum+=b-a+1
end
puts sum%k==0?0:k-sum%k

def run
  n, k = $stdin.readline.split.map(&:to_i)

  sum = 0
  $stdin.readlines.each do |line|
    l, r = line.split.map(&:to_i)
    sum += r - l + 1
  end

  puts (sum % k == 0) ? 0 : (k - sum % k)
end

run if $0 == __FILE__

class A
  def initialize
    n, k = $stdin.gets.chomp.split(' ').map(&:to_i)

    total = 0
    n.times do
      l, r = $stdin.gets.chomp.split(' ').map(&:to_i)
      count = r - l + 1
      total += count
    end

    if total%k == 0
      puts 0
    else
      puts k - (total%k)
    end
  end
end

a = A.new

a=gets.chomp.split(" ")
k=a[1].to_i
x=0
(a[0].to_i).times do
temp=gets.chomp.split(" ")
x+=temp[1].to_i-temp[0].to_i+1
end
puts "#{(k-(x%k))%k}"

n,k=gets.split.map(&:to_i)
s=0
n.times do
    l,r=gets.split.map(&:to_i)
    s+=r-l+1
end
puts (k-s%k)%k

n, k = gets.split(' ').map { |x| x.to_i }
t = 0
(1..n).each do |x|
 a,b = gets.split(' ').map { |x| x.to_i }
 t += (b-a).abs + 1
end
puts (k - t % k) % k

n, m = gets.split(' ').map!{ |i| i.to_i }

arr = Array.new
sum = 0
n.times {
	l, r = gets.split(' ').map!{ |i| i.to_i }
	arr << r - l + 1
	sum += arr[-1]
}

left = sum % m

ans = left == 0 ? 0 : m - left

p ans

n, k = gets.split.map(&:to_i)
lrs = n.times.map { gets.split.map(&:to_i) }
count = lrs.sort_by(&:first).map { |(a, b)| b - a + 1 }.reduce(:+)
if count % k == 0
  p 0
else
  p k - count % k
end

n,kp = gets.split(" ").collect {|x| x.to_i}
last = -1
rs = 0
ls = 0
s = 0
(0...n).each {|k|
	ls,rs = gets.split(" ").collect {|x| x.to_i}
	s+= (rs-ls+1)
}

puts (kp - s%kp)%kp

n, k = gets.split.collect{|i| i.to_i}
cnt = 0
(0...n).each do
    l, r = gets.split.collect{|i| i.to_i}
    cnt += r-l+1
end
if cnt%k == 0
    puts "0"
else
    puts k-cnt%k
end

n, k = gets.split(" ").collect{|x| x.to_i}

v = 0
c = 0
n.times do
  l, r = gets.split(" ").collect{|x| x.to_i}
  v += r - l + 1
end

rest = v % k
puts (k - rest) % k

def read_next_line
  gets.split.map { |x| x.to_i }
end

n, k = read_next_line
sum = 0
for _ in 1..n
  l, r = read_next_line
  sum += r - l + 1
end
rem = sum % k
puts(rem == 0 ? 0 : k - rem)

#!/usr/bin/env ruby

n, k = gets.split.collect{|i| i.to_i}
tot = 0
n.times do
	x, y = gets.split.collect{|i| i.to_i}
	tot = (tot + y - x + 1) % k
end

puts (tot == 0 ? 0 : k - tot)

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

segments = []
n.times do
  segments << gets.strip.split.map(&:to_i)[0..1]
end

value = segments.map{|x| x[1] - x[0] + 1}.inject :+
puts value % k == 0 ? 0 : ((value / k) + 1) * k - value

n, k = gets.split(' ').map { |x| x.to_i }
m = (0..10000).to_a
(1..n).each do |x|
 a,b = gets.split(' ').map { |x| x.to_i }
 (a..b).each { |i| m[i] = 1 }
end
t = 0
m.each {|x| if x == 1 then t = t+1 end}
s = 0
while (t % k != 0 )
  t = t + 1
  s = s + 1
end
puts s

n, k = gets.split(' ').map { |x| x.to_i }
t = 0
(1..n).each do |x|
 a,b = gets.split(' ').map { |x| x.to_i }
 t += b-a.abs + 1
end
if t <= k then puts k-t
else
  r = k
  while r <= t
    r += k
  end
  puts r - t
end

n, k = gets.split(' ').map { |x| x.to_i }
t = 0
(1..n).each do |x|
 a,b = gets.split(' ').map { |x| x.to_i }
 t += b-a.abs + 1
end
if t <= k then puts k-t
else
  r = k
  while r < t
    r += k
  end
  puts r - t
end

n, k = gets.split(' ').map { |x| x.to_i }
m = Array.new(20001)
(1..n).each do |x|
 a,b = gets.split(' ').map { |x| x.to_i }
 (a..b).each { |i| m[i+10000] = 1 }
end
t = 0
m.each {|x| if x == 1 then t = t+1 end}
if t <= k then puts k-t
else
  r = k
  while r <= t
    r = r + k
  end
  puts r-t
end

n, k = gets.split(' ').map { |x| x.to_i }
t = 0
(1..n).each do |x|
 a,b = gets.split(' ').map { |x| x.to_i }
 t += b-a.abs + 1
end
if t <= k then puts k-t
else
  puts k - (t % k)
end


n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.You have to write a program which prints the number of the child to be eliminated on every step.

The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1). The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).

Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step.

NoteLet's consider first example:   In the first step child 4 is eliminated, child 5 becomes the leader.  In the second step child 2 is eliminated, child 3 becomes the leader.  In the third step child 5 is eliminated, child 6 becomes the leader.  In the fourth step child 6 is eliminated, child 7 becomes the leader.  In the final step child 1 is eliminated, child 3 becomes the leader.

#!/usr/bin/env ruby

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

outs = []
childs = Array.new(n)
childs.each_with_index { |v, i| childs[i] = i + 1 }

cur = 0
ks.each do |k|
  k_i = (cur + (k % childs.size)) % childs.size
  outs << childs[k_i]
  childs.delete_at(k_i)
  cur = k_i % childs.size
end

puts outs.join(" ")

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

status = (1..n).to_a
leader = 0
a.each { |step|
    eliminate = (leader + step) % status.length
    print "#{status[eliminate]} "
    status = status.select.with_index { |v, i| i != eliminate }
    leader = eliminate
}
print "\n"

n,k=gets.split(" ").map(&:to_i)
a=gets.split(" ").map(&:to_i)
dt=(1..n).to_a

now=0

ans=[]

for i in (0...k)
	tmp=a[i]%dt.length
	now=(now+tmp)%dt.length
	ans<<dt.delete_at(now)
end
puts ans.join(" ")

parse_int = lambda{gets.split.map{|x| x.to_i}}

n, k = parse_int.call

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

lea, first = 0, true
for step in parse_int.call do
  lea = (lea + step) % children.length

  print ' ' unless first
  print children[lea]

  children.delete_at lea
  lea = 0 if lea >= children.length

  first = false
end


One day, Ahmed_Hossam went to Hemose and said "Let's solve a gym contest!". Hemose didn't want to do that, as he was playing Valorant, so he came up with a problem and told it to Ahmed to distract him. Sadly, Ahmed can't solve it... Could you help him?There is an Agent in Valorant, and he has $$$n$$$ weapons. The $$$i$$$-th weapon has a damage value $$$a_i$$$, and the Agent will face an enemy whose health value is $$$H$$$.The Agent will perform one or more moves until the enemy dies.In one move, he will choose a weapon and decrease the enemy's health by its damage value. The enemy will die when his health will become less than or equal to $$$0$$$. However, not everything is so easy: the Agent can't choose the same weapon for $$$2$$$ times in a row.What is the minimum number of times that the Agent will need to use the weapons to kill the enemy?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ $$$(1 \leq t \leq 10^5)$$$. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$H$$$ $$$(2 \leq n \leq 10^3, 1 \leq H \leq 10^9)$$$ — the number of available weapons and the initial health value of the enemy. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$ — the damage values of the weapons. It's guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum number of times that the Agent will have to use the weapons to kill the enemy.

NoteIn the first test case, the Agent can use the second weapon, making health value of the enemy equal to $$$4-7=-3$$$. $$$-3 \le 0$$$, so the enemy is dead, and using weapon $$$1$$$ time was enough.In the second test case, the Agent can use the first weapon first, and then the second one. After this, the health of enemy will drop to $$$6-4-2 = 0$$$, meaning he would be killed after using weapons $$$2$$$ times.In the third test case, the Agent can use the weapons in order (third, first, third), decreasing the health value of enemy to $$$11 - 7 - 2 - 7 = -5$$$ after using the weapons $$$3$$$ times. Note that we can't kill the enemy by using the third weapon twice, as even though $$$11-7-7<0$$$, it's not allowed to use the same weapon twice in a row.

def solve(target, arr)
  maxi = [0, 0]
  arr.each do |item|
    maxi[0] = item if item > maxi[0]
    maxi[0], maxi[1] = maxi[1], maxi[0] if maxi[0] > maxi[1]
  end

  ans = (target / (maxi.sum)) * 2
  target %= maxi.sum
  if target > 0
    ans += 1
    target -= maxi[1]
  end
  ans += 1 if target > 0
  ans
end

t = gets.chomp.to_i
t.times do
  _, h = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  print "#{solve(h, arr)}\n"
end

def solve(target, arr)
  maxi = [0, 0]
  arr.each do |item|
    maxi[0] = item if item > maxi[0]
    maxi[0], maxi[1] = maxi[1], maxi[0] if maxi[0] > maxi[1]
  end

  ans = (target / (maxi.sum)) * 2
  target %= maxi.sum
  ans += 1 if target > 0
  ans
end

t = gets.chomp.to_i
t.times do
  _, h = gets.chomp.split(' ').map(&:to_i)
  arr = gets.chomp.split(' ').map(&:to_i)
  print "#{solve(h, arr)}\n"
end


A sky scraper with 1000 floors has been built in the city of N. It has modern superfast elevators to help to travel from one floor to another. Each elevator has two doors, the front one and the back one. If one goes in through the front door, he goes out through the back one and vice versa. The elevator has two rails numbered with numbers 1 and 2. Rail 1 is located to the left of the entrance to the front door (or correspondingly, to the right of the entrance to the back door). Rail 2 is located opposite it, to the right of the entrance to the front door and to the left of the entrance to the back door. We know that each person in the city of N holds at a rail with the strongest hand. One day a VIP person visited the city and of course, he took a look at the skyscraper and took a ride in the elevator. We know the door through which he entered and the rail he was holding at. Now we need to determine as soon as possible whether he is left-handed or right-handed.

The first line indicates the door through which the very important person entered the elevator. It contains "front" if the person enters the elevator through the front door and "back" if he entered the elevator through the back door. The second line contains integer a (1 ≤ a ≤ 2) which denotes the number of the rail at which the person was holding.

Print character "R" if the VIP is right-handed or "L" if he is left-handed.

f = File.open('input.txt', 'r') or die "Unable to open file..."
input = []  # start with an empty array
  f.each_line {|line|
    input.push line
  }

door = input[0].chop
side = input[1].to_i
while door == 'front' or door == 'back'
 File.open('output.txt', 'w') do |o|
 o.puts "#{(door == 'front')? ((side == 1)? 'L' : 'R') : ((side == 2)? 'L' : 'R')}"
 end
exit
end

solve = {['front', '1'] => 'L', ['front', '2'] => 'R', ['back', '1'] => 'R', ['back', '2'] => 'L'}
File.open('input.txt', 'r') do |input|
	File.open('output.txt', 'w') do |output|
		output.puts solve[[input.gets.chomp, input.gets.chomp]]
	end
end

a, b = nil
File.open("input.txt") do |f|
  a = f.gets.strip
  b = f.gets.strip
end

if (a == 'front' && b == '1') || (a == 'back' && b == '2')
  lr = 'L'
else
  lr = 'R'
end

File.open("output.txt", "w") do |f|
  f.puts lr
end


Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet:  if the letter number is single-digit number (less than $$$10$$$), then just writes it out;  if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows:  'c' — is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3);  'o' — is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150);  'd' — is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504);  'e' — is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).

The first line of the input contains an integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. The descriptions of the test cases follow. The first line of description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of the given code. The second line of the description of each test case contains a string $$$t$$$ of length $$$n$$$ — the given code. It is guaranteed that there exists such a string of lowercase Latin letters, as a result of encoding which the string $$$t$$$ is obtained.

For each test case output the required string $$$s$$$ — the string that gives string $$$t$$$ as the result of encoding. It is guaranteed that such a string always exists. It can be shown that such a string is always unique.

code
aj
abacaba
ll
codeforces
aaaak
aaaaj
aaaaa
zf

NoteThe first test case is explained above.In the second test case, the answer is aj. Indeed, the number of the letter a is equal to $$$1$$$, so 1 will be appended to the code. The number of the letter j is $$$10$$$, so 100 will be appended to the code. The resulting code is 1100.There are no zeros in the third test case, which means that the numbers of all letters are less than $$$10$$$ and are encoded as one digit. The original string is abacaba.In the fourth test case, the string $$$s$$$ is equal to ll. The letter l has the number $$$12$$$ and is encoded as 120. So ll is indeed 120120.

c=Hash.new(nil);$stdin.each_line.with_index{|l, i|next if i==0||i%2==1;if c[l]!=nil;puts(c[l]);next;end;nt=0;o="";l.chomp.each_char.with_index {|x, i|if nt!=0;nt-=1;next;end;if (i<(l.chomp.length-2))&&(l[i + 2]=="0")&&(i>l.chomp.length-4||l[i + 3]!="0");nt=2;o+=("a".."z").to_a[(x+l[i+1]).to_i-1];next;end;o+=("a".."z").to_a[x.to_i-1]};c[l]=o;puts(o)}

c = Hash.new(nil)
$stdin.each_line.with_index do |l, i| next if i == 0 || i % 2 == 1
    if c[l] != nil
        puts c[l]
        next
    end
    nt = 0
    o = ""
    l.chomp.each_char.with_index do |x, i|
        if nt != 0
            nt -= 1
            next
        end
        if (i < (l.chomp.length - 2)) && (l[i + 2] == "0") && (i > l.chomp.length - 4 || l[i + 3] != "0")
            nt = 2
            o += ("a".."z").to_a[(x + l[i + 1]).to_i - 1]
            next
        end
        o += ("a".."z").to_a[x.to_i - 1]
    end
    c[l]=o
    puts o
end

def solve(n, s)
  alphabets = ['@', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

  ans = ''
  i = n-1
  while i >= 0 do
    if s[i] == '0'
      ans += alphabets[s[(i-2)..(i-1)].to_i]
      i -= 3
    else
      ans += alphabets[s[i].to_i]
      # p alphabets[s[i].to_i]
      i -= 1
    end
  end
  ans.reverse!
  puts ans
end

t = gets.chomp.to_i
for i in 1..t
  n = gets.chomp.to_i
  s = gets.chomp
  solve(n, s)
end

def debug(*arg)
  puts "[DEBUG] #{arg.join " "}"
end

t = gets.to_i

alpha = ('a'.upto 'z').to_a

t.times do
  n = gets.to_i
  s = gets.chomp.chars

  ans = []
  until s.empty?
    last = s.pop
    if last == '0'
      ans << alpha[s[-2..].join.to_i - 1]
      s.pop; s.pop
    else
      ans << alpha[last.to_i - 1]
    end

  end
  puts ans.reverse.join("")
end

$stdin.readline

cache = {}

while !$stdin.eof do
    $stdin.readline
    codestr = $stdin.readline.chomp

    if cache[codestr]
        puts cache[codestr]
        next
    end

    str = codestr.reverse.scan(/0[0-9][1-9]|[1-9]/).map { |code|
        code = code.reverse.to_i
        code = code < 10 ? code : code / 10
        ("a".."z").to_a[code - 1]
    }.join.reverse

    puts cache[codestr] = str
end

def ord_to_char(seq_ord)
  ('a'.ord+seq_ord-1).chr
end

def decode(encoded_str,len)
  # Search from the tail is better.
  ptr=len-1
  res_str=[]
  while ptr>=0
    if encoded_str[ptr]=='0'
      res_str << ord_to_char(encoded_str[ptr-2...ptr].to_i)
      ptr-=3
    else
      res_str << ord_to_char(encoded_str[ptr].to_i)
      ptr-=1
    end
  end
  res_str.reverse.join('')
end

n_rounds=gets.to_i

n_rounds.times do
  len=gets.to_i
  estr=gets
  puts decode(estr,len)
end

c = Hash.new(nil)
$stdin.each_line.with_index do |l, i| next if i == 0 || i % 2 == 1
    puts c[l] if c[l] != nil
    nt = 0
    o = ""
    l.chomp.each_char.with_index do |x, i|
        if nt != 0
            nt -= 1
            next
        end
        if (i < (l.chomp.length - 2)) && (l[i + 2] == "0") && (i > l.chomp.length - 4 || l[i + 3] != "0")
            nt = 2
            o += ("a".."z").to_a[(x + l[i + 1]).to_i - 1]
            next
        end
        o += ("a".."z").to_a[x.to_i - 1]
    end
    c[l]=o

    puts o
end

def solve(n, s)
  alphabets = ['@', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

  ans = ''
  i = n-1
  while i >= 0 do
    if s[i] == '0'
      ans += alphabets[s[(i-2)..(i-1)].to_i]
      i -= 3
    else
      ans += alphabets[s[i].to_i]
      # p alphabets[s[i].to_i]
      i -= 1
    end
  end
  ans.reverse!
  p ans
end

t = gets.chomp.to_i
for i in 1..t
  n = gets.chomp.to_i
  s = gets.chomp
  solve(n, s)
end

def solve(n, s)
  alphabets = ['@', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

  ans = ""
  i = n-1
  while i >= 0 do
    if s[i] == '0'
      ans += alphabets[s[(i-2)..(i-1)].to_i]
      i -= 3
    else
      ans += alphabets[s[i].to_i]
      # p alphabets[s[i].to_i]
      i -= 1
    end
  end
  ans.reverse!
  p ans
end

t = gets.chomp.to_i
for i in 1..t
  n = gets.chomp.to_i
  s = gets.chomp
  solve(n, s)
end

def debug(*arg)
  puts "[DEBUG] #{arg.join " "}"
end

t = gets.to_i

alpha = ('a'.upto 'z').to_a

p alpha

t.times do
  n = gets.to_i
  s = gets.chomp.chars

  ans = []
  until s.empty?
    last = s.pop
    if last == '0'
      ans << alpha[s[-2..].join.to_i - 1]
      s.pop; s.pop
    else
      ans << alpha[last.to_i - 1]
    end

  end
  puts ans.reverse.join("")
end


You have a statistic of price changes for one product represented as an array of $$$n$$$ positive integers $$$p_0, p_1, \dots, p_{n - 1}$$$, where $$$p_0$$$ is the initial price of the product and $$$p_i$$$ is how the price was increased during the $$$i$$$-th month.Using these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase $$$p_i$$$ to the price at the start of this month $$$(p_0 + p_1 + \dots + p_{i - 1})$$$.Your boss said you clearly that the inflation coefficients must not exceed $$$k$$$ %, so you decided to increase some values $$$p_i$$$ in such a way, that all $$$p_i$$$ remain integers and the inflation coefficients for each month don't exceed $$$k$$$ %.You know, that the bigger changes — the more obvious cheating. That's why you need to minimize the total sum of changes.What's the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 100$$$; $$$1 \le k \le 100$$$) — the length of array $$$p$$$ and coefficient $$$k$$$. The second line of each test case contains $$$n$$$ integers $$$p_0, p_1, \dots, p_{n - 1}$$$ ($$$1 \le p_i \le 10^9$$$) — the array $$$p$$$.

For each test case, print the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %.

NoteIn the first test case, you can, for example, increase $$$p_0$$$ by $$$50$$$ and $$$p_1$$$ by $$$49$$$ and get array $$$[20150, 50, 202, 202]$$$. Then you get the next inflation coefficients:   $$$\frac{50}{20150} \le \frac{1}{100}$$$;  $$$\frac{202}{20150 + 50} \le \frac{1}{100}$$$;  $$$\frac{202}{20200 + 202} \le \frac{1}{100}$$$; In the second test case, you don't need to modify array $$$p$$$, since the inflation coefficients are already good:   $$$\frac{1}{1} \le \frac{100}{100}$$$;  $$$\frac{1}{1 + 1} \le \frac{100}{100}$$$;

gets.to_i.times do
  n, k = gets.split.map(&:to_i)
  ps0, *ps = gets.split.map(&:to_i)
  nps = (ps0..10 ** 12).bsearch do |ps0|
    x = ps0
    ps.all? do |p|
      p.to_f / x <= k / 100.0 && (x += p)
    end
  end
  p nps - ps0
end

gets.to_i.times do
  n,k=gets.split.map(&:to_i)
  q=gets.split.map(&:to_i)
  c=0
  s=q[0]
  1.upto(n-1) do |i|
    if 100*q[i]-k*(s+c)>0
      c+=(100*q[i]-1)/k+1-s-c
    end
    s+=q[i]
  end
  puts c
end

def read
    gets.split.map &:to_i
end
gets.to_i.times do
    n, k = read
    a = read
    s, res = a[0], 0
    (1...n).each do |i|
        res = [res, (100 * a[i] - k * s + k - 1) / k].max
        s += a[i]
    end
    puts res
end

gets.to_i.times do
  n,k=gets.split.map(&:to_i)
  q=gets.split.map(&:to_i)
  c=0
  s=q[0]
  1.upto(n-1) do |i|
    if 100*q[i]-k*(s+c)>0
      c+=(100*q[i]-1)/k+1-s
    end
    s+=q[i]
  end
  puts c
end


Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he:   will buy exactly $$$n$$$ shovels in total;  the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then, $$$t$$$ test cases follow, one per line. Each test case consists of two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 10^9$$$) — the number of shovels and the number of types of packages.

Print $$$t$$$ answers to the test cases. Each answer is a positive integer — the minimum number of packages.

NoteThe answer to the first test case was explained in the statement.In the second test case, there is only one way to buy $$$8$$$ shovels — $$$8$$$ packages of one shovel.In the third test case, you need to buy a $$$1$$$ package of $$$6$$$ shovels.

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  ok = 1e9 + 1
  (1..sq).each { |el|
    if n.modulo(el).zero?
      an1 = 1e9 + 1
      an2 = 1e9 + 1
      an1 = n / el if el <= k
      an2 = el if n / el <= k
      next if an1 == 1e9 + 1 && an2 == 1e9 + 1
      ok = [ok, an1, an2].min
    end
  }
  puts ok
end

gets.strip.to_i.times do
  solve
end

t = gets.to_i
t.times do
  n, k = gets.split.map(&:to_i)
  ans = n
  if k >= n
    ans = 1
  else
    d = 1
    while d * d <= n do
      if n % d == 0
        if (n / d) <= k && d < ans
          ans = d
        end
        if d <= k && (n / d) < ans
          ans = (n / d)
        end
      end
      d += 1
    end
  end
  puts ans
end

require 'prime'

class Integer
	def divisors
		self.prime_division.inject([1]) do |a, (p, e)|
			(0..e).map { p**_1 }.product(a).map { _1 * _2 }
		end.sort
	end
end

gets.to_i.times do
	n, k = gets.split.map(&:to_i)
	puts n / n.divisors.select { _1 <= k }.max
end

gets.strip.to_i.times do |t|
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).ceil.to_i
  divs = [1, n]
  (2..sq).each do |i|
    if n % i == 0
      divs << i
      divs << n / i
    end
  end
  res = divs.sort.reverse.bsearch { |e| e <= k }
  puts n / res
end

require 'prime'

def divisors(n)
    res=[]
    (1..n**0.5).select{|i|n%i==0}.each{|i|
        res<<i
        res<<n/i if n/i!=i
    }
    res.sort
end

def divisors2(n)
    n.prime_division.inject([1]){|a, (p, e)|
        (0..e).map{|i| p**i}.product(a).map{|x, y| x*y}
    }.sort
end

gets.to_i.times {
    n, k=gets.split.map(&:to_i)
    puts n/divisors2(n).select{|e|e<=k}.max
}

def divisors(n)
    res=[]
    (1..n**0.5).select{|i|n%i==0}.each{|i|
        res<<i
        res<<n/i if n/i!=i
    }
    res.sort
end

gets.to_i.times {
    n, k=gets.split.map(&:to_i)
    puts n/divisors(n).select{|e|e<=k}.max
}

def divisors(n)
    res=[]
    (1..n**0.5).select{|i|n%i==0}.each{|i|
        res<<i
        res<<n/i if n/i!=i
    }
    res
#    res.sort
end

gets.to_i.times {
    n, k=gets.split.map(&:to_i)
    puts n/divisors(n).select{|e|e<=k}.max
}

# coding: utf-8

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

    if n <= k
        puts "1"
    else
        # 반드시 정확한 수량만큼 구입해야한다.
        # 오버해서 남은 삽을 버릴 수 있었다면 쉽게 풀었겠지?
        sqn = Math.sqrt(n).ceil
        m = 1
        max = 1
        r = [sqn, k].min
        for i in 2..r
            if n % i == 0
                m = i
                packs = n/m

                if max < m && m <= k
                    max = m
                end

                if max < packs && packs <= k
                    max = packs
                end
            end
        end

        puts "#{n/max}"
    end
}

# coding: utf-8

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

    if n <= k
        puts "1"
    else
        # 반드시 정확한 수량만큼 구입해야한다.
        # 오버해서 남은 삽을 버릴 수 있었다면 쉽게 풀었겠지?
        sqn = Math.sqrt(n).ceil
        m = 1
        packs = n
        r = [sqn, k].min
        for i in 0...(r-1)
            if n % (r-i) == 0
                m = r-i
                packs = n/m

                if m < packs && packs <= k
                    m, packs = packs, m
                end
                break
            end
        end

        puts "#{packs}"
    end
}

# coding: utf-8

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

    if n <= k
        puts "1"
    else
        # 반드시 정확한 수량만큼 구입해야한다.
        # 오버해서 남은 삽을 버릴 수 있었다면 쉽게 풀었겠지?
        # 1..k 개까지의 패키지를 구성할 수 있고, 이 안에서 여러번 반복해서 구입할 수 있다.
        # k 범위 내에서 가장 큰, n의 소인수를 찾아야한다.
        sqn = Math.sqrt(n).ceil
        m = 1
        for i in 2..([sqn, k].min)
            if n%i == 0
                m = i
                break
            end
        end

        puts "#{[n/m, m].min}"
    end
}

# coding: utf-8

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

    if n <= k
        puts "1"
    else
        # 반드시 정확한 수량만큼 구입해야한다.
        # 오버해서 남은 삽을 버릴 수 있었다면 쉽게 풀었겠지?
        sqn = Math.sqrt(n).ceil
        m = 1
        for i in 2..([sqn, k].min)
            if n%i == 0
                m = i
            end
        end

        if m == 1
            puts n
        else
            puts "#{[n/m, m].min}"
        end
    end
}

# coding: utf-8

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

    if n <= k
        puts "1"
    else
        # 반드시 정확한 수량만큼 구입해야한다.
        # 오버해서 남은 삽을 버릴 수 있었다면 쉽게 풀었겠지?
        sqn = Math.sqrt(n).ceil
        m = 1
        packs = n
        r = [sqn, k].min
        for i in 0...(r-1)
            if n % (r-i) == 0
                m = r-i
                packs = n/m

                if m < packs
                    m, packs = packs, m
                end
                break
            end
        end

        puts "#{packs}"
    end
}

# coding: utf-8

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

    if n <= k
        puts "1"
    else
        # 반드시 정확한 수량만큼 구입해야한다.
        # 오버해서 남은 삽을 버릴 수 있었다면 쉽게 풀었겠지?
        # 1..k 개까지의 패키지를 구성할 수 있고, 이 안에서 여러번 반복해서 구입할 수 있다.
        # k 범위 내에서 가장 큰, n의 소인수를 찾아야한다.
        sqn = Math.sqrt(n).ceil
        m = 1
        for i in 2..([sqn, k].min)
            if n%i == 0
                m = i
            end
        end

        puts "#{n/m}"
    end
}

# coding: utf-8

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

    if n <= k
        puts "1"
    else
        # 반드시 정확한 수량만큼 구입해야한다.
        # 오버해서 남은 삽을 버릴 수 있었다면 쉽게 풀었겠지?
        # 1..k 개까지의 패키지를 구성할 수 있고, 이 안에서 여러번 반복해서 구입할 수 있다.
        # k 범위 내에서 가장 큰, n의 소인수를 찾아야한다.
        sqn = Math.sqrt(n).ceil
        m = 1
        for i in 2..([sqn, k].min)
            if n%i == 0
                m = i
                break
            end
        end

        puts "#{n/m}"
    end
}

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  (1..sq).each { |el|
    if n.modulo(el).zero? && el <= k
      puts el
      return
    end
  }
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  an = 0
  (1..sq).each { |el|
    if n.modulo(n / el).zero? && n / el <= k
      an = el
    end
  }
  puts an
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  (1..sq).each { |el|
    if n.modulo(el).zero?
      an1 = 1e9 + 1
      an2 = 1e9 + 1
      an1 = n / el if el <= k
      an2 = el if n / el <= k
      next if an1 == 1e9 + 1 && an2 == 1e9 + 1
      puts [an1, an2].min
      return
    end
  }
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i + 1
  (1..sq).each { |el|
    if n.modulo(el).zero? && (n / el) <= k
      puts el
      return nil
    end
  }
  puts n
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  (1..sq).each { |el|
    if n.modulo(el).zero? && (n / el) <= k
      puts el
      return nil
    end
  }
  #puts "dasdasd"
  puts n
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i + 1
  an = 0
  (1..sq).each { |el|
    an = n / el if n.modulo(el).zero? && el <= k
    an = n / (n / el) if n.modulo(n / el).zero? && n / el <= k
  }
  puts an
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i + 1
  an = 0
  (1..sq).each { |el|
    if n.modulo(el).zero? && el <= k
      an = n / el
    end
  }
  puts an
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  an = 0
  (1..sq).each { |el|
    an = n / el if n.modulo(el).zero? && el <= k
    an = n / (n / el) if n.modulo(n / el).zero? && n / el <= k
  }
  puts an
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  ok = 0
  (1..sq).each { |el|
    if n.modulo(el).zero?
      an1 = 1e9 + 1
      an2 = 1e9 + 1
      an1 = n / el if el <= k
      an2 = el if n / el <= k
      next if an1 == 1e9 + 1 && an2 == 1e9 + 1
      ok = [an1, an2].min
    end
  }
  puts ok
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i + 1
  (1..sq).each { |el|
    if n.modulo(el).zero? && (n / el).to_f <= k
      puts el
      return nil
    end
  }
  puts n
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(k).to_i + 1
  (1..sq).each { |el|
    if n.modulo(el).zero?
      puts el
      return nil
    end
  }
  puts n
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i + 1
  (1..sq).each { |el|
    if n.modulo(el).zero? && (n / el) <= k
      puts el
      return nil
    end
  }
  #puts "dasdasd"
  puts n
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  (1..sq).each { |el|
    if (n % el).zero? && (n / el) <= k
      puts el
      return nil
    end
  }
  #puts "dasdasd"
  puts n
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  if n == k
    puts 1
    return nil
  end
  sq = Math.sqrt(n).to_i + 1
  an = 0
  (1..sq).each { |el|
    if n.modulo(el).zero? && el <= k
      an = n / el
    end
  }
  puts an
end

gets.strip.to_i.times do
  solve
end

def solve
  n, k = gets.strip.split(' ').map(&:to_i)
  sq = Math.sqrt(n).to_i
  (1..sq).each { |el|
    if n.modulo(n / el).zero? && n / el <= k
      puts el
      return;
    end
  }
end

gets.strip.to_i.times do
  solve
end


There are $$$n$$$ houses in a row. They are numbered from $$$1$$$ to $$$n$$$ in order from left to right. Initially you are in the house $$$1$$$.You have to perform $$$k$$$ moves to other house. In one move you go from your current house to some other house. You can't stay where you are (i.e., in each move the new house differs from the current house). If you go from the house $$$x$$$ to the house $$$y$$$, the total distance you walked increases by $$$|x-y|$$$ units of distance, where $$$|a|$$$ is the absolute value of $$$a$$$. It is possible to visit the same house multiple times (but you can't visit the same house in sequence).Your goal is to walk exactly $$$s$$$ units of distance in total.If it is impossible, print "NO". Otherwise print "YES" and any of the ways to do that. Remember that you should do exactly $$$k$$$ moves.

The first line of the input contains three integers $$$n$$$, $$$k$$$, $$$s$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le k \le 2 \cdot 10^5$$$, $$$1 \le s \le 10^{18}$$$) — the number of houses, the number of moves and the total distance you want to walk.

If you cannot perform $$$k$$$ moves with total walking distance equal to $$$s$$$, print "NO". Otherwise print "YES" on the first line and then print exactly $$$k$$$ integers $$$h_i$$$ ($$$1 \le h_i \le n$$$) on the second line, where $$$h_i$$$ is the house you visit on the $$$i$$$-th move. For each $$$j$$$ from $$$1$$$ to $$$k-1$$$ the following condition should be satisfied: $$$h_j \ne h_{j + 1}$$$. Also $$$h_1 \ne 1$$$ should be satisfied.

def solution
  n, k, s = read_ints

  if k > s
    puts "NO"
    return
  end

  if k * (n - 1) < s
    puts "NO"
    return
  end

  rs = s

  dir = 1
  crt = 1
  path = []

  k.times do |j|
    rk = k - j

    move = (rs.to_f / rk).ceil * dir
    dir *= -1
    rs -= move.abs

    crt = crt + move
    path << crt
  end

  puts "YES"
  puts path.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

N, K, s = gets.split.map(&:to_i)
if (N-1)*K < s || K > s
    puts 'NO'
    exit
end

ans = []
now = 1
s -= K
K.times do |i|
    add = [s, N-2].min
    s -= add
    now += (add+1) * (i%2==0 ? 1 : -1)
    ans.push(now)
end
puts 'YES'
puts ans.join(' ')

def solution
  n, k, s = read_ints

  if k > s
    puts "NO"
    return
  end

  if s.to_f / k > (n-1)
    puts "NO"
    return
  end

  crt = 1
  rs = s
  rk = k

  path = []

  while rs > 0
    steps_per_move = (rs.to_f / rk).ceil
    if crt < steps_per_move
      goto = crt + steps_per_move
    else
      goto = crt - steps_per_move
    end

    rs -= (goto-crt).abs
    rk -= 1

    path << goto
    crt = goto
  end

  puts 'YES'
  puts path.join(' ')

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']