Bizon the Champion isn't just attentive, he also is very hardworking.Bizon the Champion decided to paint his old fence his favorite color, orange. The fence is represented as n vertical planks, put in a row. Adjacent planks have no gap between them. The planks are numbered from the left to the right starting from one, the i-th plank has the width of 1 meter and the height of ai meters.Bizon the Champion bought a brush in the shop, the brush's width is 1 meter. He can make vertical and horizontal strokes with the brush. During a stroke the brush's full surface must touch the fence at all the time (see the samples for the better understanding). What minimum number of strokes should Bizon the Champion do to fully paint the fence? Note that you are allowed to paint the same area of the fence multiple times.

The first line contains integer n (1 ≤ n ≤ 5000) — the number of fence planks. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a single integer — the minimum number of strokes needed to paint the whole fence.

NoteIn the first sample you need to paint the fence in three strokes with the brush: the first stroke goes on height 1 horizontally along all the planks. The second stroke goes on height 2 horizontally and paints the first and second planks and the third stroke (it can be horizontal and vertical) finishes painting the fourth plank.In the second sample you can paint the fence with two strokes, either two horizontal or two vertical strokes.In the third sample there is only one plank that can be painted using a single vertical stroke.

def b(l,r,v=1)
	if l==r
		$t[v]=l
		return 0
	end
	return 0 if l>r
	m=(l+r)/2
	b(l,m,v*2)
	b(m+1,r,v*2+1)
	if $a[$t[v*2]]<$a[$t[v*2+1]]
		$t[v]=$t[v*2]
	else
		$t[v]=$t[v*2+1]
	end
end
def g(l,r,tl=0,tr=$n-1,v=1)
	return $n if tl>r || tr<l
	return $t[v] if tl>=l && tr<=r
	m=(tl+tr)/2
	a=g(l,r,tl,m,v*2)
	b=g(l,r,m+1,tr,v*2+1)
	return ($a[a]<$a[b]) ? a : b
end
def z(l,r,h)
	return 0 if l>r
	m=g(l,r)
	return [r-l+1,z(l,m-1,$a[m])+z(m+1,r,$a[m])+$a[m]-h].min
end
n=gets.to_i
$n=2
while $n<n
	$n*=2
end
$t=[0]*$n*4
$a=gets.split.map(&:to_i)+[1e18]*$n*4
b(0,$n-1)
p z(0,n-1,0)

class Array
	attr_accessor :seg_tree
	Info = Struct.new(:left, :right, :min, :index)

	def create_seg(left = 0, right = size - 1, n = 1)
		@seg_tree = [] if @seg_tree == nil

		if right == left
			@seg_tree[n] = Info.new(left, left, slice(left), left)
		else
			mid = (left + right) / 2
			min = [create_seg(left, mid, 2*n), create_seg(mid + 1, right, 2*n+1)].min{|x, y| x.min <=> y.min}
			@seg_tree[n] = Info.new(left, right, min.min, min.index)
		end

		@seg_tree[n]
	end

	def seg_min(l, r, n = 1)
		mid = (@seg_tree[n].left + @seg_tree[n].right) / 2

		if l <= @seg_tree[n].left and @seg_tree[n].right <= r
			@seg_tree[n]
		elsif mid >= r
			seg_min(l, r, n*2)
		elsif mid < l
			seg_min(l, r, n*2 + 1)
		else
			[seg_min(l, r, n*2), seg_min(l, r, n*2 + 1)].min{|x, y| x.min <=> y.min}
		end
	end
end

n = gets.chomp.to_i
a = gets.chomp.split.map{|i| i.to_i}
a.create_seg
# puts a.seg_tree
# puts a.seg_min(1, 2)

def sol(arr, l, r, base)
	# print arr
	return 0 if r == l && base == arr[r]
	return r - l + 1 if r - l + 1 <= 1
	m = arr.seg_min(l, r).min
	mid = arr.seg_min(l, r).index
	ans = [r - l + 1, sol(arr, l, mid - 1, m) + sol(arr, mid + 1, r, m) + (m - base)].min
	# puts "r - l + 1 = #{r - l + 1}, sol(arr, #{l}, #{mid - 1}, #{m}) = #{sol(arr, l, mid - 1, m)}, sol(arr, #{mid + 1}, #{r}, #{m}) = #{sol(arr, mid + 1, r, m)}"
	# puts "in (#{l}, #{r}), min = #{m}, base = #{base}, ans = #{ans}"
	ans
end

puts sol(a, 0, a.size - 1, 0)

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

def split0(arr)
	slice = []
	ans = []
	arr.each do |i|
		if i == 0 && (not slice.empty?)
			ans << slice
			slice = []
		elsif i != 0
			slice << i
		end
	end
	if (not slice.empty?)
		ans << slice
	end
	ans
end

def sol(arr)
	return arr.size if arr.size <= 1
	narr = arr.map{|i| i - arr.min}

	return [arr.size, split0(narr).map{|i| sol i}.inject(0, :+) + 1].min
end

puts sol(a)

class Array
	attr_accessor :seg_tree
	Info = Struct.new(:left, :right, :min, :index)

	def create_seg(left = 0, right = size - 1, n = 1)
		@seg_tree = [] if @seg_tree == nil

		if right == left
			@seg_tree[n] = Info.new(left, left, slice(left), left)
		else
			mid = (left + right) / 2
			min = [create_seg(left, mid, 2*n), create_seg(mid + 1, right, 2*n+1)].min{|x, y| x.min <=> y.min}
			@seg_tree[n] = Info.new(left, right, min.min, min.index)
		end

		@seg_tree[n]
	end

	def seg_min(l, r, n = 1)
		mid = (@seg_tree[n].left + @seg_tree[n].right) / 2

		if l <= @seg_tree[n].left && r >= @seg_tree[n].right
			@seg_tree[n]
		elsif mid >= r
			seg_min(l, r, n*2)
		elsif mid <= l
			seg_min(l, r, n*2 + 1)
		else
			[seg_min(l, r, n*2), seg_min(l, r, n*2 + 1)].min{|x, y| x.min <=> y.min}
		end
	end
end

n = gets.chomp.to_i
a = gets.chomp.split.map{|i| i.to_i}
a.create_seg

def sol(arr, l, r, base)
	# print arr
	return 0 if r == l && base == arr[r]
	return r - l + 1 if r - l + 1 <= 1
	m = arr.seg_min(l, r).min
	mid = arr.seg_min(l, r).index
	return [r - l + 1, sol(arr, l, mid - 1, m) + sol(arr, mid + 1, r, m) + (m - base)].min
end

puts sol(a, 0, a.size - 1, 0)


There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any betting decisions, he/she may only do so if all other players have a status of either "ALLIN" or "FOLDED". The player's own status may be either "ALLIN" or "IN".Find the number of cows that can currently show their hands without affecting any betting decisions.

The first line contains a single integer, n (2 ≤ n ≤ 2·105). The second line contains n characters, each either "A", "I", or "F". The i-th character is "A" if the i-th player's status is "ALLIN", "I" if the i-th player's status is "IN", or "F" if the i-th player's status is "FOLDED".

The first line should contain a single integer denoting the number of players that can currently show their hands.

NoteIn the first sample, cows 1, 4, 5, and 6 can show their hands. In the second sample, only cow 3 can show her hand.

n=gets
text= gets
I=text.scan('I').length
F=text.scan('F').length
A=text.scan('A').length

if I>1
  puts "0"
elsif I==1
  puts "1"
else
  puts A.to_s
end

n = gets.to_i
s = gets.strip

ac = 0
ic = 0

for i in 0...n
  if s[i] == 'A' then ac += 1 end
  if s[i] == 'I' then ic += 1 end
end

if ic > 1 then puts 0
elsif ic == 1 then puts 1
else puts ac end

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
s = STDIN.readline.strip.downcase

counts = {'a' => 0, 'i' => 0, 'f' => 0}

n.times do |i|
	counts[s[i]] += 1
end

if counts['i'] > 1
	answer = 0
elsif counts['i'] == 1
	answer = 1
else
	answer = counts['a']
end

puts answer

n=gets.to_i
s=gets.chomp
i=s.count(?I)
p i>1 ? 0 : i>0 ? 1 : n-s.count(?F)

n = gets.to_i
s = gets.chomp
players = s.count('I')

if players == 1
  puts "1"
else
  if players == 0
    puts s.count('A')
  else
    puts "0"
  end
end

gets;a=gets;a.count('I')==1 ?(puts 1):(a.count('I')==0 ?(puts a.count('A')):(puts 0))

n = gets.to_i
s = gets.chomp

l = s.size
a = 0
i = 0
f = 0
(0...l).each { |p|
   if s[p].downcase == "a"
      a+=1
   end
   if s[p].downcase == "f"
      f+=1
   end
   if s[p].downcase == "i"
      i+=1
   end

}

if i == 0
 puts a
end

if i == 1
 puts 1
end

if i > 1
 puts 0
end

n = gets.to_i
s = gets

a = i = 0
n.times do |idx|
  if s[idx] == "A"
    a += 1
  elsif s[idx] == "I"
    i += 1
  end
end

if i > 1
  puts 0
elsif i == 0
  puts a
else
  puts 1
end

gets # Skip the first line
s = gets.chomp
players_in = s.count('I')
puts(players_in == 1 ? 1 : players_in == 0 ? s.count('A') : 0)

n = gets; a = gets
a.count('I')==1? (puts 1) : (a.count('I')==0? (puts a.count('A') ):(puts 0))

#!/usr/bin/ruby1.9

n = STDIN.readline.to_i
s = STDIN.readline.strip.downcase

counts = {'a' => 0, 'i' => 0, 'f' => 0}

n.times do |i|
	counts[s[i]] += 1
end

if counts['i'] == 1
	answer = 1
else
	answer = counts['a']
end

puts answer

n=gets.to_i
s=gets.chomp
p s.count(?I)>1 ? 0 : n-s.count(?F)


Petya loves football very much, especially when his parents aren't home. Each morning he comes to the yard, gathers his friends and they play all day. From time to time they have a break to have some food or do some chores (for example, water the flowers).The key in football is to divide into teams fairly before the game begins. There are n boys playing football in the yard (including Petya), each boy's football playing skill is expressed with a non-negative characteristic ai (the larger it is, the better the boy plays). Let's denote the number of players in the first team as x, the number of players in the second team as y, the individual numbers of boys who play for the first team as pi and the individual numbers of boys who play for the second team as qi. Division n boys into two teams is considered fair if three conditions are fulfilled:  Each boy plays for exactly one team (x + y = n).  The sizes of teams differ in no more than one (|x - y| ≤ 1).  The total football playing skills for two teams differ in no more than by the value of skill the best player in the yard has. More formally: Your task is to help guys divide into two teams fairly. It is guaranteed that a fair division into two teams always exists.

The first line contains the only integer n (2 ≤ n ≤ 105) which represents the number of guys in the yard. The next line contains n positive space-separated integers, ai (1 ≤ ai ≤ 104), the i-th number represents the i-th boy's playing skills.

On the first line print an integer x — the number of boys playing for the first team. On the second line print x integers — the individual numbers of boys playing for the first team. On the third line print an integer y — the number of boys playing for the second team, on the fourth line print y integers — the individual numbers of boys playing for the second team. Don't forget that you should fulfil all three conditions: x + y = n, |x - y| ≤ 1, and the condition that limits the total skills. If there are multiple ways to solve the problem, print any of them. The boys are numbered starting from one in the order in which their skills are given in the input data. You are allowed to print individual numbers of boys who belong to the same team in any order.

NoteLet's consider the first sample test. There we send the first and the second boy to the first team and the third boy to the second team. Let's check all three conditions of a fair division. The first limitation is fulfilled (all boys play), the second limitation on the sizes of groups (|2 - 1| = 1 ≤ 1) is fulfilled, the third limitation on the difference in skills ((2 + 1) - (1) = 2 ≤ 2) is fulfilled.

n = gets.chomp.to_i
a = gets.chomp.split(/ /).map!{|x| x.to_i}
b = []
idx = 1
a.each{|aa|
  b << [aa, idx]
  idx += 1
}
b = b.sort{|b2,b1|
  b1[0] <=> b2[0]
}
c1 = []
c2 = []
c1s = 0
c2s = 0
b.each{|bb|
  if c1.length > c2.length
    c2 << bb[1]
    c2s += bb[0]
  elsif c2.length > c1.length
    c1 << bb[1]
    c1s += bb[0]
  else
    if c1s > c2s
      c2 << bb[1]
      c2s += bb[0]
    else
      c1 << bb[1]
      c1s += bb[0]
    end
  end
}
puts c1.length
puts c1.join(" ")
puts c2.length
puts c2.join(" ")

n = gets.to_i
a = gets.split.map(&:to_i).zip(1.upto(n)).sort.reverse
l, r, x, y = 0, 0, [], []

if n.odd?
    b = a.pop
    l += b[0]
    x << b[1]
end

(n / 2).times do
    b = a.pop
    c = a.pop
    b, c = c, b if l <= r
    l += b[0]
    x << b[1]
    r += c[0]
    y << c[1]
end

p x.size
puts x * ' '
p y.size
puts y * ' '

n=gets.chomp.to_i
players=[]
arr=gets.chomp.split
arr.each_index{|i| players.push [i+1,arr[i].to_i]}
players.sort_by!{|a| a[1]}
dif=0
i=2
s_i=0
l_i=players.size-1
a=[]
b=[]
while i <= n
 if dif >0
   a.push players[s_i][0]
   dif =dif+players[s_i][1]
   s_i=s_i+1
 else
   a.push players[l_i][0]
   dif =dif+players[l_i][1]
   l_i=l_i-1
 end
  if dif <0
   b.push players[s_i][0]
   dif =dif-players[s_i][1]
   s_i=s_i+1
 else
   dif =dif-players[l_i][1]
   b.push players[l_i][0]
   l_i=l_i-1
 end
i=i+2
end
if n%2!=0
 if dif >0
   b.push players[l_i][0]
 else
   a.push players[l_i][0]
 end
end
#p dif
puts a.size,a.to_s.delete('[').delete(']').gsub(",",""),b.size,b.to_s.delete('[').delete(']').gsub(",","")

n=gets.chomp.to_i
players=[]
arr=gets.chomp.split
arr.each_index{|i| players.push [i+1,arr[i].to_i]}
players.sort_by!{|a| a[1]}
dif=0
i=2
s_i=0
l_i=players.size-1
a=[]
b=[]
while i <= n
 if dif >0
   a.push players[s_i][0]
   dif =dif+players[s_i][1]
   s_i=s_i+1
 else
   a.push players[l_i][0]
   dif =dif+players[l_i][1]
   l_i=l_i-1
 end
  if dif <0
   b.push players[s_i][0]
   dif =dif+players[s_i][1]
   s_i=s_i+1
 else
   dif =dif+players[l_i][1]
   b.push players[l_i][0]
   l_i=l_i-1
 end
i=i+2
end
if n%2!=0
 if dif >0
   b.push players[l_i][0]
 else
   a.push players[l_i][0]
 end
end
puts a.size,a.to_s.delete('[').delete(']').gsub(",",""),b.size,b.to_s.delete('[').delete(']').gsub(",","")


Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation.We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on the rear wheel axle has bj (0 < b1 < b2 < ... < bm) teeth. Any pair (i, j) (1 ≤ i ≤ n; 1 ≤ j ≤ m) is called a gear and sets the indexes of stars to which the chain is currently attached. Gear (i, j) has a gear ratio, equal to the value .Since Vasya likes integers, he wants to find such gears (i, j), that their ratios are integers. On the other hand, Vasya likes fast driving, so among all "integer" gears (i, j) he wants to choose a gear with the maximum ratio. Help him to find the number of such gears.In the problem, fraction  denotes division in real numbers, that is, no rounding is performed.

The first input line contains integer n (1 ≤ n ≤ 50) — the number of stars on the bicycle's pedal axle. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 104) in the order of strict increasing. The third input line contains integer m (1 ≤ m ≤ 50) — the number of stars on the rear wheel axle. The fourth line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 104) in the order of strict increasing. It is guaranteed that there exists at least one gear (i, j), that its gear ratio is an integer. The numbers on the lines are separated by spaces.

Print the number of "integer" gears with the maximum ratio among all "integer" gears.

NoteIn the first sample the maximum "integer" gear ratio equals 3. There are two gears that have such gear ratio. For one of them a1 = 4, b1 = 12, and for the other a2 = 5, b3 = 15.

gets
a = gets.split.map &:to_i
gets
b = gets.split.map &:to_i

c = b.product(a).map{ |bi,aj| bi*1.0/aj }.select{ |i| i%1 == 0 }
puts c.count c.max

gets;a=gets.split.map &:to_i;gets;b=gets.split.map &:to_i;c=a.product(b).map{|x,y|y%x==0?(y/x):0};p c.count c.max

n = gets.to_i
gears1 = gets.split(' ').map{|x| x.to_i}
m = gets.to_i
gears2 = gets.split(' ').map{|x| x.to_i}

best = -1
count = 0

for i in gears1
        for j in gears2
                if j % i == 0 && j / i > best
                        best = j / i
                        count = 1
                elsif j % i == 0 && j / i == best
                        count += 1
                end
        end
end

print "#{count}\n"

n, a, m, b = readlines.map(&:chomp).map(&:split).map { |x| x.map!(&:to_i) }
s = a.product(b).map { |x| x[1]%x[0] == 0 ? x[1]/x[0] : nil }.compact
puts s.count { |x| x == s.max }

n = gets.to_i
a = gets.split.map! {|x| x.to_i }
m = gets.to_i
b = gets.split.map! {|x| x.to_i }
ans = []
for x in a do
    for y in b do
        ans << y / x if y % x == 0
    end
end
mx = -1
ans.each do |x|
    mx = x if x > mx
end
cnt = 0
ans.each do |x|
    cnt += 1 if x == mx
end
puts cnt

a=gets.chomp.to_i
b=gets.chomp.split(" ")
0.upto(a-1) {|i| b[i]=b[i].to_i}
c=gets.chomp.to_i
d=gets.chomp.split(" ")
0.upto(c-1) {|i| d[i]=d[i].to_i}

num=[]
d.each do |i|
b.each do |j|
if i%j==0
num << i/j
end
end
end
num.sort!
max=num[num.length-1]
ans=num.count(max)
puts "#{ans}"

gets
a=gets.split.map(&:to_i)
gets
b=gets.split.map(&:to_i)
c = []
a.each do |aa|
  b.each do |bb|
    c << bb / aa if bb % aa == 0
  end
end
p c.count c.max

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

n = gets.to_i
front = gets.split.map &:to_i
m = gets.to_i
back = gets.split.map &:to_i

max_value = 0
max_count = 0

for front_x in front do
  for back_x in back do
    next if back_x % front_x != 0
    next if back_x / front_x < max_value

    if back_x / front_x == max_value then
      max_count+=1
    else
      max_value = back_x / front_x
      max_count = 1
    end
  end
end

print max_count

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

n = gets.to_i
front = gets.split.map &:to_i
m = gets.to_i
back = gets.split.map &:to_i

hash = Hash.new( 0 )

for front_x in front do
  for back_x in back do
    next if back_x % front_x != 0

    hash[back_x / front_x]+=1
  end
end

print hash.to_a.max[1]

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

gets
front = gets.split.map &:to_i
gets
back = gets.split.map &:to_i

hash = Hash.new( 0 )

front.each{|v1|
  back.each{|v2|
    next if v2 % v1 != 0

    hash[v2 / v1]+=1
  }
}

print hash.to_a.max[1]

#!/usr/bin/ruby
n = gets.chomp.to_i
a = gets.chomp.split(' ').map{|x| x.to_i}
m = gets.chomp.to_i
b = gets.chomp.split(' ').map{|x| x.to_i}
maxrat = 0
ints = 0
for i in 0..n-1
	for j in 0..m-1
		if b[j]%a[i] == 0
			if b[j]/a[i] > maxrat
				ints = 1
				maxrat = b[j]/a[i]
			elsif b[j]/a[i] == maxrat
				ints +=1
			end
		end
	end
end
puts ints

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

values = []
b.each do |i|
  a.each do |j|
      values << i/j if i%j == 0
  end
end

values = values.sort_by{|el| -el}
puts values.count(values[0])

n = Integer(gets.chomp)
a = gets.chomp.split.map { |x| x.to_i }
m = Integer(gets.chomp)
b = gets.chomp.split.map { |x| x.to_i }

max = 0
for i in (m - 1).downto(0)
  for j in 0...n
    if b[i] % a[j] == 0
      r = b[i] / a[j]
      max = r if r > max
    end
  end
end

c = 0
for i in 0...m
  for j in 0...n
    c += 1 if b[i] % a[j] == 0 && b[i] / a[j] == max
  end
end
puts c

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

max = 0
count = 0

a.each do |ai|
  b.each do |bj|
    if bj % ai == 0
      r = bj / ai
      if r == max
        count += 1
      elsif r > max
        max = r
        count = 1
      end
    end
  end
end

p count

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

c = a.product(b).map!{|x,y| y%x == 0 ? y/x : 0}

p c.count(c.max)

n = gets.to_i
nn = []
nmas = gets.split
m = gets.to_i
mm = []
mmas = gets.split
i = 0
while i<n do
    nn << nmas[i].to_i
    i += 1
end
i = 0
while i<m do
    mm << mmas[i].to_i
    i += 1
end
result = 0
max = 0
i = 0
while i<n do
    j = 0
    while j<m do
        k = mm[j]/nn[i]
        if (mm[j] % nn[i] == 0) then
            if  k == max then result += 1
            elsif k > max then
                result = 1
                max = k
            end
        end
        j += 1
    end
    i += 1
end
print "#{result}\n"

n = Integer(gets.chomp)
a = gets.chomp.split.map { |x| x.to_i }
m = Integer(gets.chomp)
b = gets.chomp.split.map { |x| x.to_i }

max = 0
catch (:done) do
  for i in (m - 1).downto(0)
    for j in 0...n
      if b[i] % a[j] == 0
        max = b[i] / a[j]
        throw :done
      end
    end
  end
end

c = 0
for i in 0...m
  for j in 0...n
    c += 1 if b[i] % a[j] == 0 && b[i] / a[j] == max
  end
end
puts c


Polycarp has to solve exactly $$$n$$$ problems to improve his programming skill before an important programming competition. But this competition will be held very soon, most precisely, it will start in $$$k$$$ days. It means that Polycarp has exactly $$$k$$$ days for training!Polycarp doesn't want to procrastinate, so he wants to solve at least one problem during each of $$$k$$$ days. He also doesn't want to overwork, so if he solves $$$x$$$ problems during some day, he should solve no more than $$$2x$$$ problems during the next day. And, at last, he wants to improve his skill, so if he solves $$$x$$$ problems during some day, he should solve at least $$$x+1$$$ problem during the next day.More formally: let $$$[a_1, a_2, \dots, a_k]$$$ be the array of numbers of problems solved by Polycarp. The $$$i$$$-th element of this array is the number of problems Polycarp solves during the $$$i$$$-th day of his training. Then the following conditions must be satisfied:   sum of all $$$a_i$$$ for $$$i$$$ from $$$1$$$ to $$$k$$$ should be $$$n$$$;  $$$a_i$$$ should be greater than zero for each $$$i$$$ from $$$1$$$ to $$$k$$$;  the condition $$$a_i < a_{i + 1} \le 2 a_i$$$ should be satisfied for each $$$i$$$ from $$$1$$$ to $$$k-1$$$. Your problem is to find any array $$$a$$$ of length $$$k$$$ satisfying the conditions above or say that it is impossible to do it.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9, 1 \le k \le 10^5$$$) — the number of problems Polycarp wants to solve and the number of days Polycarp wants to train.

If it is impossible to find any array $$$a$$$ of length $$$k$$$ satisfying Polycarp's rules of training, print "NO" in the first line. Otherwise print "YES" in the first line, then print $$$k$$$ integers $$$a_1, a_2, \dots, a_k$$$ in the second line, where $$$a_i$$$ should be the number of problems Polycarp should solve during the $$$i$$$-th day. If there are multiple answers, you can print any.

n,k = gets.split.map(&:to_i)
ans = Array.new(k){|i|i+1}
n -= k*(k+1)/2
if n < 0
    puts "NO"
    exit
end
k.times do |i|
    ans[i] += n/k
end
n %= k
(k-1).downto(1) do |i|
    m = [ans[i-1]*2-ans[i],n].min
    m = [ans[i+1]-1,m].min if i+1 < k
    ans[i] += m
    n -= m
end
(k-1).times do |i|
    if ans[i]*2 < ans[i+1]
        puts "NO"
        exit
    end
end
if n > 0
    puts "NO"
    exit
end
puts "YES",ans.join(" ")

n,k = gets.split.map(&:to_i)
ans = Array.new(k){|i|i+1}
n -= k*(k+1)/2
if n < 0
    puts "NO"
    exit
end
k.times do |i|
    ans[i] += n/k
end
n %= k
(k-1).downto(1) do |i|
    m = [ans[i-1]*2-ans[i],n].min
    ans[i] += m
    n -= m
end
(k-1).times do |i|
    if ans[i]*2 < ans[i+1]
        puts "NO"
        exit
    end
end
if n > 0
    puts "NO"
    exit
end
puts "YES",ans.join(" ")


A binary string is a string that consists of characters $$$0$$$ and $$$1$$$. A bi-table is a table that has exactly two rows of equal length, each being a binary string.Let $$$\operatorname{MEX}$$$ of a bi-table be the smallest digit among $$$0$$$, $$$1$$$, or $$$2$$$ that does not occur in the bi-table. For example, $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 0011\\ 1010 \end{bmatrix}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ occur in the bi-table at least once. $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 111\\ 111 \end{bmatrix}$$$ is $$$0$$$, because $$$0$$$ and $$$2$$$ do not occur in the bi-table, and $$$0 < 2$$$.You are given a bi-table with $$$n$$$ columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table — the whole bi-table.What is the maximal sum of $$$\operatorname{MEX}$$$ of all resulting bi-tables can be?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of the description of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of columns in the bi-table. Each of the next two lines contains a binary string of length $$$n$$$ — the rows of the bi-table. It's guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the maximal sum of $$$\operatorname{MEX}$$$ of all bi-tables that it is possible to get by cutting the given bi-table optimally.

NoteIn the first test case you can cut the bi-table as follows:  $$$\begin{bmatrix} 0\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 10\\ 10 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 1\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$0$$$. $$$\begin{bmatrix} 0\\ 1 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$2$$$. $$$\begin{bmatrix} 0\\ 0 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$1$$$. $$$\begin{bmatrix} 0\\ 0 \end{bmatrix}$$$, its $$$\operatorname{MEX}$$$ is $$$1$$$.The sum of $$$\operatorname{MEX}$$$ is $$$8$$$.

t = gets.to_i
t.times do

n = gets.to_i
s1 = gets.chomp.chars.map!(&:to_i)
s2 = gets.chomp.chars.map!(&:to_i)

s = s1.zip(s2).map { |a, b| (a + b + 1) % 3 }
c = s.join.gsub(/01|10/, "2").chars.map!(&:to_i).sum

puts c

end


DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where Now DZY has a string s. He wants to insert k lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?

The first line contains a single string s (1 ≤ |s| ≤ 103). The second line contains a single integer k (0 ≤ k ≤ 103). The third line contains twenty-six integers from wa to wz. Each such number is non-negative and doesn't exceed 1000.

Print a single integer — the largest possible value of the resulting string DZY could get.

NoteIn the test sample DZY can obtain "abcbbc", value = 1·1 + 2·2 + 3·2 + 4·2 + 5·2 + 6·2 = 41.

s = gets.chomp
k = gets.to_i
arr = gets.split(" ").map(&:to_i)

ans = 0
s.each_char.with_index  do |c,i|
	weight = arr[c.ord - 97]
	ans += weight * (i +1)
end
sum = ((s.length+1)..(s.length+k)).inject(0,&:+)
ans +=  sum * arr.max
puts ans
#

str = gets.chomp
k = gets.to_i
azarr = gets.split(" ").collect { |e|  e.to_i}

az = []
str.each_char { |e|
    az << azarr[e.ord - 97]
}

max = [az.max, azarr.max].max

i = 1
len = str.length
#p len
sum = max*(k*(2*len+1+k))/2
#p sum
az.each { |e|
    sum += i*e
    i += 1
}
p sum

a = gets.chomp.split('').map { |c| c.ord - 97 }
k = gets.to_i
w = gets.chomp.split.map(&:to_i)
n = a.size + 1
puts a.each_with_index.map { |x, i| w[x] * (i + 1) }.inject(:+) + ((2 * n + k - 1) * k / 2) * w.max

a = gets.chomp.split('').map { |c| c.ord - 97 }
k = gets.to_i
w = gets.chomp.split.map(&:to_i)
puts a.each_with_index.map { |x, i| w[x] * (i + 1) }.inject(:+) + ((2 * a.size + k + 1) * k / 2) * w.max

s=gets.chomp
k=gets.to_i
w=gets.split.map &:to_i
l,t=s.size,0
l.times{|i| t+=(i+1)*w[s[i].ord-'a'.ord]}
t+=(k*l+k*(k+1)/2)*w.max
p t

s = gets.chomp
k = gets.to_i
w = gets.split.map {|i| i.to_i}
m = w.max
sum = 0
s.scan(/./).each_with_index {|i, x| sum += w[i.ord - 'a'.ord] * (x + 1)}
for i in 1..k
  sum += m * (i + s.length)
end
puts sum

#!/usr/bin/ruby
s=gets.chomp.bytes.map{|e|e-97}
n=gets.to_i
a=gets.split.map(&:to_i)
p (s.map{|e|a[e]}+[a.max]*n).each.with_index(1).reduce(0){|s,(e,i)|s+e*i}

s = gets
k = gets
vals = gets

k = k.to_i
vals = vals.split(" ")
vals = vals.map(&:to_i)

s = s.split(" ")
v1 = 0
i = 1

s[0].each_char do |c|
    v1+=(i*vals[c.ord-97])
    i+=1
end

vals = vals.sort.reverse

for j in 1..k
    v1 += (vals[0]*i)
    i+=1
end
i = 1

puts v1

s=gets.chomp.split('')
k=gets.to_i
a=gets.chomp.split.map(&:to_i)
m,ans,i=a.max,0,0
while i<s.length
	ans+=a[s[i].ord-97]*(i+1)
	i+=1
end
k.times do
	ans+=m*(i+1)
	i+=1
end
puts ans

s=gets
n=gets.to_i
a=gets.split.map{|i| i.to_i}+[0]*100
e=0
i=1
s.each_byte{|c| e+=a[c-'a'.ord]*i;i+=1}
p(e+a.max*(s.length*2+n-1)*n/2)

s=gets.chomp
k=gets.to_i
x=gets.chomp.split.map{|e| e.to_i}
y=x.max
i=0
h=Hash.new(0)
"a".upto("z"){|e|
	h[e]=x[i]
	i+=1
}
i=1
ans=0
s.chars{|e|
	ans+=h[e]*i
	i+=1
}
k.times{
	ans+=y*i
	i+=1
}
puts ans

s = gets.split('')
s.pop
k = gets.to_i
values_str = gets.split(' ')
values = Array.new(26) { Array.new(2) }
values_str.each_with_index do |val, i|
  values[i] = [i, val.to_i]
end

total = 0
s.each_with_index do |c, i|
  total += (i + 1) * values[c.ord - 'a'.ord][1]
end

values.sort! do |i, j|
  j[1] <=> i[1]
end

k.times do |i|
  total += (i + 1 + s.length) * values[0][1]
end

puts total

s = gets.strip
k = gets.to_i
weights = gets.split(" ").map(&:to_i)

alph = ["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"]
alph_weights = {}
alph.each_with_index { |letter, index| alph_weights[letter] = weights[index] }

max, max_index = weights.each_with_index.max

s << alph[max_index] * k

str_weight = 0
s.chars.each_with_index { |char, index|
  str_weight += alph_weights[char]*(index+1)
}

#puts s
puts str_weight

s = gets.chomp
k = gets.to_i
w = gets.split.map { |x| x.to_i }

ans = 0
s.each_char.with_index do |c, i|
	ans += w[c.ord - 97] * (i + 1)
end
ans += k * (s.length + 1 + s.length + k) / 2 * w.max

puts ans

#!/usr/bin/ruby
s=gets.chomp.bytes.map{|e|e-97}
n=gets.to_i
a=gets.split.map(&:to_i)
p (s.map{|e|a[e]}+[a.max]*3).sort.each.with_index(1).reduce(0){|s,(e,i)|s+e*i}

#!/usr/bin/ruby
s=gets.chomp.bytes.map{|e|e-97}
n=gets.to_i
a=gets.split.map(&:to_i)
p (s.map{|e|a[e]}+[a.max]*3).each.with_index(1).reduce(0){|s,(e,i)|s+e*i}

s = gets
k = gets
vals = gets

k = k.to_i
vals = vals.split(" ")
s = s.split(" ")
v1 = 0
i = 1

s[0].each_char do |c|
    v1+=(i*vals[c.ord-97].to_i)
    i+=1
end

vals = vals.sort.reverse

for j in 1..k
    v1 += (vals[0].to_i * i )
    i+=1
end

puts v1


You are given an array $$$a$$$ of $$$n$$$ integers, and another integer $$$k$$$ such that $$$2k \le n$$$.You have to perform exactly $$$k$$$ operations with this array. In one operation, you have to choose two elements of the array (let them be $$$a_i$$$ and $$$a_j$$$; they can be equal or different, but their positions in the array must not be the same), remove them from the array, and add $$$\lfloor \frac{a_i}{a_j} \rfloor$$$ to your score, where $$$\lfloor \frac{x}{y} \rfloor$$$ is the maximum integer not exceeding $$$\frac{x}{y}$$$.Initially, your score is $$$0$$$. After you perform exactly $$$k$$$ operations, you add all the remaining elements of the array to the score.Calculate the minimum possible score you can get.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$0 \le k \le \lfloor \frac{n}{2} \rfloor$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$).

Print one integer — the minimum possible score you can get.

NoteLet's consider the example test.In the first test case, one way to obtain a score of $$$2$$$ is the following one:  choose $$$a_7 = 1$$$ and $$$a_4 = 2$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{2} \rfloor = 0$$$, the array becomes $$$[1, 1, 1, 1, 3]$$$;  choose $$$a_1 = 1$$$ and $$$a_5 = 3$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{3} \rfloor = 0$$$, the array becomes $$$[1, 1, 1]$$$;  choose $$$a_1 = 1$$$ and $$$a_2 = 1$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{1} \rfloor = 1$$$, the array becomes $$$[1]$$$;  add the remaining element $$$1$$$ to the score, so the resulting score is $$$2$$$. In the second test case, no matter which operations you choose, the resulting score is $$$16$$$.In the third test case, one way to obtain a score of $$$0$$$ is the following one:  choose $$$a_1 = 1$$$ and $$$a_2 = 3$$$ for the operation; the score becomes $$$0 + \lfloor \frac{1}{3} \rfloor = 0$$$, the array becomes $$$[3, 7]$$$;  choose $$$a_1 = 3$$$ and $$$a_2 = 7$$$ for the operation; the score becomes $$$0 + \lfloor \frac{3}{7} \rfloor = 0$$$, the array becomes empty;  the array is empty, so the score doesn't change anymore. In the fourth test case, no operations can be performed, so the score is the sum of the elements of the array: $$$4 + 2 = 6$$$.

t = gets.to_i
ans = []
t.times do |i|
  n,k = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i).sort.reverse
  arr = []
  k.times do |i|
    arr << a[i]
  end
  k.times do |i|
    arr[i] = a[k+i] / arr[i]
  end
  (n-2*k).times do |i|
    arr << a[2*k+i]
  end
  ans << arr.sum
end
puts ans


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Let's call a pair of indices $$$i$$$, $$$j$$$ good if $$$1 \le i < j \le n$$$ and $$$\gcd(a_i, 2a_j) > 1$$$ (where $$$\gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$).Find the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of the test case contains a single integer $$$n$$$ ($$$2 \le n \le 2000$$$) — the number of elements in the array. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$.

For each test case, output a single integer — the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.

NoteIn the first example, the array elements can be rearranged as follows: $$$[6, 3, 5, 3]$$$.In the third example, the array elements can be rearranged as follows: $$$[4, 4, 2, 1, 1]$$$.

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map &:to_i
  a.sort! { |x, y|
    if x.even? && y.odd?
      -1
    elsif x.odd? && y.even?
      1
    else
      0
    end
  }
  ans = 0
  i = 0
  while i < n
    j = i + 1
    while j < n
      ans += 1 if a[i].gcd(2*a[j]) > 1
      j += 1
    end
    i += 1
  end
  puts ans
end


Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with the task.

The single line contains an integer n (1 ≤ n ≤ 106) — the sum of digits of the required lucky number.

Print on the single line the result — the minimum lucky number, whose sum of digits equals n. If such number does not exist, print -1.

#!/usr/bin/ruby

n = gets.to_i
seven = (n/7)
while true
	if (n-seven*7) % 4 == 0
		puts '4'*((n-seven*7)/4) << '7'*seven
		exit
	end
	seven -= 1
	if seven == -1
		puts -1
		exit
	end
end

n = gets.chop.to_i
a = 0
r = 0
vyslo = 0
(n-1).downto(0){ |b|
	#puts b
	a = (n-7*b)/4
	if 4*a + 7*b == n && a >= 0
		r = b
		vyslo = 1
		break
	end
}
if vyslo == 1
	for i in 0..a-1
		print "4"
	end
	for i in 0..r-1
		print "7"
	end
else
	print "-1"
end
print "\n"

def check
  count = 0
  val.each_char  { |s|
    if (s == '4' or s == '7')
      count += 1
    end
  }

  if (count == 4 or count == 7)
    return true
  else
    return false
  end
end

def succ(val, index)
  if index == -1
    return '4' + val
  end

  if (val[index] == '7')
    val[index] = '4'
    val = succ(val, index - 1)
  else
    val[index] = '7'
  end
  return val
end

def isucc(i)
  s = i.to_s
  return succ(s, s.length-1).to_i
end

def sum(i)
  h = Hash.new(0)
  h['4'] = 0
  h['7'] = 0
  i.each_char { |c|
    h[c] += 1
  }
  return h['4']*4 + h['7']*7
end

i = gets.chop.to_i

max4 = i / 4
max7 = i / 7
max4 += 1
max7 += 1

arr = Array.new(0)
res = "-1"
found = false
max7.downto(0) { |i7|
  #puts i7
  max4 = i - i7*7 + 7
  max4.downto(0) { |i4|
    if i == i7*7 + i4*4
      res = '4'*i4 + '7'*i7
      found = true
      break
    end
  }
  if found == true
    break
  end
}

puts res

#start = '4'
#100.times {
#  start = succ(start, start.length-1)
#  puts "#{start} sum = #{sum(start)}"
#}

inp = gets.to_i

a = 0
x = inp/7
found=false
res1=''
res2=''
while x >= 0 do
  a = inp - 7*x
  if a%4 == 0
    found = true
    break
  end
  x = x-1
end

res1 = res1.rjust(x,'7')
res2 = res2.rjust(a/4,'4')

if found
  puts res2+res1
else
  puts -1
end

i = STDIN.gets.to_i
  if (i % 7) == 0
    r = '7'*(i/7)
  else
    if i < 4
      r = '-1'
    else
      seven = i/7
      while seven > -1 && (i-seven*7) % 4 != 0
        seven -= 1
      end

      if seven == -1
        r = '-1'
      else
        r = "#{'4' * ((i - seven*7) / 4)}#{'7' * seven}\n"
      end
    end
  end
puts r

n = gets.to_i
s = n / 7
r = n - s * 7
while s > 0 and r % 4 != 0 do s -= 1; r = n - s * 7 end
if r % 4 != 0 or n < 4
  puts -1
else
  f = r / 4
  puts "4" * f + "7" * s
end

#!/usr/bin/env ruby

n = STDIN.gets.to_i

count = n/7
while  count > -1
  if (n-7*count) % 4 == 0
    puts [[4]*((n-7*count)/4),[7]*count].flatten.join
    exit
  end
  count -= 1
end
puts -1

def func(n)
    if (n == 0) then
        s = "-1"
    elsif (n % 7 == 0) then
        s = "7" * (n/7)
    elsif (n % 4 == 0) then
        s = "4"
        if n != 4 then
            n -= 4
            s += func(n)
        end
    else
        s = "-1"
    end
    return s
end

n = gets.to_i
if (s = func(n)) != "-1" then
    print "#{s}\n"
else
    r = 4
    s = "4"
    while r < n do
        if func(n-r) != "-1" then
            s += func(n-r)
            r = n
        elsif (r + 7) == n then
            r += 7
            s += "7"
        else
            r += 4
            s += "4"
        end
    end
    if r > n then s = "-1"
    end
    print "#{s}\n"
end

n = gets.to_i
# n = 7 * n7 + 4 * n4

n7 = n / 7
while n7 >= 0 do
  if (n - n7 * 7) % 4 == 0
    n4 = (n - n7 * 7) / 4
    break
  end
  n7 -= 1
end

if n7 >= 0
  puts (Array.new(n4) {4}).join + (Array.new(n7) {7}).join
else
  puts -1
end

sum = gets.chomp.to_i
div = 1
count = 0
while sum>=0
  if(sum%7==0 or sum == 0)
    puts ("4"*count + "7"*(sum/7)).split("").sort.join
    exit
  end
  sum-=4
  count+=1
end
puts -1

n = gets.to_i

s = n / 7
f = 0
while s * 7 + f * 4 != n and s >= 0 do
    f += 1
    if s * 7 + f * 4 > n then s -= 1 end
end

if s >= 0 then
    st = ''
    puts '4' * f + '7' * s
else
    puts -1
end

# def lucky(four,seven,n)
# 	if n == 0
# 		# puts "here"
# 		@fo = four
# 		@sev = seven
# 		return true
# 	end
# 	return false if n < 0
# 	if lucky(four,seven+1,n-7) || lucky(four+1,seven,n-4)
# 		return true
# 	else
# 		return false
# 	end
# end

# @fo = 0
# @sev = 0

# n = gets.to_i

# # puts lucky(0,0,n)
# if lucky(0,0,n)
# 	puts "4" * @fo + "7" * @sev
# else
# 	puts "-1"
# end

n = gets.to_i

b = 0
min_a = 10 ** 12
min_b = 10 ** 12
min_ab = 10 ** 12

a = 0
ans = false
# a * 4 + b * 7 = n
while a * 4 <= n
	b = (n - (a * 4))/7
	if (a * 4 + b * 7 == n) && ((a + b < min_ab) || (a + b == min_ab && b < min_b))
		min_a = a
		min_b = b
		min_ab = a + b
		ans = true
	end
	a += 1
end

if ans
	puts "4" * min_a + "7" * min_b
else
	puts "-1"
end

n = gets.to_i
m = -1
for i in 0..n/7
	m = i if ( n - 7 * i ) % 4 == 0
end
if m == -1
	puts -1
else
	n = ( n - 7 * m ) / 4
	n.times { print 4 }
	m.times { print 7 }
	puts
end

n = gets.to_i
cnt_7 = n/7
cnt_4 = (n-cnt_7*7)/4
while cnt_7 >= 0 and  cnt_7*7+cnt_4*4 != n
    cnt_7 -= 1
    cnt_4 = (n-cnt_7*7)/4
end
if cnt_7 >= 0 and  cnt_7*7+cnt_4*4 == n
    puts '4'*cnt_4+'7'*cnt_7
else
    puts -1
end

#!/usr/bin/ruby

n = gets.to_i
dp = Array.new(n+1, nil)
dp[0] = ''
1.upto(n) do |i|
    if i-4 >= 0 && dp[i-4]
        str = dp[i-4] + '4'
        if dp[i].nil?
            dp[i] = str
        else
            dp[i] = str if dp[i] > str
        end
    end

    if i-7 >= 0 && dp[i-7]
        str = dp[i-7] + '7'
        if dp[i].nil?
            dp[i] = str
        else
            dp[i] = str if dp[i] > str
        end
    end
end

puts dp[n] || -1

n = gets.chop.to_i
a = 0
b = 0
vyslo = 0
for b in 0..n-1
	a = (n-7*b)/4
	if 4*a + 7*b == n && a >= 0
		vyslo = 1
		break
	end
end
if vyslo == 1
	for i in 0..a-1
		print "4"
	end
	for i in 0..b-1
		print "7"
	end
else
	print "-1"
end
print "\n"

n = gets.chop.to_i
a = 0
b = 0
for b in 0..n-1
	a = (n-7*b)/4
	if 4*a + 7*b == n
		break

	end
end
puts "A" + a.to_s
puts "B" + b.to_s

n = gets.chop.to_i
a = 0
b = 0
for b in 0..n-1
	a = (n-7*b)/4
	if 4*a + 7*b == n
		break

	end
end
for i in 0..a-1
	print "4"
end
for i in 0..b-1
	print "7"
end
print "\n"

n = gets.chop.to_i
a = 0
b = 0
vyslo = 0;
for b in 0..n-1
	a = (n-7*b)/4
	if 4*a + 7*b == n
		vyslo = 1
		break
	end
end
if vyslo == 1
	for i in 0..a-1
		print "4"
	end
	for i in 0..b-1
		print "7"
	end
else
	print "-1"
end
print "\n"

def check
  count = 0
  val.each_char  { |s|
    if (s == '4' or s == '7')
      count += 1
    end
  }

  if (count == 4 or count == 7)
    return true
  else
    return false
  end
end

def succ(val, index)
  if index == -1
    return '4' + val
  end

  if (val[index] == '7')
    val[index] = '4'
    val = succ(val, index - 1)
  else
    val[index] = '7'
  end
  return val
end

def isucc(i)
  s = i.to_s
  return succ(s, s.length-1).to_i
end

def sum(i)
  h = Hash.new(0)
  h['4'] = 0
  h['7'] = 0
  i.each_char { |c|
    h[c] += 1
  }
  return h['4']*4 + h['7']*7
end

i = gets.chop.to_i
ii = i + 4 + 7 + 4
x = 4
fail = false

four_count = i / 4
start = '4' * four_count
#x = start.to_i

s = sum(start)
while s != i
  if (s > ii)
    fail = true
    break
  end

  start = succ(start, start.length-1)
  s = sum(start)
end

if (fail == false)
  puts start
else
  puts -1
end

i = STDIN.gets.to_i
  if (i % 4) == 0
    r = '4'*(i/4)
  else
    if i < 7
      r = '-1'
    else
      four = i/4
      while four > -1 && (i-four*4) % 7 != 0
        four -= 1
      end

      if four == -1
        r = '-1'
      else
        r = "#{'4' * four}#{'7' * ((i - four*4) / 7)}\n"
      end
    end
  end
puts r

#!/usr/bin/env ruby

n = STDIN.gets.to_i

count = 0
while  (7*count) < n
  if (n-7*count) % 4 == 0
    puts [[4]*((n-7*count)/4),[7]*count].flatten.join
    exit
  end
  count += 1
end
puts -1

def func(n)
    if (n == 0) then
        s = "-1"
    elsif (n % 7 == 0) then
        s = "7" * (n/7)
    elsif (n % 4 == 0) then
        s = "4" * (n/4)
    else
        s = "-1"
    end
    return s
end

n = gets.to_i
if (s = func(n)) != "-1" then
    print "#{s}\n"
else
    r = 4
    s = "4"
    while r < n do
        if func(n-r) != "-1" then
            s += func(n-r)
            r = n
        elsif (r + 7) == n then
            r += 7
            s += "7"
        else
            r += 4
            s += "4"
        end
    end
    if r > n then s = "-1"
    end
    print "#{s}\n"
end

def func(n)
    if (n == 0) then
        s = "-1"
    elsif (n % 7 == 0) then
        s = "7" * (n/7)
    elsif (n % 4 == 0) then
        s = "4"
        n -= 4
        s += func(n)
    else
        s = "-1"
    end
    return s
end

n = gets.to_i
if (s = func(n)) != "-1" then
    print "#{s}\n"
else
    r = 4
    s = "4"
    while r < n do
        if func(n-r) != "-1" then
            s += func(n-r)
            r = n
        elsif (r + 7) == n then
            r += 7
            s += "7"
        else
            r += 4
            s += "4"
        end
    end
    if r > n then s = "-1"
    end
    print "#{s}\n"
end

sum = gets.chomp.to_i
q4 = sum/4
div4 = sum%4
q7 = sum - q4*4
div7 = (sum - q4*4)%7

if(div7==0)
  num = "4"*q4 + "7"*q7
  num = num.split("").sort.join
  puts num
else
  puts -1
end

sum = gets.chomp.to_i
div = 1
count = 0
while sum>0
  sum-=4
  count+=1
  if(sum%7==0)
    puts ("4"*count + "7"*(sum/7)).split("").sort.join
    exit
  end
end
puts -1

sum = gets.chomp.to_i
q7 = sum/7
div7 = sum%7
q4 = (sum - q7*7)/4
div4 = (sum-q7*7)%4

if(div4==0)
  num = "4"*q4 + "7"*q7
  num = num.split("").sort.join
  puts num
else
  puts -1
end

require 'mathn'
sum = gets.chomp.to_i
q7 = (sum/7).floor
div7 = sum%7
q4 = ((sum - q7*7)/4).floor
div4 = (sum-q7*7)%4

if(div4==0)
  num = "4"*q4 + "7"*q7
  num = num.split("").sort.join
  puts num
else
  puts -1
end

# def lucky(four,seven,n)
# 	if n == 0
# 		# puts "here"
# 		@fo = four
# 		@sev = seven
# 		return true
# 	end
# 	return false if n < 0
# 	if lucky(four,seven+1,n-7) || lucky(four+1,seven,n-4)
# 		return true
# 	else
# 		return false
# 	end
# end

# @fo = 0
# @sev = 0

# n = gets.to_i

# # puts lucky(0,0,n)
# if lucky(0,0,n)
# 	puts "4" * @fo + "7" * @sev
# else
# 	puts "-1"
# end

n = gets.to_i

b = 0
min_a = 10 ** 5
min_b = 10 ** 5
min_ab = 10 ** 5

a = 0
ans = false
# a * 4 + b * 7 = n
while a * 4 <= n
	b = (n - (a * 4))/7
	if (a * 4 + b * 7 == n) && ((a + b < min_ab) || (a + b == min_ab && b < min_b))
		min_a = a
		min_b = b
		min_ab = a + b
		ans = true
	end
	a += 1
end

if ans
	puts "4" * min_a + "7" * min_b
else
	puts "-1"
end


$$$n$$$ students are taking an exam. The highest possible score at this exam is $$$m$$$. Let $$$a_{i}$$$ be the score of the $$$i$$$-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied:   All scores are integers  $$$0 \leq a_{i} \leq m$$$  The average score of the class doesn't change. You are student $$$1$$$ and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.

Each test contains multiple test cases.  The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 200$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^{3}$$$, $$$1 \leq m \leq 10^{5}$$$)  — the number of students and the highest possible score respectively. The second line of each testcase contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 0 \leq a_{i} \leq m$$$)  — scores of the students.

For each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._

NoteIn the first case, $$$a = [1,2,3,4] $$$, with average of $$$2.5$$$. You can change array $$$a$$$ to $$$[10,0,0,0]$$$. Average remains $$$2.5$$$, and all conditions are satisfied.In the second case, $$$0 \leq a_{i} \leq 5$$$. You can change $$$a$$$ to $$$[5,1,1,3]$$$. You cannot increase $$$a_{1}$$$ further as it will violate condition $$$0\le a_i\le m$$$.

t = gets.to_i
t.times do
  n,m = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  p [a.inject(:+), m].min
end

def read_input()

   rules = STDIN.gets()
   students = STDIN.gets()

   rules = rules.split(' ').map(&:to_i)
   students = students.split(' ').map(&:to_i)

   raise "Invalid rules input" if rules.size != 2
   raise "Invalid input" if students.size != rules[0]

   return rules, students

end

def do_some_magic(cnt)
    cnt.times {

        rules, students = read_input()

        oth_cnt = students.size - 1

        # we need this num of points
        x = rules[1] - students[0]

        # available this num of points
        y = 0
        1.upto(oth_cnt) { |s|
            y += students[s]
        }

        # and this num of points we can add to first student
        z = y < x ? y : x

        puts students[0] + z

    }
end

cnt = Integer(STDIN.gets())

do_some_magic(cnt)

#! /usr/bin/env ruby
# encoding: UTF-8

def solve
	n,m = gets.split.map{|x| x.to_i }
	xs = gets.split.map {|x| x.to_i }
	sum = xs.reduce(:+)
	puts([m, sum].min)
end

t = gets.to_i
t.times {solve}

T = gets.to_i

T.times do
  n, m = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)

  sum = a.inject(:+)

  puts [m, sum].min
end

def main
  t = gets.chomp.to_i
  t.times { solve }
end

def solve
  n, m = gets.chomp.split.map(&:to_i)
  a = gets.chomp.split.map(&:to_i)
  # S = gets.chomp.chars

  sum = 0
  0.upto(n-1).each do |i|
    sum += a[i]
  end
  a0 = [sum, m].min # min(sum, m) is a0
  p a0
end

main


You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.

The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.

Print exactly $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.

NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.

def single_input
	gets.chomp.to_i
end

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

n, m = multiple_input
names = multiple_input

rem = m
ac = []
n.times do |i|
	if names[i] < rem
		rem -= names[i]
		ac << 0
		next
	end

	if rem == names[i]
		rem = m
		ac << 1
		next
	end

	x = (names[i]-rem) / m
	rem = (names[i]-rem) % m
	rem = m - rem
	ac << (x + 1)
end

print ac.map(&:to_s).join(" ")

n,m,*a=$<.read.split.map &:to_i
s=q=0;r=[]
a.each{|e|s+=e;r<<s/m-q/m;q=s}
puts r*' '

def solve
  n, m = gets.strip.split.map(&:to_i)
  a = gets.strip.split.map(&:to_i)
  sum = 0
  pages = []
  a.each_with_index do |val, i|
    sum += val
    pages << (sum / m).to_i
    sum = sum % m if sum >= m
  end
  puts pages.join(' ')
end

solve

N, M = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
sum = 0
ans = []
N.times do |i|
    ans[i] = (sum+as[i])/M - sum/M
    sum += as[i]
end
puts ans.join(' ')

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

ans = Array.new(n, 0)
cu=m
0.upto(n-1).each do |i|
  ai = ais[i]
  if ai<cu
    cu-=ai
  elsif ai==cu
    cu=m
    ans[i]+=1
  else # ai>cu
    rai = ai-cu
    ans[i]+=1
    ans[i]+= (rai/m)
    cu = m - (rai%m)
    cu = m if cu==0
  end
end

puts ans.join(' ')

def single_input
	gets.chomp.to_i
end

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

n, m = multiple_input
names = multiple_input

rem = m
ac = []
n.times do |i|
	if names[i] < rem
		rem -= names[i]
		ac << 0
		next
	end

	if rem == names[i]
		rem = 0
		ac << 1
		next
	end

	x = (names[i]-rem) / m
	rem = (names[i]-rem) % m
	rem = m - rem
	ac << (x + 1)
end

print ac.map(&:to_s).join(" ")

def single_input
	gets.chomp.to_i
end

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

n, m = multiple_input
names = multiple_input

rem = m
ac = []
n.times do |i|
	if names[i] < rem
		rem -= names[i]
		ac << 0
		next
	end

	if rem == names[i]
		rem = 0
		ac << 1
		next
	end

	x = (names[i]-rem) / m
	rem = (names[i]-rem) % m
	rem = m - rem
	ac << (x + 1)
end

p ac.map(&:to_s).join(" ")


Cowboy Vlad has a birthday today! There are $$$n$$$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from $$$1$$$ to $$$n$$$ in a circle order, that is, for every $$$i$$$ child with number $$$i$$$ will stand next to the child with number $$$i+1$$$, also the child with number $$$1$$$ stands next to the child with number $$$n$$$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of the children who came to the cowboy Vlad's birthday. The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) denoting heights of every child.

Print exactly $$$n$$$ integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child. If there are multiple possible answers, print any of them.

NoteIn the first example, the discomfort of the circle is equal to $$$1$$$, since the corresponding absolute differences are $$$1$$$, $$$1$$$, $$$1$$$ and $$$0$$$. Note, that sequences $$$[2, 3, 2, 1, 1]$$$ and $$$[3, 2, 1, 1, 2]$$$ form the same circles and differ only by the selection of the starting point.In the second example, the discomfort of the circle is equal to $$$20$$$, since the absolute difference of $$$10$$$ and $$$30$$$ is equal to $$$20$$$.

n = gets.to_i
a = gets.split.map(&:to_i).sort
ans = []
c = 0
a.each do |v|
  if c % 2 == 0
    ans.push(v)
  else
    ans.unshift(v)
  end
  c += 1
end
puts ans.join(" ")

DBG = true
n = gets.to_i
a = gets.split.map{|z| z.to_i}
a.sort!
m = n/2
b = Array.new(n)
for i in 0...m
  b[i] = a[2*i]
  b[n-1-i] = a[2*i+1]
end
if n%2 == 1
  b[m] = a[n-1]
end
for i in 0...n
  print "#{b[i]} "
end
puts ""

N = gets.to_i
X = gets.split.map(&:to_i).sort

o = X.each_with_index.select{|e,i| i.odd?}.map(&:shift)
o += X.each_with_index.select{|e,i| i.even?}.map(&:shift).reverse

puts o*" "

# #pragma GCC optimize ("O3")
# #include "bits/stdc++.h"
#
# using namespace std;
# using ll = long long int;
#
# #define debugos cout
# #define debug(v) {printf("L%d %s > ",__LINE__,#v);debugos<<(v)<<endl;}
# #define debugv(v) {printf("L%d %s > ",__LINE__,#v);for(auto e:(v)){debugos<<e<<" ";}debugos<<endl;}
# #define debuga(m,w) {printf("L%d %s > ",__LINE__,#m);for(int x=0;x<(w);x++){debugos<<(m)[x]<<" ";}debugos<<endl;}
# #define debugaa(m,h,w) {printf("L%d %s >\n",__LINE__,#m);for(int y=0;y<(h);y++){for(int x=0;x<(w);x++){debugos<<(m)[y][x]<<" ";}debugos<<endl;}}
# #define ALL(v) (v).begin(),(v).end()
# #define repeat(cnt,l) for(remove_reference<remove_const<decltype(l)>::type>::type cnt=0;(cnt)<(l);++(cnt))
# #define rrepeat(cnt,l) for(auto cnt=(l)-1;0<=(cnt);--(cnt))
# #define iterate(cnt,b,e) for(auto cnt=(b);(cnt)!=(e);++(cnt))
# #define diterate(cnt,b,e) for(auto cnt=(b);(cnt)!=(e);--(cnt))
# const ll MD = 1000000007ll; const long double PI = 3.1415926535897932384626433832795L;
# inline void assert_call(bool assertion, function<void()> f) { if (!assertion) { cerr << "assertion fault:" << endl; f(); abort(); } }
# template<typename T1, typename T2> inline ostream& operator <<(ostream &o, const pair<T1, T2> p) { o << '(' << p.first << ':' << p.second << ')'; return o; }
# template<typename Vec> inline ostream& _ostream_vecprint(ostream& os, const Vec& a) {
#     os << '['; for (const auto& e : a) os << ' ' << e << ' '; os << ']'; return os;
# }
# template<typename T> inline ostream& operator<<(ostream& o, const vector<T>& v) { return _ostream_vecprint(o, v); }
# template<typename T, size_t S> inline ostream& operator<<(ostream& o, const array<T, S>& v) { return _ostream_vecprint(o, v); }
# template<typename T> inline T& chmax(T& to, const T& val) { return to = max(to, val); }
# template<typename T> inline T& chmin(T& to, const T& val) { return to = min(to, val); }
# void bye(string s, int code = 0) { cout << s << endl; exit(code); }
# mt19937_64 randdev(8901016);
# template<typename T> inline T rand(T l, T h) { return uniform_int_distribution<T>(l, h)(randdev); }
# template<> inline double rand<double>(double l, double h) { return uniform_real_distribution<double>(l, h)(randdev); }
# template<> inline float rand<float>(float l, float h) { return uniform_real_distribution<float>(l, h)(randdev); }
#
# #if defined(_WIN32) || defined(_WIN64)
# #define getchar_unlocked _getchar_nolock
# #define putchar_unlocked _putchar_nolock
# #elif defined(__GNUC__)
# #else
# #define getchar_unlocked getchar
# #define putchar_unlocked putchar
# #endif
# namespace {
# #define isvisiblechar(c) (0x21<=(c)&&(c)<=0x7E)
#     class MaiScanner {
#     public:
#         template<typename T> void input_integer(T& var) {
#             var = 0; T sign = 1;
#             int cc = getchar_unlocked();
#             for (; cc < '0' || '9' < cc; cc = getchar_unlocked())
#                 if (cc == '-') sign = -1;
#             for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked())
#                 var = (var << 3) + (var << 1) + cc - '0';
#             var = var * sign;
#         }
#         inline int c() { return getchar_unlocked(); }
#         inline MaiScanner& operator>>(int& var) { input_integer<int>(var); return *this; }
#         inline MaiScanner& operator>>(long long& var) { input_integer<long long>(var); return *this; }
#         inline MaiScanner& operator>>(string& var) {
#             int cc = getchar_unlocked();
#             for (; !isvisiblechar(cc); cc = getchar_unlocked());
#             for (; isvisiblechar(cc); cc = getchar_unlocked())
#                 var.push_back(cc);
#             return *this;
#         }
#         template<typename IT> void in(IT begin, IT end) { for (auto it = begin; it != end; ++it) *this >> *it; }
#     };
#     class MaiPrinter {
#     public:
#         template<typename T>
#         void output_integer(T var) {
#             if (var == 0) { putchar_unlocked('0'); return; }
#             if (var < 0)
#                 putchar_unlocked('-'),
#                 var = -var;
#             char stack[32]; int stack_p = 0;
#             while (var)
#                 stack[stack_p++] = '0' + (var % 10),
#                 var /= 10;
#             while (stack_p)
#                 putchar_unlocked(stack[--stack_p]);
#         }
#         inline MaiPrinter& operator<<(char c) { putchar_unlocked(c); return *this; }
#         inline MaiPrinter& operator<<(int var) { output_integer<int>(var); return *this; }
#         inline MaiPrinter& operator<<(long long var) { output_integer<long long>(var); return *this; }
#         inline MaiPrinter& operator<<(char* str_p) { while (*str_p) putchar_unlocked(*(str_p++)); return *this; }
#         inline MaiPrinter& operator<<(const string& str) {
#             const char* p = str.c_str();
#             const char* l = p + str.size();
#             while (p < l) putchar_unlocked(*p++);
#             return *this;
#         }
#         template<typename IT> void join(IT begin, IT end, char sep = ' ') { for (bool b = 0; begin != end; ++begin, b = 1) b ? *this << sep << *begin : *this << *begin; }
#     };
# }
# MaiScanner scanner;
# MaiPrinter printer;
#
#
# //
#
# /*
# あらかじめソート
#
# 低い人->高い人 を選択
# 高い人->低い人 を未選択する
#
# これを動的計画法する
# */
#
# int N;
# ll A[111];
#
# ll dp[111][111];
#
# int main() {
#     scanner >> N;
#     scanner.in(A, A + N);
#     sort(A, A + N);
#
#     fill(dp[0], dp[110], ll(1e18));
#     dp[0][0] = 0;
#
#     int M = N - 1;
#     iterate(i, 0, N) {
#         iterate(j, 0, i+1) {
#             ll d = 0;
#             int jp = j;
#             iterate(k, i+1, N) {
#                 chmin(dp[k][j], max(dp[i][j], max(d, A[k] - A[i])));
#
#                 chmax(d, A[k] - A[jp]);
#                 jp = k;
#             }
#         }
#     }
#     ll ans = 1e18;
#     repeat(i, N) {
#         chmin(ans, max(dp[N-1][i], A[N - 1] - A[i]));
#     }
#
#     debugaa(dp, N+1, N+1);
#
#     cout << ans << endl;
#
#     return 0;
# }

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

n = gets.to_i
arr = []
arr= gets.chomp.split(" ").map(&:to_i)

def getdisc(arr)
	max = 0
	arr[1..-1].each_with_index do |x,i|
		asd = (x-arr[i-1]).abs
		max = asd if asd>max
	end
	asd = (arr[-1]-arr[0]).abs
	max=asd if asd>max
	return max
end

def newgetdisc(arr)
	max = 0
	arr[1..-1].each_with_index do |x,i|
		asd = (x-arr[i-1]).abs
		max+= asd
	end
	asd = (arr[-1]-arr[0]).abs
	max+=asd# if asd>max
	return max
end

def swap(arr,a,b)
	temp  = arr[a]
	arr[a]=arr[b]
	arr[b]=temp
	return arr
end

#newarr = []
#disc =

#p arr
=begin
arr.each do |x|
	if newarr.length==0
		newarr.push x
	else
		scorearr = []
		(0..newarr.length).each do |insloc|
			newnewarr = newarr.dup
			newnewarr.insert(insloc,x)
			scorearr.push newgetdisc(newnewarr)
		end
		theloc = scorearr.index(scorearr.min)
		newarr.insert(theloc,x)
	end
	p newarr
end
=end
=begin
newarr = arr.dup

while true
	currscore = getdisc(newarr)
	tobreak = false
	newarr.each_with_index do |x,i|
		newarr[i+1..-1].each_with_index do |y,j|
			newnewarr = newarr.dup
			newnewarr = swap(newnewarr,i,j)
			if(getdisc(newnewarr)<currscore)
				newarr=newnewarr.dup
				tobreak = true
				break
			end
		end
		break if tobreak
	end

	break if not tobreak
end
p newarr
=end

arr.sort!
newarr = []
arr.each_with_index do |x,i|
	newarr.push x if i%2==0
end

arr.reverse!

if arr.length%2==0
	arr.each_with_index do |x,i|
		newarr.push x if i%2==0
	end
else
	arr.each_with_index do |x,i|
		newarr.push x if i%2==1
	end
end

newarr.each do |x|
	print x
	print " "
end
puts


You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.

The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1, c2, ..., cn — the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.

Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.

4 3
codeforces codesecrof
contest round
letter message
codeforces contest letter contest

5 3
joll wuqrd
euzf un
hbnyiyc rsoqqveh
hbnyiyc joll joll euzf joll

codeforces round letter round
hbnyiyc joll joll un joll

n, m = gets.split.map(&:to_i)
d = Hash.new
m.times do
  a, b = gets.split
  d[a] = if a.length <= b.length; a; else b; end
end
puts gets.split.map {|w| d[w]}.join(' ')

n, m = gets.strip.split.map {|n| n.to_i}
lang1 = []
lang2 = []
m.times do
	w1, w2 = gets.strip.split.map {|n| n}
	lang1.push(w1)
	lang2.push(w2)
end
notes = ""
lec = gets.strip.split(" ")
lec.each do |word|
	i = lang1.index(word)
	notes += lang1[i].size <= lang2[i].size ? lang1[i] + " " : lang2[i]+ " "
end
puts notes

hash = Hash.new;
n, m = gets.chomp.split.map(&:to_i);

m.times do
  a, b = gets.chomp.split;
  hash[a] = b.length < a.length ? b : a;
end
gets.chomp.split.each {|x| print hash[x] + " "};

n, m = gets.chomp.split.map(&:to_i)
a={}
m.times do
  ai, bi = gets.chomp.split
  a[ai] = bi
end
ans=''

gets.chomp.split.each do |s|
  ans += (s.length <= a[s].length ? s : a[s]) + ' '
end
puts ans

n,m =gets.split().map(&:to_i)
dic = {}
m.times do
  a,b = gets.split(" ")
  dic[a] =b
end

val = gets.split(" ")
res = ''
val.each do |i|
  if i.size > dic[i].size
    res +=dic[i]
  else
    res +=i
  end
  res +=' '
end
puts res

n,m=gets.split.map{|e| e.to_i}
h={}
m.times{
	a,b=gets.chomp.split
	if ((a.size)<=>(b.size))<1 then
		h[a]=a
		h[b]=a
	else
		h[a]=b
		h[b]=b
	end
}
s=gets.chomp.split
i=0
s.each{|e|
	print " " if i>0
	print h[e]
	i+=1
}
print "\n"

#$stdin = File.open "input.txt"

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

replace = {}
m.times do
	a, b = gets.chomp.split
	replace[a] = b.size < a.size ? b : a
end

puts gets.chomp.split.map { |s| replace[s] }.join(" ")

#!/usr/bin/ruby
class InputReader
    def initialize
        @data = []
        @offset = 0
    end

    def next
        if @data.empty? || @offset >= @data.length
            line = STDIN.gets.chomp
            return nil if line.empty?
            @data = line.split(/\s+/)
            @offset = 0
        end
        @offset += 1
        return @data[@offset-1]
    end
end

# ===== Your solution goes here =====
reader = InputReader.new
n = reader.next.to_i
m = reader.next.to_i
dict = {}
m.times do
    k = reader.next
    v = reader.next
    dict[k] = v
end

n.times do
    word = reader.next
    if word.length <= dict[word].length
        print "#{word} "
    else
        print "#{dict[word]} "
    end
end

n, m = gets.split(' ').map(&:to_i)
dic = Hash[]
m.times do
  word = gets.split
  dic[word.first] = word.min_by &:length
end
puts gets.split.map {|w| dic[w]}.join(' ')

nums = gets.chomp.split
n = Integer(nums[0])
m = Integer(nums[1])
best = Array.new
bad = Array.new
input = Array.new
for i in 0...m
    input[i] = Array.new
    input[i] = gets.chomp.split
    if input[i][0].length <= input[i][1].length
        best.push(input[i][0])
        bad.push(input[i][1])
    else
        best.push(input[i][1])
        bad.push(input[i][0])
    end
end
lecture = Array.new
lecture = gets.chomp.split

note = {}
for i in 0...m
    note[best[i]] = best[i]
    note[bad[i]] = best[i]
end
best_note = []
for i in 0...n
    best_note.push(note[lecture[i]])
end

print best_note.join(" ")

nm = gets.chomp.split
n = nm[0].to_i
m = nm[1].to_i
ab = []
a = []
b = []
for i in (0..m-1)
	ab[i] = gets.chomp.split
	a[i] = ab[i][0]
	b[i] = ab[i][1]
	if a[i].size <= b[i].size
		b[i] = nil
	end
end
c = gets.chomp.split

for i in (0..n-1)
	if b[a.find_index(c[i])] == nil
		print a[a.find_index(c[i])] + " "
	else
		print b[a.find_index(c[i])] + " "
	end
end

n,m = gets.split(" ").map(&:to_i)
words = {}
m.times do
	a,b = gets.split(" ")
	words[a] =  b
end
lec = gets.split(" ")
op = []
lec.each do |a|
	if a.length > words[a].length
		op << words[a]
	else
		op << a
	end
end

puts op.join(" ")

n, m = gets.chomp.split(' ').map(&:to_i)
a = {}
m.times do
  ai, bi = gets.chomp.split ' '
  a[ai] = bi
end

res = ''

gets.chomp.split(' ').each do |s|
  res += (s.length <= a[s].length ? s : a[s]) + ' '
end
puts res

n,m = gets.split.map &:to_i
dic = Hash[]
m.times do
  w = gets.split
  dic[w.first] = w.min_by &:length
end
puts gets.split.map {|w| dic[w]}.join(' ')

n, m = gets.split.map(&:to_i)
a, b = m.times.map { gets.split }.transpose
puts gets.split.map { |x| [x, b[a.index(x)]].min_by(&:size) }.join(' ')

line = gets.chop!.split(" ")

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

A = {}
B = {}

for i in (1 .. m)
    line = gets.chop!.split(" ")

    first = line[0]
    second = line[1]

    B[first] = i
    B[second] = i

    if second.size < first.size
        A[i] = second
    elsif second.size > first.size
        A[i] = first
    else
        A[i] = first
    end
end

line = gets.chop!.split(" ")

for i in (1 .. n)
    print A[B[line[i-1]]]

    if i < n
        print " "
    end
end

n, m = gets.split.map &:to_i
dict = Hash.new
m.times do
	a, b = gets.split
	dict[a] = b.size < a.size ? b : a
end
puts gets.split.map { |_| dict[_] }.join(' ')

n, m = gets.split.map{|x| x.to_i}
h = {}
m.times{h.merge!(Hash[*gets.split])}
puts(gets.split.map{|x| x.size <= h[x].size ? x : h[x]}.join(' '))

q=[]
j=0
gets.split.each do |i|
q[j]=i.to_i
j=j+1
end
hash=Hash[]

q[1].times do
  s=gets.split
  hash[s[0]]=s[1]
end

gets.split.each do |i|
  if i.length <= hash[i].length
    print i + " "
  else
    print hash[i]+" "
  end
end

# http://codeforces.com/problemset/problem/499/B

n, m = gets.chomp.split.map(&:to_i)
lang_1 = []
lang_2 = []

m.times do
  words = gets.chomp.split
  lang_1 << words[0]
  lang_2 << words[1]
end

lecture = gets.chomp.split
note = []

for word in lecture
  index = lang_1.index(word)
  replace_word = [word, lang_2[index]].min_by(&:length)
  note << replace_word
end

puts note.join(" ")

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

1.upto(m) do
  k, v = gets.chomp.split(' ')
  words[k] = v
end

result = gets.chomp.split(' ').map { |s| s.length > words[s].length ? words[s] : s }

puts result.join(' ')

# 499B

def read_line
  gets.chomp.split
end

w = {}
read_line[1].to_i.times do
  k, v = read_line
  w[k] = v
end
puts read_line.map { |k| v = w[k]; v.size < k.size ? v : k } * ' '

# f = File.open('input.txt', 'r')
f = STDIN
n, m = f.gets.chomp.split.map &:to_i
dict1, dict2 = {}, {}
m.times do
  s1, s2 = f.gets.chomp.split
  dict1[s1] = s2
  dict2[s2] = s1
end

strs = f.gets.chomp.split
t = strs.map do |s|
  if dict1[s]
    dict1[s].length < s.length ? dict1[s] : s
  else
    dict2[s].length < s.length ? dict2[s] : s
  end
end

puts t.join(' ')

class Array
	def __min
		self[0].length <= self[1].length ? self[0] : self[1]
	end
end

n, m = gets.split.map(&:to_i)
dict = {}
m.times do
	a, b = gets.split
	dict[a] = [a, b].__min
end
puts gets.split.map{|w| dict[w]}.join(' ')

hash = Hash.new;
n, m = gets.chomp.split.map(&:to_i);

m.times do
  a, b = gets.chomp.split;
  hash[a] = b.length < a.length ? b : a;
end

p gets.chomp.split.inject(){ |sum, x|
  # p "#{sum}, #{x}, #{hash[x]}";
  sum + " " + hash[x];
}

nm = gets.chomp.split
n = nm[0].to_i
m = nm[1].to_i
ab = []
a = []
b = []
for i in (0..m-1)
	ab[i] = gets.chomp.split
	a[i] = ab[i][0]
	b[i] = ab[i][1]
	if a[i].size < b[i].size
		b[i] = nil
	end
end
c = gets.chomp.split

for i in (0..n-1)
	if b[a.find_index(c[i])] == nil
		print a[a.find_index(c[i])] + " "
	else
		print b[a.find_index(c[i])] + " "
	end
end

n, m = gets.chomp.split(' ').map(&:to_i)
a = {}
m.times do
  ai, bi = gets.chomp.split ' '
  a[ai] = bi
end

res = ''

gets.chomp.split(' ').each do |s|
  res += (s.length >= a[s].length ? s : a[s]) + ' '
end
puts res

line = gets.chop!.split(" ")

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

A = {}
B = {}

for i in (1 .. m)
    line = gets.chop!.split(" ")

    first = line[0]
    second = line[1]

    B[first] = i
    B[second] = i

    if second.size < first.size
        A[i] = second
    elsif second.size > first.size
        A[i] = first
    else
        if second < first
            A[i] = second
        else
            A[i] = first
        end
    end
end

line = gets.chop!.split(" ")

for i in (1 .. n)
    print A[B[line[i-1]]]

    if i < n
        print " "
    end
end

line = gets.chop!.split(" ")

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

A = {}
B = {}

for i in (1 .. m)
    line = gets.chop!.split(" ")

    first = line[0]
    second = line[1]

    B[first] = i
    B[second] = i

    if second < first
        A[i] = second
    else
        A[i] = first
    end
end

line = gets.chop!.split(" ")

for i in (1 .. n)
    print A[B[line[i-1]]]

    if i < n
        print " "
    end
end

# http://codeforces.com/problemset/problem/499/B

n, m = gets.chomp.split.map(&:to_i)
lang_1 = []
lang_2 = []

m.times do
  words = gets.chomp.split
  lang_1 << words[0]
  lang_2 << words[1]
end

text_str = gets.chomp
text_arr = text_str.split

for i in 0..(m - 1)
  if !text_arr.include?(lang_1[i])
    next
  end

  word = lang_1[i].length <= lang_2[i].length ? lang_1[i] : lang_2[i]
  text_str.gsub!(lang_1[i], word)
end

puts text_str


You are given two rectangles on a plane. The centers of both rectangles are located in the origin of coordinates (meaning the center of the rectangle's symmetry). The first rectangle's sides are parallel to the coordinate axes: the length of the side that is parallel to the Ox axis, equals w, the length of the side that is parallel to the Oy axis, equals h. The second rectangle can be obtained by rotating the first rectangle relative to the origin of coordinates by angle α.  Your task is to find the area of the region which belongs to both given rectangles. This region is shaded in the picture.

The first line contains three integers w, h, α (1 ≤ w, h ≤ 106; 0 ≤ α ≤ 180). Angle α is given in degrees.

In a single line print a real number — the area of the region which belongs to both given rectangles. The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 6.

NoteThe second sample has been drawn on the picture above.

ww, hh, alpha = gets.split(' ').map{ |e| e.to_i}

if (ww < hh)
	w = hh.to_f
	h = ww.to_f
else
	w = ww.to_f
	h = hh.to_f
end
# w >= h
alpha = 180 - alpha if alpha > 90
alpha = alpha * Math::PI / 180
theta = 2 * Math.atan(h / w)

if alpha == 0
	puts w * h
elsif alpha < theta
	sa = Math.sin(alpha)
	ca = Math.cos(alpha)
	puts (w * h - (1-ca)*(h*h+w*w-2*h*w*sa)/(2*sa*ca))
else
	puts h * h / Math.sin(alpha)
end

ww, hh, alpha = gets.split(' ').map{ |e| e.to_i}

if (ww < hh)
	w = hh.to_f
	h = ww.to_f
else
	w = ww.to_f
	h = hh.to_f
end
# w >= h
alpha = 180 - alpha if alpha > 90
alpha = alpha * Math::PI / 180
theta = 360 * Math.atan(h / w) / Math::PI

if alpha < theta
	sa = Math.sin(alpha)
	ca = Math.cos(alpha)
	puts (w * h - (1-ca)*(h*h+w*w-2*h*w*sa)/(2*sa*ca))
else
	puts h * h / Math.sin(alpha)
end

ww, hh, alpha = gets.split(' ').map{ |e| e.to_i}

if (ww < hh)
	w = hh.to_f
	h = ww.to_f
else
	w = ww.to_f
	h = hh.to_f
end
# w >= h
alpha = 180 - alpha if alpha > 90
alpha = alpha * Math::PI / 180
theta = 360 * Math.atan(h / w) / Math::PI

if alpha == 0
	puts w * h
elsif  alpha < theta
	sa = Math.sin(alpha)
	ca = Math.cos(alpha)
	puts (w * h - (1-ca)*(h*h+w*w-2*h*w*sa)/(2*sa*ca))
else
	puts h * h / Math.sin(alpha)
end

ww, hh, alpha = gets.split(' ').map{ |e| e.to_i}

if (ww < hh)
	w = hh.to_f
	h = ww.to_f
else
	w = ww.to_f
	h = hh.to_f
end
# w >= h
alpha = 180 - alpha if alpha > 90
alpha = alpha * Math::PI / 180
theta = 2 * Math.atan(h / w)

if alpha == 0
	puts w * h
elsif alpha < theta
	sa = Math.sin(alpha)
	ca = Math.cos(alpha)
	puts (w * h - (1-ca)*(h*h+w*w-2*h*w*sa)/(2*sa*ca))
else
	puts 'here'
	puts h * h / Math.sin(alpha)
end


The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = ki·x + bi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1 < x2. In other words, is it true that there are 1 ≤ i < j ≤ n and x', y', such that:   y' = ki * x' + bi, that is, point (x', y') belongs to the line number i;  y' = kj * x' + bj, that is, point (x', y') belongs to the line number j;  x1 < x' < x2, that is, point (x', y') lies inside the strip bounded by x1 < x2. You can't leave Anton in trouble, can you? Write a program that solves the given task.

The first line of the input contains an integer n (2 ≤ n ≤ 100 000) — the number of lines in the task given to Anton. The second line contains integers x1 and x2 ( - 1 000 000 ≤ x1 < x2 ≤ 1 000 000) defining the strip inside which you need to find a point of intersection of at least two lines. The following n lines contain integers ki, bi ( - 1 000 000 ≤ ki, bi ≤ 1 000 000) — the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two i ≠ j it is true that either ki ≠ kj, or bi ≠ bj.

Print "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes).

NoteIn the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it.

n = gets.chomp.to_i
x1, x2 = gets.chomp.split(" ").map(&:to_i)
x1 += 1.0e-10
x2 -= 1.0e-10
ary = []
n.times do |i|
  k, b = gets.chomp.split(" ").map(&:to_f)
  ary << [i, (x1)*k+b, (x2)*k+b]
end
ary1 = ary.sort_by{|v| v[1]}
ary2 = ary.sort_by{|v| v[2]}
if ary1 == ary2 then
  puts "NO"
else
  puts "YES"
end

n = gets.chomp.to_i
x1, x2 = gets.chomp.split(" ").map(&:to_i)
ary = []
n.times do |i|
  k, b = gets.chomp.split(" ").map(&:to_f)
  y1 = k * x1 + b
  y2 = k * x2 + b
  ary << [i, y1, y2]
end
ary1 = ary.sort{|a, b| a[1] <=> b[1]}
ary2 = ary.sort{|a, b| a[2] <=> b[2]}
if ary1 == ary2 then
  puts "NO"
else
  puts "YES"
end

n = gets.chomp.to_i
x1, x2 = gets.chomp.split(" ").map(&:to_i)
ary = []
n.times do |i|
  k, b = gets.chomp.split(" ").map(&:to_f)
  ary << [i, k, b]
end
ary1 = ary.sort_by{|v| (x1*v[1]+v[2]).nonzero? || (x1 + 0.1)*v[1]+v[2]}
ary2 = ary.sort_by{|v| (x2*v[1]+v[2]).nonzero? || (x2 - 0.1)*v[1]+v[2]}
if ary1 == ary2 then
  puts "NO"
else
  puts "YES"
end

n = gets.chomp.to_i
x1, x2 = gets.chomp.split(" ").map(&:to_i)
ary = []
n.times do |i|
  k, b = gets.chomp.split(" ").map(&:to_f)
  ary << [i, (x1 + 0.00001)*k+b, (x2 - 0.00001)*k+b]
end
ary1 = ary.sort_by{|v| v[1]}
ary2 = ary.sort_by{|v| v[2]}
if ary1 == ary2 then
  puts "NO"
else
  puts "YES"
end

n = gets.chomp.to_i
x1, x2 = gets.chomp.split(" ").map(&:to_i)
ary = []
n.times do |i|
  k, b = gets.chomp.split(" ").map(&:to_f)
  ary << [i, (x1 + 0.0001)*k+b, (x2 - 0.0001)*k+b]
end
ary1 = ary.sort_by{|v| v[1]}
ary2 = ary.sort_by{|v| v[2]}
if ary1 == ary2 then
  puts "NO"
else
  puts "YES"
end

n = gets.chomp.to_i
x1, x2 = gets.chomp.split(" ").map(&:to_i)
ary = []
n.times do |i|
  k, b = gets.chomp.split(" ").map(&:to_f)
  ary << [i, (x1 + 0.000001)*k+b, (x2 - 0.000001)*k+b]
end
ary1 = ary.sort_by{|v| v[1]}
ary2 = ary.sort_by{|v| v[2]}
if ary1 == ary2 then
  puts "NO"
else
  puts "YES"
end


You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.

NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".In the third query we can do nothing to obtain a good string.

gets;puts$<.map{|e|e=e.chomp.chars.sort*'';e[0]<e[-1] ? e : -1}

n = gets.strip.to_i
results = []
n.times do
    x = gets.strip
    res = -1
    if x.chars.uniq.length > 1
        x_chars = x.chars
        if x_chars == x.chars.reverse
            while true do
                x_chars.shuffle!
                if x_chars != x_chars.reverse
                    res = x_chars.join
                    break
                end
            end
        else
            res = x_chars.join
        end
    end
    results << res
end

n.times do |x|
    puts results[x]
end

n = gets.to_i
n.times do
  s = gets.chomp
  idx = nil
  flag = false
  s.length.times do |i|
    if s[i] != s[0]
      flag = true
      idx = i
    end
  end
  if flag && s == s.reverse
    t = s[0]
    s[0] = s[idx]
    s[idx] = t
  end
  puts flag ? s : -1
end

def solve(s)
  if s.split('').uniq.size == 1
    -1
  else
    s.split('').sort.join
  end
end

gets.strip.to_i.times do
  puts solve(gets.strip)
end

gets;puts$<.map{|e|e.chomp!;f=e.chars.sort*'';f<e ? f : -1}

n = gets.strip.to_i
results = []
n.times do
    x = gets.strip
    res = -1
    if x.chars.uniq.length > 1
        x_chars = x.chars
        if x_chars == x.chars.reverse
            while true do
                x_chars.shuffle!
                if x_chars != x.chars.reverse
                    res = x_chars.join
                    break
                end
            end
        else
            res = x_chars.join
        end
    end
    results << res
end

n.times do |x|
    puts results[x]
end


A flowerbed has many flowers and two fountains.You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.

The first line of the input contains integers n, x1, y1, x2, y2 (1 ≤ n ≤ 2000,  - 107 ≤ x1, y1, x2, y2 ≤ 107) — the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≤ xi, yi ≤ 107) — the coordinates of the i-th flower. It is guaranteed that all n + 2 points in the input are distinct.

Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.

NoteThe first sample is (r12 = 5, r22 = 1):  The second sample is (r12 = 1, r22 = 32):

n, x1, y1, x2, y2 = gets.split(' ').map(&:to_i)

fs = []
for i in 0...n
  fx, fy = gets.split(' ').map(&:to_i)
  fs << [fx, fy]
end

ds = []
for j in 0...n
  fx, fy = fs[j]
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  ds << [d1, d2]
end
ds << [0,0]

min = Float::INFINITY
for dv in ds
    d1 = dv[0]
    d2 = 0
    for dw in ds
        if dw[0] > d1
            d2 = [dw[1], d2].max
        end
    end

    min = [min, d1+d2].min
end

puts min

n, x1, y1, x2, y2 = gets.chomp.split(" ").map(&:to_i)
dist = []

n.times do
  fx, fy = gets.chomp.split(" ").map(&:to_i)
  d1 = (x1 - fx)**2 + (y1 - fy)**2
  d2 = (x2 - fx)**2 + (y2 - fy)**2
  dist << [d1, d2]
end
dist << [0,0]

res = Float::INFINITY
dist.each do |i|
  r1 = i[0]
  r2 = 0
  dist.each do |j|
    if j[0] > r1 then
      r2 = [r2, j[1]].max
    end
  end
  res = [res, r1 + r2].min
end

puts res

n, x1, y1, x2, y2 = gets.split(' ').map(&:to_i)
md1 = md2 = 0
for i in 0...n
  fx, fy = gets.split(' ').map(&:to_i)
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  if d1-md1 < d2-md2
    # closer to r1
    md1 = [md1, d1].max
  else
    # closer to r2
    md2 = [md2, d2].max
  end
end

puts md1 + md2

n, x1, y1, x2, y2 = gets.split(' ').map(&:to_i)

fs = []
for i in 0...n
  fx, fy = gets.split(' ').map(&:to_i)
  fs << [fx, fy]
end

min = Float::INFINITY

md1 = md2 = 0
for j in 0...n
  fx, fy = fs[j]
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  if d1-md1 < d2-md2
    # closer to r1
    md1 = [md1, d1].max
  else
    # closer to r2
    md2 = [md2, d2].max
  end
end
min = [min, md1 + md2].min

md1 = md2 = 0
for j in 1..n
  fx, fy = fs[n-j]
  d1 = (fx-x1)**2+(fy-y1)**2
  d2 = (fx-x2)**2+(fy-y2)**2
  if d1-md1 < d2-md2
    # closer to r1
    md1 = [md1, d1].max
  else
    # closer to r2
    md2 = [md2, d2].max
  end
end
min = [min, md1 + md2].min

puts min

n, x1, y1, x2, y2 = gets.chomp.split(" ").map(&:to_i)
dist = []

n.times do
  fx, fy = gets.chomp.split(" ").map(&:to_i)
  d1 = (x1 - fx)**2 + (y1 - fy)**2
  d2 = (x2 - fx)**2 + (y2 - fy)**2
  dist << [d1, d2]
end

res = 10**15
dist.each do |i|
  r1 = i[0]
  r2 = 0
  dist.each do |j|
    if j[0] > r1 then
      r2 = [r2, j[1]].max
    end
  end
  res = [res, r1 + r2].min
end
puts res

n, x1, y1, x2, y2 = gets.chomp.split(" ").map(&:to_i)
dist = []

n.times do
  fx, fy = gets.chomp.split(" ").map(&:to_i)
  d1 = (x1 - fx)**2 + (y1 - fy)**2
  d2 = (x2 - fx)**2 + (y2 - fy)**2
  dist << [d1, d2]
end

res = 10**8
dist.each do |i|
  r1 = i[0]
  r2 = 0
  dist.each do |j|
    if j[0] > r1 then
      r2 = [r2, j[1]].max
    end
  end
  res = [res, r1 + r2].min
end
puts res


Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.

The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.

A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.

NoteIn the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 31 1 2 2 32 1 1 2 3

# TEMPLATE BEGIN
def read_vector
    gets.chomp.split(/\s+/)
end
def read_vector_int
    read_vector.map(&:to_i)
end
# TEMPLATE END

$mod = 1_000_000_007
$maxn = 1010

def mypow(a, b)
    res = 1
    while b > 0
        res = res * a % $mod if b % 2 == 1
        a = a * a % $mod
        b /= 2
    end
    res
end

def ceshka(a, b)
    $fuck[a] * $rfuck[b] * $rfuck[a-b] % $mod
end

$fuck, $rfuck = [1], [1]
(1..$maxn).each.map do |i|
    $fuck.push $fuck[i-1] * i % $mod
    $rfuck.push mypow($fuck[i], $mod - 2)
end

k = read_vector_int.first
a = k.times.map{ read_vector_int.first }

res, sum = 1, 0
k.times do |i|
    sum += a[i]
    res = res * ceshka(sum - 1, a[i] - 1) % $mod
end
puts res

k = gets().chomp().to_i

n = gets().chomp().to_i
count = 1
mod = 1000000007
(k-1).times {
        c = gets().chomp().to_i
        p=c-1
        t1=1
        t2=1
        for i in(1..p)
                t1 *= n+i
                #t1 %= mod
                t2 *= i
                #t2 %= mod
        end

        count *= t1/t2
        count %= mod
        n+=c
}

puts count

k = gets().chomp().to_i

n = gets().chomp().to_i
count = 1
mod = 1000000007
(k-1).times {
        c = gets().chomp().to_i
        p=c-1
        t1=1
        t2=1
        for i in(1..p)
                t1 *= n+i
                t1 %= mod
                t2 *= i
                t2 %= mod
        end

        count *= t1/t2
        n+=c
}

puts count


You are given an integer $$$n$$$. Find any string $$$s$$$ of length $$$n$$$ consisting only of English lowercase letters such that each non-empty substring of $$$s$$$ occurs in $$$s$$$ an odd number of times. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print a single line containing the string $$$s$$$. If there are multiple such strings, output any. It can be shown that such string always exists under the given constraints.

NoteIn the first test case, each substring of "abc" occurs exactly once.In the third test case, each substring of "bbcaabbba" occurs an odd number of times. In particular, "b" occurs $$$5$$$ times, "a" and "bb" occur $$$3$$$ times each, and each of the remaining substrings occurs exactly once.

gets
while n = gets&.to_i
  m = n / 2
  puts n == 1 ? 'a' : 'a' * m + 'b' + 'a' * (m - 1) + 'c' * n[0]
end


Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $$$a$$$ and $$$b$$$ ($$$a < b$$$). After that, the student can apply any of the following operations any number of times:   $$$a := a + 1$$$ (increase $$$a$$$ by $$$1$$$),  $$$b := b + 1$$$ (increase $$$b$$$ by $$$1$$$),  $$$a := a \ | \ b$$$ (replace $$$a$$$ with the bitwise OR of $$$a$$$ and $$$b$$$). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $$$a$$$ equal to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line for each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a < b \le 10^6$$$). It is guaranteed that the sum of $$$b$$$ over all test cases does not exceed $$$10^6$$$.

For each test case print one integer — the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.

NoteIn the first test case, it is optimal to apply the third operation.In the second test case, it is optimal to apply the first operation three times.In the third test case, it is optimal to apply the second operation and then the third operation.

gets.to_i.times do
  a, b = gets.split.map(&:to_i)
  p (0..(b - a)).flat_map { |i|
    new_a = a + i
    new_b = b + i
    [i + (new_a == b ? 0 : 1 + (new_a | b) - b),
     i + 1 + (a | new_b) - new_b]
  }.min
end


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given a regular bracket sequence $$$s$$$ and an integer number $$$k$$$. Your task is to find a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$.It is guaranteed that such sequence always exists.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 2 \cdot 10^5$$$, both $$$n$$$ and $$$k$$$ are even) — the length of $$$s$$$ and the length of the sequence you are asked to find. The second line is a string $$$s$$$ — regular bracket sequence of length $$$n$$$.

Print a single string — a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$. It is guaranteed that such sequence always exists.

N, K = gets.split.map(&:to_i)
str = gets.chomp
use = []
cnt = 0
N.times do |i|
    if str[i] == '(' && cnt < K/2
        use[i] = true
        cnt += 1
    end
end
cnt = 0
(N-1).downto(0) do |i|
    if str[i] == ')' && cnt < K/2
        use[i] = true
        cnt += 1
    end
end

ans = ''
N.times do |i|
    ans << str[i] if use[i]
end
puts ans


There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete — the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\max(A) - \min(B)|$$$ is as small as possible, where $$$\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is:   first team: $$$A = [1, 2, 4]$$$,  second team: $$$B = [3, 6]$$$. In this case, the value $$$|\max(A) - \min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\max(A) - \min(B)|$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of two lines.  The first line contains positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — number of athletes.  The second line contains $$$n$$$ positive integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 1000$$$), where $$$s_i$$$ — is the strength of the $$$i$$$-th athlete. Please note that $$$s$$$ values may not be distinct.

For each test case print one integer — the minimum value of $$$|\max(A) - \min(B)|$$$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.

NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, so the answer is $$$|2-2|=0$$$.

gets.to_i.times do
	n = gets.to_i
	a = gets.split.map(&:to_i).sort
	puts a.each_cons(2).map { _2 - _1 }.min
end

gets.strip.to_i.times do |t|
  _ = gets.strip.to_i
  vals = gets.strip.split(' ').map(&:to_i).sort
  mn = vals[1] - vals[0]
  a = vals[0]
  b = vals[1]
  vals.each_with_index do |e, i|
    next if i.zero?
    if vals[i] - vals[i - 1] < mn
      mn = vals[i] - vals[i-1]
      a = vals[i-1]
      b = vals[i]
    end
  end
  puts (a - b).abs
end

t = gets.chomp.to_i
t.times do |testcase|
  n = gets.chomp.to_i
  arr = gets.split.map(&:to_i)
  arr = arr.sort ; min_val = 1000000
  (arr.size-1).times do |i|
    min_val = [min_val , arr[i+1]-arr[i]].min
  end
  puts min_val
end

t = gets.to_i

1.upto t do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  a.sort!
  diff = a[1] - a[0]
  1.upto a.length-1 do |i|
    diff = [diff, a[i]-a[i-1]].min
  end
  puts diff
end

gets.to_i.times {
    gets
    puts gets.split.map(&:to_i).sort.each_cons(2).map{|x,y|y-x}.min
}

gets.to_i.times {
  gets
  data = gets.split.map { |v| v.to_i }.sort_by {|v| v}

  m = data[1] - data[0]
  for i in 2...data.size
    d = data[i] - data[i-1]
    if d < m
      m = d
    end
  end

  puts m
}

def solve
  _ = gets
  arr = gets.strip.split(' ').map(&:to_i).sort
  diff = 1001
  arr.each_with_index { |el, i|
    next if i.zero?
    diff = [diff, arr[i] - arr[i - 1]].min
  }
  puts diff

end

gets.strip.to_i.times do
  solve
end

t = gets.to_i
t.times do
  n = gets.to_i
  s = gets.split.map(&:to_i).sort
  min_diff = s[-1] - s[0]
  for i in 0...(n - 1) do
    diff = s[i + 1] - s[i]
    if diff < min_diff
      min_diff = diff
    end
  end
  puts min_diff
end

gets.to_i.times do
  gets
  a = gets.split(' ').map(&:to_i).sort

  result = 1_000_000
  while a.size > 1
    x = a.shift

    result = [a.first - x, result].min
  end

  puts result
end

n = gets.chomp.to_i
n.times {
    arrNum = gets.chomp.to_i
    userstr = gets.chomp
    arr = userstr.split().map(&:to_i).sort
    result = arr.each_cons(2).map {|a,b| b-a}
    p result.min
}