Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations:  the final tournament features n teams (n is always even)  the first n / 2 teams (according to the standings) come through to the knockout stage  the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals  it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.

class Team
	def initialize(nm)
		@name = nm
		@point = 0
		@scored = 0
		@missed = 0
	end
	attr_accessor :name, :point, :scored, :missed
end

n = gets.chomp.to_i
h = Hash.new(n)
for i in 0..n-1
	s = gets.chomp
	h[s] = Team.new(s)
end

for i in 0..n*(n-1)/2-1
	a = gets.chomp.split(/ /)
	teams = a[0].split(/\-/)
	score = a[1].split(/\:/).map!{|x| x.to_i}
	h[teams[0]].scored += score[0]
	h[teams[0]].missed += score[1]
	h[teams[1]].scored += score[1]
	h[teams[1]].missed += score[0]
	if score[0] == score[1]
		h[teams[0]].point += 1
		h[teams[1]].point += 1
	elsif  score[0] > score[1]
		h[teams[0]].point += 3
	else
		h[teams[1]].point += 3
	end
end

qu = h.values.sort!{|a,b|
	if a.point == b.point
		if (a.scored - a.missed) == (b.scored-b.missed)
			b.scored <=> a.scored
		else
			(b.scored - b.missed) <=> (a.scored-a.missed)
		end
	else
		b.point <=> a.point
	end
}

qu = qu.slice(0..n/2-1)
qu.sort!{|a,b| a.name <=> b.name}

for i in 0..n/2-1
	puts qu[i].name
end

class SoccerData
  attr_accessor :win
  attr_accessor :lose
  attr_accessor :point
  attr_accessor :name
  def initialize(name)
    @name=name
    @win=0
    @lose=0
    @point=0
  end
  include Comparable
  def <=>(other)
    if @point!=other.point
      return other.point-@point
    elsif (@win-@lose)!=(other.win-other.lose)
      return (other.win-other.lose)-(@win-@lose)
    elsif (@win!=other.win)
      return other.win-@win
    else
      return @name<=>other.name
    end
  end
end
n=gets.chomp!.to_i
data=Array.new(n)
t=SoccerData.new("test")
memo=Hash.new
n.times do |i|
  name=gets.chomp!
  data[i]=SoccerData.new(name)
  memo[name]=data[i]
end
(n*(n-1)/2).times do
  tmp1=gets.chomp!.split(" ")
  tmp2=tmp1[0].split("-")
  d1=memo[tmp2[0]]
  d2=memo[tmp2[1]]
  tmp2=tmp1[1].split(":")
  w1=tmp2[0].to_i
  w2=tmp2[1].to_i
  if w1>w2
    d1.point+=3
  elsif w1<w2
    d2.point+=3
  else
    d1.point+=1
    d2.point+=1
  end
  d1.win+=w1
  d1.lose+=w2
  d2.win+=w2
  d2.lose+=w1
end
data.sort!
str=Array.new(n/2)
(n/2).times do |i|
  str[i]=data[i].name
end
str.sort!
str.each do |s|
  puts(s)
end

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

=begin
nA. World Football Cup
time limit per test
2 seconds
memory limit per test
64 megabytes
input
standard input
output
standard output

Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations:

    * the final tournament features n teams (n is always even)
    * the first n / 2 teams (according to the standings) come through to the knockout stage
    * the standings are made on the following principle: for a victory a team gets 3 points, for a draw — 1 point, for a defeat — 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place — in decreasing order of the difference between scored and missed goals; in the third place — in the decreasing order of scored goals
    * it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity.

You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
Input

The first input line contains the only integer n (1 ≤ n ≤ 50) — amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following n·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 — names of the teams; num1, num2 (0 ≤ num1, num2 ≤ 100) — amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
Output

Output n / 2 lines — names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
=end

N = gets.to_i
teams = Hash.new
N.times do
  teams[gets.chomp] = [0, 0, 0]
end

(N * (N - 1) / 2).times do
  tmp = gets.chomp.split
  team1, team2 = tmp[0].split('-')
  score1, score2 = tmp[1].split(':').map{|e| e.to_i}
  if score1 > score2
    teams[team1][0] += 3
  elsif score1 == score2
    teams[team1][0] += 1
    teams[team2][0] += 1
  else
    teams[team2][0] += 3
  end

  teams[team1][1] += score1 - score2
  teams[team2][1] += score2 - score1

  teams[team1][2] += score1
  teams[team2][2] += score2
end

#p teams

teams = teams.to_a
teams.sort!{|l_e, r_e|
  l = l_e[1]
  r = r_e[1]
  if l[0] > r[0]
    -1
  elsif l[0] < r[0]
    1
  elsif l[1] > r[1]
    -1
  elsif l[1] < r[1]
    1
  elsif l[2] > r[2]
    -1
  elsif l[2] < r[2]
    1
  else
    0
  end
}

#p teams

passed = teams[0, (N / 2)].sort{|l, r|
  l[0] <=> r[0]
}

passed.each {|e|
  puts e[0]
}

n = gets.to_i
teams = Hash.new { |hash, key| hash[key] = [0, 0, 0]}
n.times{ gets }
((n * (n - 1) / 2)).times do
  line = gets.chomp
  line =~ /(\w+)\-(\w+) (\d+):(\d+)/
  t_an, t_bn, t_aw, t_bw = $1, $2, $3.to_i, $4.to_i
  if t_aw > t_bw
    teams[t_an][0] += 3
  elsif t_aw < t_bw
    teams[t_bn][0] += 3
  else
    teams[t_an][0] += 1
    teams[t_bn][0] += 1
  end
  teams[t_an][1] += t_aw - t_bw; teams[t_an][2] += t_aw
  teams[t_bn][1] += t_bw - t_aw; teams[t_bn][2] += t_bw
end

puts teams.sort { |a, b| b[1] <=> a[1] }.map{ |u| u[0]}[0, n / 2].sort

#!/usr/bin/env ruby
n = gets.to_i

matches = (n * (n - 1)/2).to_i
matrix = []
n.times { |i| matrix[i] = [] }

t = {}
n.times do |i|
  team = gets.strip
  matrix[i] = [0, 0, 0, team]
  t[team] = i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matches.times do
  result = gets
  ts, res = result.split

  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':').map { |v| v.to_i }
  score1, score2 = get_score.call(goal1, goal2)

  # by score
  matrix[t[team1]][0] += score1
  matrix[t[team2]][0] += score2

  # by diff
  matrix[t[team1]][1] += goal1 - goal2
  matrix[t[team2]][1] += goal2 - goal1

  # by goals
  matrix[t[team1]][2] += goal1
  matrix[t[team2]][2] += goal2
end

matrix = matrix.sort_by { |team| [ team[0], team[1], team[2] ] }

puts (n/2 .. n-1).inject([]) { |res, i| res << matrix[i][-1] }.sort

class Team
  attr_accessor :name, :point, :net_score, :score

  def initialize(name)
    self.name = name
    self.point = self.net_score = self.score = 0
  end

  def add(x, y)
    self.point += [0, 1, 3][(x <=> y) + 1]
    self.net_score += x - y
    self.score += x
  end

  def <=>(o)
    [:point, :net_score, :score].each do |t|
      ret = self.send(t) <=> o.send(t)
      return ret unless ret == 0
    end
  end
end

n = gets.to_i
teams = Hash.new
n.times do
  name = gets.strip
  teams[name] = Team.new(name)
end
(n * (n - 1) / 2).times do
  a, b, x, y = gets.strip.split(/[\:\- ]/)
  x = x.to_i
  y = y.to_i
  teams[a].add(x, y)
  teams[b].add(y, x)
end
winner = teams.values.sort[-n / 2..-1].map(&:name).sort
puts winner

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][2] += g1
	teams[b][2] += g2

	teams[a][1] -= g2 - g1
	teams[b][1] -= g1 - g2

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

t = teams.sort { |a, b| b[1] <=> a[1] }.first(n / 2).map { |data| data[0] }.sort
t.each { |e| puts e }

class Team
	def initialize(nm)
		@name = nm
		@point = 0
		@scored = 0
		@missed = 0
	end
	attr_accessor :name, :point, :scored, :missed
end

n = gets.chomp.to_i
h = Hash.new(n)
for i in 0..n-1
	s = gets.chomp
	h[s] = Team.new(s)
end

for i in 0..n*(n-1)/2-1
	a = gets.chomp.split(/ /)
	teams = a[0].split(/\-/)
	score = a[1].split(/\:/).map!{|x| x.to_i}
	h[teams[0]].scored += score[0]
	h[teams[0]].missed += score[1]
	h[teams[1]].scored += score[1]
	h[teams[1]].missed += score[0]
	if score[0] == score[1]
		h[teams[0]].point += 1
		h[teams[1]].point += 1
	elsif  score[0] > score[1]
		h[teams[0]].point += 3
	else
		h[teams[1]].point += 3
	end
end

qu = h.values.sort!{|a,b|
	if a.point == b.point
		if (a.scored - a.missed) == (b.scored-b.missed)
			b.scored <=> a.scored
		else
			(a.scored - a.missed) <=> (b.scored-b.missed)
		end
	else
		b.point <=> a.point
	end
}

qu = qu.slice(0..n/2-1)
qu.sort!{|a,b| a.name <=> b.name}

for i in 0..n/2-1
	print " " if i > 0
	print qu[i].name
end
puts

class Team
	def initialize(nm)
		@name = nm
		@point = 0
		@scored = 0
		@missed = 0
	end
	attr_accessor :name, :point, :scored, :missed
end

n = gets.chomp.to_i
h = Hash.new(n)
for i in 0..n-1
	s = gets.chomp
	h[s] = Team.new(s)
end

for i in 0..n*(n-1)/2-1
	a = gets.chomp.split(/ /)
	teams = a[0].split(/\-/)
	score = a[1].split(/\:/).map!{|x| x.to_i}
	h[teams[0]].scored += score[0]
	h[teams[0]].missed += score[1]
	h[teams[1]].scored += score[1]
	h[teams[1]].missed += score[0]
	if score[0] == score[1]
		h[teams[0]].point += 1
		h[teams[1]].point += 1
	elsif  score[0] > score[1]
		h[teams[0]].point += 3
	else
		h[teams[1]].point += 3
	end
end

qu = h.values.sort!{|a,b|
	if a.point == b.point
		if (a.scored - a.missed) == (b.scored-b.missed)
			b.scored <=> a.scored
		else
			(a.scored - a.missed) <=> (b.scored-b.missed)
		end
	else
		b.point <=> a.point
	end
}

qu = qu.slice(0..n/2-1)
qu.sort!{|a,b| a.name <=> b.name}

for i in 0..n/2-1
	puts qu[i].name
end

#!/usr/bin/env ruby
number = gets.to_i

t = {}
y = {}
number.times do |i|
  team = gets.strip
  t[team] = i
  y[i] = team
end

matches = (number * (number - 1)/2).to_i
matrix = []
number.times { |i| matrix[i] = Array.new(0) }

matches.times do
  result = gets
  ts, res = result.split
  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':')

  matrix[t[team1]][t[team2]] = goal1.to_i
  matrix[t[team2]][t[team1]] = goal2.to_i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matrix_r = matrix
matrix.each_with_index do |team, i|
  sum = team.inject(0) { |r, v| r+v.to_i }

  diff = sum
  number.times do |j|
    diff -= matrix[j][i] || 0
  end

  matrix_r[i] << sum << diff << y[i]
end

matrix_sorted = matrix_r.sort_by do |team|
  [ team[-3], team[-2] ]
end

# output results
(number / 2).times do |i|
  puts matrix_sorted[number/2 + i][-1]
end

#!/usr/bin/env ruby
number = gets.to_i

matches = (number * (number - 1)/2).to_i
matrix = []
number.times { |i| matrix[i] = [] }

t = {}
number.times do |i|
  team = gets.strip
  matrix[i] = [0, 0, 0, team]
  t[team] = i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matches.times do
  result = gets
  ts, res = result.split

  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':').map { |v| v.to_i }
  score1, score2 = get_score.call(goal1, goal2)

  matrix[t[team1]][0] += score1
  matrix[t[team2]][0] += score2

  matrix[t[team1]][1] += goal1 - goal2
  matrix[t[team2]][1] += goal2 - goal1

  matrix[t[team1]][2] += goal1
  matrix[t[team2]][2] += goal2
end

matrix = matrix.sort_by do |team|
  [ team[0], team[1], team[2] ]
end

(number / 2).times do |i|
  puts matrix[number/2 + i][-1]
end

#!/usr/bin/env ruby
number = gets.to_i

t = {}
y = {}
number.times do |i|
  team = gets.strip
  t[team] = i
  y[i] = team
end

matches = (number * (number - 1)/2).to_i
matrix = []
number.times { |i| matrix[i] = Array.new(0) }

matches.times do
  result = gets
  ts, res = result.split
  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':')

  matrix[t[team1]][t[team2]] = goal1.to_i
  matrix[t[team2]][t[team1]] = goal2.to_i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matrix_r = matrix
matrix.each_with_index do |team, i|
  sum = team.inject(0) { |r, v| r+v.to_i }

  diff = sum
  number.times do |j|
    diff -= matrix[j][i] || 0
  end

  matrix_r[i] << sum << diff << y[i]
end

matrix_sorted = matrix_r.sort_by do |team|
  [ team[-3], team[-2] ]
end.reverse

# output results
(number / 2).times do |i|
  puts matrix_sorted[i][-1]
end

#!/usr/bin/env ruby
number = gets.to_i

matches = (number * (number - 1)/2).to_i
matrix = []
number.times { |i| matrix[i] = [] }

t = {}
number.times do |i|
  team = gets.strip
  matrix[i] = [0, 0, 0, team]
  t[team] = i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matches.times do
  result = gets
  ts, res = result.split

  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':').map { |v| v.to_i }
  score1, score2 = get_score.call(goal1, goal2)

  matrix[t[team1]][0] += score1
  matrix[t[team2]][0] += score2

  matrix[t[team1]][1] += goal1 - goal2

  matrix[t[team1]][2] += goal1
end

matrix = matrix.sort_by do |team|
  [ team[0], team[1], team[2] ]
end

(number / 2).times do |i|
  puts matrix[number/2 + i][-1]
end

#!/usr/bin/env ruby
number = gets.to_i

matches = (number * (number - 1)/2).to_i
matrix = []
number.times { |i| matrix[i] = [] }

t = {}
number.times do |i|
  team = gets.strip
  matrix[i] = [0, 0, 0, team]
  t[team] = i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matches.times do
  result = gets
  ts, res = result.split

  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':').map { |v| v.to_i }
  score1, score2 = get_score.call(goal1, goal2)

  matrix[t[team1]][0] += score1
  matrix[t[team2]][0] += score2

  matrix[t[team1]][1] += goal1 - goal2
  matrix[t[team2]][1] += goal2 - goal1

  matrix[t[team1]][2] += goal1
  matrix[t[team2]][2] += goal2
end

matrix = matrix.sort_by do |team|
  [ team[0], team[1], team[2] ]
end

p matrix

(number / 2).times do |i|
  puts matrix[number/2 + i][-1]
end

#!/usr/bin/env ruby
number = gets.to_i

matches = (number * (number - 1)/2).to_i
matrix = []
number.times { |i| matrix[i] = [] }

t = {}
number.times do |i|
  team = gets.strip
  matrix[i] = [0, 0, team]
  t[team] = i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matches.times do
  result = gets
  ts, res = result.split

  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':').map { |v| v.to_i }
  score1, score2 = get_score.call(goal1, goal2)

  matrix[t[team1]][0] += score1
  matrix[t[team2]][0] += score2

  matrix[t[team1]][1] += goal1 - goal2
end

matrix_sorted = matrix.sort_by do |team|
  [ team[-3], team[-2] ]
end

# output results
qual = number==1 ? 1 : number / 2
qual.times do |i|
  puts matrix_sorted[number/2 + i][-1]
end

#!/usr/bin/env ruby
n = gets.to_i

matches = (n * (n - 1)/2).to_i
matrix = []
n.times { |i| matrix[i] = [] }

t = {}
n.times do |i|
  team = gets.strip
  matrix[i] = [0, 0, 0, team]
  t[team] = i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matches.times do
  result = gets
  ts, res = result.split

  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':').map { |v| v.to_i }
  score1, score2 = get_score.call(goal1, goal2)

  # by score
  matrix[t[team1]][0] += score1
  matrix[t[team2]][0] += score2

  # by diff
  matrix[t[team1]][1] += goal1 - goal2
  matrix[t[team2]][1] += goal2 - goal1

  # by goals
  matrix[t[team1]][2] += goal1
  matrix[t[team2]][2] += goal2
end

matrix = matrix.sort_by { |team| [ team[0], team[1], team[2], team[3] ] }

(n/2 .. n-1).each { |i| puts matrix[i][-1] }

#!/usr/bin/env ruby
n = gets.to_i

matches = (n * (n - 1)/2).to_i
matrix = []
n.times { |i| matrix[i] = [] }

t = {}
n.times do |i|
  team = gets.strip
  matrix[i] = [0, 0, 0, team]
  t[team] = i
end

get_score = lambda do |goal1, goal2|
  if goal1 > goal2
    [3, 0]
  elsif goal1 < goal2
    [0, 3]
  else
    [1, 1]
  end
end

matches.times do
  result = gets
  ts, res = result.split

  team1, team2 = ts.split('-')
  goal1, goal2 = res.split(':').map { |v| v.to_i }
  score1, score2 = get_score.call(goal1, goal2)

  # by score
  matrix[t[team1]][0] += score1
  matrix[t[team2]][0] += score2

  # by diff
  matrix[t[team1]][1] += goal1 - goal2
  matrix[t[team2]][1] += goal2 - goal1

  # by goals
  matrix[t[team1]][2] += goal1
  matrix[t[team2]][2] += goal2
end

matrix = matrix.sort_by { |team| [ team[0], team[1], team[2] ] }

(n / 2 .. n-1).each { |i| puts matrix[i][-1] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][2] += g1
	teams[b][2] += g2

	teams[a][1] += (g1 - g2).abs
	teams[a][1] += (g2 - g1).abs

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

teams.sort { |a, b| a[1] <=> b[1] }.reverse.first(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][1] += g1
	teams[b][1] += g2

	teams[a][2] += g2
	teams[a][2] += g1

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

teams.sort { |a, b| a[1] <=> b[1] }.last(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][2] += g1
	teams[b][2] += g2

	teams[a][1] += (g1 - g2).abs
	teams[a][1] += (g2 - g1).abs

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

t = teams.sort { |a, b| b[1] <=> a[1] }.map { |data| data[0] }.sort
t.first(n / 2).each { |e| puts e }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][1] += g1
	teams[b][1] += g2

	teams[a][2] += (g1 - g2).abs
	teams[a][2] += (g2 - g1).abs

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

teams.sort { |a, b| a[1] <=> b[1] }.last(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][2] += g1
	teams[b][2] += g2

	teams[a][1] += (g1 - g2).abs
	teams[a][1] += (g2 - g1).abs

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

t = teams.sort { |a, b| b[1] <=> a[1] }.first(n / 2).map { |data| data[0] }.sort
t.each { |e| puts e }

n, teams = gets.to_i, Hash.new(0); n.times { gets }
while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i
	teams[a] += g1
	teams[b] += g2
end

p teams

teams.sort { |a, b| a[1] <=> b[1] }.last(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][2] += g1
	teams[b][2] += g2

	teams[a][1] += (g1 - g2).abs
	teams[a][1] += (g2 - g1).abs

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

teams.sort { |a, b| a[1] <=> b[1] }.last(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][1] += g1
	teams[b][1] += g2

	teams[a][2] += g1 - g2
	teams[a][2] += g2 - g1

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

teams.sort { |a, b| a[1] <=> b[1] }.last(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][2] += g1
	teams[b][2] += g2

	teams[a][1] += (g1 - g2).abs
	teams[a][1] += (g2 - g1).abs

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

teams.sort { |a, b| b[1] <=> a[1] }.first(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, Hash.new(0); n.times { gets }
while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i
	teams[a] += g1
	teams[b] += g2
end
teams.sort { |a, b| a[1] <=> b[1] }.last(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, {}
n.times { teams[gets.strip.to_sym] = [0, 0, 0] }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)
	a, b, g1, g2 = g[0].to_sym, g[1].to_sym, g[2].to_i, g[3].to_i

	teams[a][1] += g1
	teams[b][1] += g2

	teams[a][2] -= g2
	teams[a][2] -= g1

	if g1 == g2
		teams[a][0] += 1
		teams[b][0] += 1
	elsif g1 > g2
		teams[a][0] += 3
	else
		teams[b][0] += 3
	end

end

teams.sort { |a, b| a[1] <=> b[1] }.last(n / 2).each { |data| puts data[0] }

n, teams = gets.to_i, Hash.new(0); n.times { gets }

while g = gets
	g = g.strip.split(/[:\-[:space:]]/)

	 a = g[0].to_sym
	 b = g[1].to_sym
	as = g[2].to_i
	bs = g[3].to_i

	if as == bs
		score = [1, 1]
	elsif as > bs
		score = [3, -1]
	else
		score = [-1, 3]
	end

	teams[a] = score[0]
	teams[b] = score[1]

end

teams.sort_by { |team, score| score }.last(n / 2).each { |data| puts data[0] }


You are given an array $$$a$$$ of $$$n$$$ integers. Initially there is only one copy of the given array.You can do operations of two types:  Choose any array and clone it. After that there is one more copy of the chosen array.  Swap two elements from any two copies (maybe in the same copy) on any positions. You need to find the minimal number of operations needed to obtain a copy where all elements are equal.

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 each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output a single integer — the minimal number of operations needed to create at least one copy where all elements are equal.

NoteIn the first test case all elements in the array are already equal, that's why the answer is $$$0$$$.In the second test case it is possible to create a copy of the given array. After that there will be two identical arrays:$$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 0 \ 1 \ 3 \ 3 \ 7 \ 0 \ ]$$$After that we can swap elements in a way so all zeroes are in one array:$$$[ \ 0 \ \underline{0} \ \underline{0} \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ \underline{1} \ 1 \ 3 \ 3 \ 7 \ \underline{3} \ ]$$$Now let's create a copy of the first array:$$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$, $$$[ \ 0 \ 0 \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$Let's swap elements in the first two copies:$$$[ \ 0 \ 0 \ 0 \ \underline{0} \ \underline{0} \ 0 \ ]$$$, $$$[ \ \underline{3} \ \underline{7} \ 0 \ 3 \ 7 \ 0 \ ]$$$ and $$$[ \ 1 \ 1 \ 3 \ 3 \ 7 \ 3 \ ]$$$.Finally, we made a copy where all elements are equal and made $$$6$$$ operations.It can be proven that no fewer operations are enough.

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  have = xs.tally.max_by { |k, v| v }.last
  clones = 0
  have2 = have
  while have2 < xs.size
    have2 *= 2
    clones += 1
  end
  p clones + xs.size - have
end


Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are $$$n$$$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $$$i$$$-th position. Thus each of $$$n$$$ positions should contain exactly one flower: a rose or a lily.She knows that exactly $$$m$$$ people will visit this exhibition. The $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\leq n, m\leq 10^3$$$) — the number of flowers and visitors respectively. Each of the next $$$m$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1\leq l_i\leq r_i\leq n$$$), meaning that $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive.

Print the string of $$$n$$$ characters. The $$$i$$$-th symbol should be «0» if you want to put a rose in the $$$i$$$-th position, otherwise «1» if you want to put a lily. If there are multiple answers, print any.

NoteIn the first example, Sonya can put roses in the first, fourth, and fifth positions, and lilies in the second and third positions;  in the segment $$$[1\ldots3]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$;  in the segment $$$[2\ldots4]$$$, there are one rose and two lilies, so the beauty is equal to $$$1\cdot 2=2$$$;  in the segment $$$[2\ldots5]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$. The total beauty is equal to $$$2+2+4=8$$$.In the second example, Sonya can put roses in the third, fourth, and sixth positions, and lilies in the first, second, and fifth positions;  in the segment $$$[5\ldots6]$$$, there are one rose and one lily, so the beauty is equal to $$$1\cdot 1=1$$$;  in the segment $$$[1\ldots4]$$$, there are two roses and two lilies, so the beauty is equal to $$$2\cdot 2=4$$$;  in the segment $$$[4\ldots6]$$$, there are two roses and one lily, so the beauty is equal to $$$2\cdot 1=2$$$. The total beauty is equal to $$$1+4+2=7$$$.

n,m = STDIN.readline.strip.split(/\s+/).map(&:to_i)

coordinates = []
m.times do
  coordinates << STDIN.readline.strip.split(/\s+/).map(&:to_i)
end

flower = '1'
string = ''
n.times do
  string += flower
  if flower == '1'
    flower = '0'
  else
    flower = '1'
  end
end

puts string

n, d = gets.chomp.split.map(&:to_i)
x = ""
0.upto(n-1) { |n| x += (n&1).to_s }
print x

n, m = gets.chomp.split
n = n.to_i
m = m.to_i
m.times do |m|
  gets.chomp
end

ans = ""
n.times do |i|
  ans << (i % 2).to_s
end
puts ans

N, M = gets.to_i
puts N.times.map{|i| i%2==0 ? 1 : 0}.join

n, m = gets.strip.split.map(&:to_i)
m.times do
  gets.strip.split.map(&:to_i)
end

str = ""
n.times do |i|
  str << (i%2).to_s
end
puts str

n, m = gets.split.map &:to_i
puts (0...n).map { |i| i.even? ? ?0 : ?1 } .join


In order to do some research, $$$n^2$$$ labs are built on different heights of a mountain. Let's enumerate them with integers from $$$1$$$ to $$$n^2$$$, such that the lab with the number $$$1$$$ is at the lowest place, the lab with the number $$$2$$$ is at the second-lowest place, $$$\ldots$$$, the lab with the number $$$n^2$$$ is at the highest place.To transport water between the labs, pipes are built between every pair of labs. A pipe can transport at most one unit of water at a time from the lab with the number $$$u$$$ to the lab with the number $$$v$$$ if $$$u > v$$$.Now the labs need to be divided into $$$n$$$ groups, each group should contain exactly $$$n$$$ labs. The labs from different groups can transport water to each other. The sum of units of water that can be sent from a group $$$A$$$ to a group $$$B$$$ is equal to the number of pairs of labs ($$$u, v$$$) such that the lab with the number $$$u$$$ is from the group $$$A$$$, the lab with the number $$$v$$$ is from the group $$$B$$$ and $$$u > v$$$. Let's denote this value as $$$f(A,B)$$$ (i.e. $$$f(A,B)$$$ is the sum of units of water that can be sent from a group $$$A$$$ to a group $$$B$$$).For example, if $$$n=3$$$ and there are $$$3$$$ groups $$$X$$$, $$$Y$$$ and $$$Z$$$: $$$X = \{1, 5, 6\}, Y = \{2, 4, 9\}$$$ and $$$Z = \{3, 7, 8\}$$$. In this case, the values of $$$f$$$ are equal to:  $$$f(X,Y)=4$$$ because of $$$5 \rightarrow 2$$$, $$$5 \rightarrow 4$$$, $$$6 \rightarrow 2$$$, $$$6 \rightarrow 4$$$,  $$$f(X,Z)=2$$$ because of $$$5 \rightarrow 3$$$, $$$6 \rightarrow 3$$$,  $$$f(Y,X)=5$$$ because of $$$2 \rightarrow 1$$$, $$$4 \rightarrow 1$$$, $$$9 \rightarrow 1$$$, $$$9 \rightarrow 5$$$, $$$9 \rightarrow 6$$$,  $$$f(Y,Z)=4$$$ because of $$$4 \rightarrow 3$$$, $$$9 \rightarrow 3$$$, $$$9 \rightarrow 7$$$, $$$9 \rightarrow 8$$$,  $$$f(Z,X)=7$$$ because of $$$3 \rightarrow 1$$$, $$$7 \rightarrow 1$$$, $$$7 \rightarrow 5$$$, $$$7 \rightarrow 6$$$, $$$8 \rightarrow 1$$$, $$$8 \rightarrow 5$$$, $$$8 \rightarrow 6$$$,  $$$f(Z,Y)=5$$$ because of $$$3 \rightarrow 2$$$, $$$7 \rightarrow 2$$$, $$$7 \rightarrow 4$$$, $$$8 \rightarrow 2$$$, $$$8 \rightarrow 4$$$. Please, divide labs into $$$n$$$ groups with size $$$n$$$, such that the value $$$\min f(A,B)$$$ over all possible pairs of groups $$$A$$$ and $$$B$$$ ($$$A \neq B$$$) is maximal.In other words, divide labs into $$$n$$$ groups with size $$$n$$$, such that minimum number of the sum of units of water that can be transported from a group $$$A$$$ to a group $$$B$$$ for every pair of different groups $$$A$$$ and $$$B$$$ ($$$A \neq B$$$) as big as possible.Note, that the example above doesn't demonstrate an optimal division, but it demonstrates how to calculate the values $$$f$$$ for some division.If there are many optimal divisions, you can find any.

The only line contains one number $$$n$$$ ($$$2 \leq n \leq 300$$$).

Output $$$n$$$ lines: In the $$$i$$$-th line print $$$n$$$ numbers, the numbers of labs of the $$$i$$$-th group, in any order you want. If there are multiple answers, that maximize the minimum number of the sum of units of water that can be transported from one group the another, you can print any.

NoteIn the first test we can divide $$$9$$$ labs into groups $$$\{2, 8, 5\}, \{9, 3, 4\}, \{7, 6, 1\}$$$.From the first group to the second group we can transport $$$4$$$ units of water ($$$8 \rightarrow 3, 8 \rightarrow 4, 5 \rightarrow 3, 5 \rightarrow 4$$$).From the first group to the third group we can transport $$$5$$$ units of water ($$$2 \rightarrow 1, 8 \rightarrow 7, 8 \rightarrow 6, 8 \rightarrow 1, 5 \rightarrow 1$$$).From the second group to the first group we can transport $$$5$$$ units of water ($$$9 \rightarrow 2, 9 \rightarrow 8, 9 \rightarrow 5, 3 \rightarrow 2, 4 \rightarrow 2$$$).From the second group to the third group we can transport $$$5$$$ units of water ($$$9 \rightarrow 7, 9 \rightarrow 6, 9 \rightarrow 1, 3 \rightarrow 1, 4 \rightarrow 1$$$).From the third group to the first group we can transport $$$4$$$ units of water ($$$7 \rightarrow 2, 7 \rightarrow 5, 6 \rightarrow 2, 6 \rightarrow 5$$$).From the third group to the second group we can transport $$$4$$$ units of water ($$$7 \rightarrow 3, 7 \rightarrow 4, 6 \rightarrow 3, 6 \rightarrow 4$$$).The minimal number of the sum of units of water, that can be transported from one group to another is equal to $$$4$$$. It can be proved, that it is impossible to make a better division.

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end
def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi

ans=Array.new(n){[]}

idx=0
n.times do |i|
  if i%2==0
    0.upto(n-1) do |j|
      num = i*n + j + 1
      ans[j] << num
    end
  else
    (n-1).downto(0) do |j|
      num = i*n + (n-1-j) + 1
      ans[j] << num
    end
  end
end

ans.map{|i|puts i.join(" ")}

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end
def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi

ans=Array.new(n){[]}

idx=0
n.times do |i|
  n.times do |j|
    num = i*n + j + 1
    ans[idx] << num
    idx = (idx+1)%n
  end
  idx = (idx+1)%n
end

ans.map{|i|puts i.join(" ")}


Today at the lesson of mathematics, Petya learns about the digital root.The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-digit number is reached. Let's denote the digital root of $$$x$$$ as $$$S(x)$$$. Then $$$S(5)=5$$$, $$$S(38)=S(3+8=11)=S(1+1=2)=2$$$, $$$S(10)=S(1+0=1)=1$$$.As a homework Petya got $$$n$$$ tasks of the form: find $$$k$$$-th positive number whose digital root is $$$x$$$.Petya has already solved all the problems, but he doesn't know if it's right. Your task is to solve all $$$n$$$ tasks from Petya's homework.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$) — the number of tasks in Petya's homework. The next $$$n$$$ lines contain two integers $$$k_i$$$ ($$$1 \le k_i \le 10^{12}$$$) and $$$x_i$$$ ($$$1 \le x_i \le 9$$$) — $$$i$$$-th Petya's task in which you need to find a $$$k_i$$$-th positive number, the digital root of which is $$$x_i$$$.

Output $$$n$$$ lines, $$$i$$$-th line should contain a single integer — the answer to the $$$i$$$-th problem.

def root(n)
  until n <= 9
    n = n.to_s.split('').map(&:to_i).inject(:+)
  end
  n
end

def solve(s)
end

gets.strip.to_i.times do
  k, x = gets.strip.split(' ').map(&:to_i)
  puts (9 * (k - 1)) + x
end

n = gets.to_i
n.times do
    k,x = gets.split.map(&:to_i)
    puts 9*(k-1)+x
end

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

n = gets.to_i
n.times do
  kx = gets.chomp.split(" ").map(&:to_i)
  k = kx[0]
  x = kx[1]

  puts 9*(k-1) + x
end

q=gets.to_i
for _ in 1..q
  a,b=gets.split.map &:to_i
  puts b+9*a-9
end


I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?You are given a string of $$$n$$$ lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. 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.Find out what the MEX of the string is!

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 1000$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the length of the word. The second line for each test case contains a single string of $$$n$$$ lowercase Latin letters. The sum of $$$n$$$ over all test cases will not exceed $$$1000$$$.

For each test case, output the MEX of the string on a new line.

3
28
qaabzwsxedcrfvtgbyhnujmiklop
13
cleanairactbd
10
aannttoonn

MAXLEN = 6
AAA = 'a' * MAXLEN
require 'set'
t = gets.to_i
t.times.each do
  n = gets.to_i
  s = gets.chomp
  seen = Set.new
  (0...s.length).each do |i|
    (i + 1..s.length).each do |j|
      seen << s[i, j - i]
    end
  end

  base = 'a'.ord - 1
  key = nil
  (1..2000000).each do |s|
    key = ''
    ok = true
    until s == 0 do
      if s % 27 == 0
        ok = false
        break
      end
      c = (base + (s % 27)).chr
      key.concat(c)
      s /= 27
    end
    key.reverse!

    break if ok && !seen.include?(key)
  end
  puts key
end

require 'set'
t = gets.to_i
t.times.each do
  n = gets.to_i
  s = gets.chomp
  seen = Set.new
  (0...s.length).each do |i|
    (i + 1..s.length).each do |j|
      seen << s[i, j - i]
    end
  end
  cur = 'a'
  while seen.include?(cur) do
    pos = cur.length - 1
    while cur[pos] == 'z' && pos >= 0 do
      pos -= 1
    end
    if pos < 0
      cur = 'a' * (cur.length + 1)
    else
      cur[pos] = (cur[pos].ord + 1).chr
    end
  end
  puts cur
end


There are $$$n$$$ participants in a competition, participant $$$i$$$ having a strength of $$$s_i$$$. Every participant wonders how much of an advantage they have over the other best participant. In other words, each participant $$$i$$$ wants to know the difference between $$$s_i$$$ and $$$s_j$$$, where $$$j$$$ is the strongest participant in the competition, not counting $$$i$$$ (a difference can be negative).So, they ask you for your help! For each $$$i$$$ ($$$1 \leq i \leq n$$$) output the difference between $$$s_i$$$ and the maximum strength of any participant other than participant $$$i$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$2 \leq n \leq 2\cdot10^5$$$) — the length of the array. The following line contains $$$n$$$ space-separated positive integers $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$1 \leq s_i \leq 10^9$$$) — the strengths of the participants. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, output $$$n$$$ space-separated integers. For each $$$i$$$ ($$$1 \leq i \leq n$$$) output the difference between $$$s_i$$$ and the maximum strength of any other participant.

NoteFor the first test case: The first participant has a strength of $$$4$$$ and the largest strength of a participant different from the first one is $$$7$$$, so the answer for the first participant is $$$4 - 7 = -3$$$.  The second participant has a strength of $$$7$$$ and the largest strength of a participant different from the second one is $$$5$$$, so the answer for the second participant is $$$7 - 5 = 2$$$. The third participant has a strength of $$$3$$$ and the largest strength of a participant different from the third one is $$$7$$$, so the answer for the third participant is $$$3 - 7 = -4$$$. The fourth participant has a strength of $$$5$$$ and the largest strength of a participant different from the fourth one is $$$7$$$, so the answer for the fourth participant is $$$5 - 7 = -2$$$.

main = -> {
  n = gets.to_i
  s = gets.split.map(&:to_i)

  strongs = s.max(2)

  ans = n.times.map {|i|
    if s[i] == strongs[0]
      s[i] - strongs[1]
    else
      s[i] - strongs[0]
    end
  }

  ans.join(" ")
}

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

=begin

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

=end

t=gets.to_i
for i in 1..t
    n =gets.to_i
    s=gets
    maks=s.split.map{|x|x.to_i}
    s1=maks.dup
    s2=maks.dup
    for j in 1..(n-1)
        s1[j]=[s1[j-1], s1[j]].max
        s2[n-j-1]=[s2[n-j-1], s2[n-j]].max
    end
    print(maks[0]-s2[1], " ")
    for j in 1..(n-2)
        print(maks[j]-[s1[j-1], s2[j+1]].max, " ")
    end
    puts maks[n-1]-s1[n-2]
end

gets.to_i.times{
    gets
    x = gets.split.map &:to_i
    a = x.max
    b = x.max(2)[1]
    x.size.times{|i|
        if x[i]==a
            print(a-b,' ')
        else
            print(x[i]-a,' ')
        end
    }
    puts ""
}


In late autumn evening n robots gathered in the cheerful company of friends. Each robot has a unique identifier — an integer from 1 to 109.At some moment, robots decided to play the game "Snowball". Below there are the rules of this game. First, all robots stand in a row. Then the first robot says his identifier. After that the second robot says the identifier of the first robot and then says his own identifier. Then the third robot says the identifier of the first robot, then says the identifier of the second robot and after that says his own. This process continues from left to right until the n-th robot says his identifier.Your task is to determine the k-th identifier to be pronounced.

The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ min(2·109, n·(n + 1) / 2). The second line contains the sequence id1, id2, ..., idn (1 ≤ idi ≤ 109) — identifiers of roborts. It is guaranteed that all identifiers are different.

Print the k-th pronounced identifier (assume that the numeration starts from 1).

NoteIn the first sample identifiers of robots will be pronounced in the following order: 1, 1, 2. As k = 2, the answer equals to 1.In the second test case identifiers of robots will be pronounced in the following order: 10, 10, 4, 10, 4, 18, 10, 4, 18, 3. As k = 5, the answer equals to 4.

n,k,*a=$<.read.split.map(&:to_i)
i=1
(k-=i;i+=1)while k>i
p a[k-1]

include Math

n,k = gets.split.map(&:to_i)
arr = gets.split.map(&:to_i)
val = ((-1 + sqrt(1+8*k))/2).ceil
ans = k - ((val-1)*val)/2

puts arr[ans-1]

n, k = readline.split(' ').collect(&:to_i)
arr = readline.split(' ').collect(&:to_i)
k -= 1
1.upto(n) do |x|
  if k >= x
    k -= x
  else
    puts arr[k]
    break
  end
end

a=gets.chomp.split.map{|i|i.to_i}
b=gets.chomp.split
if a[1]==1
puts "#{b[0]}"
else
n=1
loop do
p=(n*(n+1))/2
if p>=a[1]
n-=1
break
else
n+=1
end
end
a[1]-=((n*(n+1))/2)
puts"#{b[a[1]-1]}"
end

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

k1 = ((-1 + sqrt(1+8*k))/2).ceil
keq = k - ((k1-1)*k1)/2

# puts "k1 #{k1}"
# puts "k1(k1+1)/2 #{k1*(k1+1)/2}"
# puts "Number of ids in k1 robots turn #{(k1*(k1+1) - (k1-1)*k1)/2}"
# puts keq
puts arr_n[keq-1]

def f num
	((num + 1) * num) / 2
end

input = gets.chomp.split(' ').map { |i| i.to_i }
n, k = input[0], input[1]

ident = []

input = gets.chomp.split(' ').map { |i| i.to_i }

input.each do |i|
	ident << i
end

max = f(n)
nearest = 0

until f(nearest) >= k
	nearest += 1
end

nearest -= 1
k -= f(nearest)

#puts k
puts ident[k - 1] if k > 0
puts ident[0] if k <= 0

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

n,k = parse_int.call
nums = parse_int.call

i = 1
while true
  break if k-i<1

  k-=i
  i+=1

end

print nums[k-1]

def f num
	((num + 1) * num) / 2
end

input = gets.chomp.split(' ').map { |i| i.to_i }
n, k = input[0], input[1]

ident = []

input = gets.chomp.split(' ').map { |i| i.to_i }

input.each do |i|
	ident << i
end

max = f(n)
nearest = 0

until f(nearest) > k
	nearest += 1
end

nearest -= 1
k -= f(nearest)

puts input[k - 1]

input = gets.chomp.split(' ').map { |i| i.to_i }
n, k = input[0], input[1]

ident = []

input = gets.chomp.split(' ').map { |i| i.to_i }

input.each do |i|
	ident << i
end

target = 0

if k > n
	target = (k % n) - 1
	target = (n - 1) if target < 0
else
	target = k - 1
end

puts (n - target)


In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.Tzuyu gave Sana two integers $$$a$$$ and $$$b$$$ and a really important quest.In order to complete the quest, Sana has to output the smallest possible value of ($$$a \oplus x$$$) + ($$$b \oplus x$$$) for any given $$$x$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.

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 of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^{9}$$$).

For each testcase, output the smallest possible value of the given expression.

NoteFor the first test case Sana can choose $$$x=4$$$ and the value will be ($$$6 \oplus 4$$$) + ($$$12 \oplus 4$$$) = $$$2 + 8$$$ = $$$10$$$. It can be shown that this is the smallest possible value.

T = gets.to_i

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

  bl = [a.bit_length, b.bit_length].max
  x = 0

  bl.times do |i|
    if a[i] == 1 && b[i] == 1
      x |= (1 << i)
    end
  end

  puts (a ^ x) + (b ^ x)
end

t = gets.chomp.to_i
t.times do
  a, b = gets.chomp.split(' ').map(&:to_i)
  a_binary = a.to_s(2).reverse
  b_binary = b.to_s(2).reverse
  l = [a_binary.length, b_binary.length].min
  x = ""
  l.times do |i|
    if a_binary[i] == "1" && b_binary[i] == "1"
      x << "1"
    else
      x << "0"
    end
  end
  x = x.reverse.to_i(2)
  puts (a ^ x) + (b ^ x)
end

1.upto(gets.to_i){a,b=gets.split(' ').map(&:to_i)
puts a^b}

1.upto(gets.to_i){
  a,b=gets.split(' ').map(&:to_i)
  puts a^b
}

(1..(gets.to_i)).each{
  a,b=gets.split(' ').map(&:to_i)
  puts a^b
}

gets.to_i.times{a,b=gets.split(' ')
puts a.to_i^b.to_i}


You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is diverse.A garland is called diverse if any two adjacent (consecutive) lamps (i. e. such lamps that the distance between their positions is $$$1$$$) have distinct colors.In other words, if the obtained garland is $$$t$$$ then for each $$$i$$$ from $$$1$$$ to $$$n-1$$$ the condition $$$t_i \ne t_{i + 1}$$$ should be satisfied.Among all ways to recolor the initial garland to make it diverse you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

In the first line of the output print one integer $$$r$$$ — the minimum number of recolors needed to obtain a diverse garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ — a diverse garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

def solution
  read_int
  gs = read_string.chars

  colors = ["R", "G", "B"]

  moves = 0

  for i in (0...gs.size)
    prv = i > 0 ? gs[i - 1] : nil
    crt = gs[i]
    nxt = gs[i + 1]

    if prv == crt
      moves += 1
      gs[i] = colors.find { |c| c != prv && c != nxt }
    end

  end

  puts moves
  puts gs.join('')

end

def read_int
  gets.to_i
end

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

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

num = gets.to_i
colors = gets
possible_colors = ["R", "G", "B"]
colors = colors.split("")
num_possibilites = 0
(1..num).each do |index|
	color = colors[index]
	prev_color = colors[index-1] || ""
	next_color = colors[index+1] || ""
	if color == prev_color
		possibilites = (possible_colors-[prev_color, next_color])
		num_possibilites += 1
		colors[index] = possibilites.first
	end
end
puts num_possibilites
puts colors.join("")


Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.

The first line contains three integers h1, a1, c1 (1 ≤ h1, a1 ≤ 100, 2 ≤ c1 ≤ 100) — Vova's health, Vova's attack power and the healing power of a potion. The second line contains two integers h2, a2 (1 ≤ h2 ≤ 100, 1 ≤ a2 < c1) — the Modcrab's health and his attack power.

In the first line print one integer n denoting the minimum number of phases required to win the battle. Then print n lines. i-th line must be equal to HEAL if Vova drinks a potion in i-th phase, or STRIKE if he attacks the Modcrab. The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action. If there are multiple optimal solutions, print any of them.

NoteIn the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left.

line_one = $stdin.gets
line_two= $stdin.gets

h1, a1, c1 = line_one.split.map(&:to_i)
h2, a2 = line_two.split.map(&:to_i)

actions = Array.new
while h2 > 0
  if h1 > a2 || a1 >= h2
    actions << 'STRIKE'
    h2 -= a1
  else
    actions << 'HEAL'
    h1 += c1
  end
  h1 -= a2
end

puts actions.length
puts actions

h, a, c=gets.split.map &:to_i
g, b=gets.split.map &:to_i
res=[]
while g>0
    if h-b<=0 && g-a>0
        res<<"HEAL"
        h+=c
    else
        res<<"STRIKE"
        g-=a
    end
    h-=b
end
puts res.size, res

h,a,c=gets.split.map &:to_i
g,b=gets.split.map &:to_i
k=(g+a-1)/a
n=[(b*(k-1)-h)/(c-b)+1,0].max
puts n+k,[:HEAL]*n,[:STRIKE]*k

hac = gets.chomp.split.map(&:to_i)
h = hac[0]
a = hac[1]
c = hac[2]
ha = gets.chomp.split.map(&:to_i)
h2 = ha[0]
a2 = ha[1]

arr = []
while h2-a > 0
	if h - a2 > 0
		arr << "STRIKE"
		h2 -= a
	else
		arr << "HEAL"
		h += c
	end
	if h2 > 0
		h -= a2
	end
end

puts arr.size+1
for n in arr
	puts n
end
print "STRIKE"

#!/usr/bin/env ruby

h1, a1, c1 = gets.split.map{|x| x.to_i}
h2, a2 = gets.split.map{|x| x.to_i}

$cnt = 0
$moves = []
while h2 > 0 do
	$cnt += 1
	if h1 <= a2 and a1 < h2 then
		$moves.push("HEAL")
		h1 += c1
	else
		$moves.push("STRIKE")
		h2 -= a1
	end

	h1 -= a2
end

puts $cnt
puts $moves.join("\n")

h1, a1, c1 = gets.split.map(&:to_i)
h2, a2 = gets.split.map(&:to_i)
s = (h2 - 1) / a1
h = a2 * s < h1 ? 0 : (a2 * s - h1) / (c1 - a2) + 1
p s + h + 1
h.times {puts 'HEAL'}
(s + 1).times {puts 'STRIKE'}

line_one = $stdin.gets
line_two= $stdin.gets

h1, a1, c1 = line_one.split.map(&:to_i)
h2, a2 = line_two.split.map(&:to_i)

actions = Array.new
while h2 > 0
  if h1 > a2
    actions << 'STRIKE'
    h2 -= a1
  else
    actions << 'HEAL'
    h1 += c1
  end
  h1 -= a2
end

puts actions.length
puts actions

line_one = $stdin.gets
line_two= $stdin.gets

h1, a1, c1 = line_one.split.map(&:to_i)
h2, a2 = line_two.split.map(&:to_i)

actions = Array.new
while h2 > 0
  if h1 > a2
    actions << 'STRIKE'
    h2 -= a1
  else
    actions << 'HEAL'
    h1 += c1
  end
  if h2 <= 0
    break
  end
  h1 -= a2
end

puts actions.length
puts actions

h, a, c=gets.split.map &:to_i
g, b=gets.split.map &:to_i
res=[]
while g>0
    if h-b<=0
        res<<"HEAL"
        h+=c
    else
        res<<"STRIKE"
        g-=a
    end
    h-=b
end
puts res.size, res

hac = gets.chomp.split.map(&:to_i)
h = hac[0]
a = hac[1]
c = hac[2]
ha = gets.chomp.split.map(&:to_i)
h2 = ha[0]
a2 = ha[1]

arr = []
while h2 > 0
	if h - a2 > 0
		arr << "STRIKE"
		h2 -= a
		h -= a2
	else
		arr << "HEAL"
		h += c
		h -= a
	end
end

puts arr.size
for n in arr
	puts n
end

hac = gets.chomp.split.map(&:to_i)
h = hac[0]
a = hac[1]
c = hac[2]
ha = gets.chomp.split.map(&:to_i)
h2 = ha[0]
a2 = ha[1]

arr = []
while h2 > 0
	if h/a2 >= h2/a && h - a2 > 0
		arr << "STRIKE"
		h2 -= a
		h -= a2
	else
		arr << "HEAL"
		h += c
		h -= a2
	end
end

puts arr.size
for n in arr
	puts n
end

hac = gets.chomp.split.map(&:to_i)
h = hac[0]
a = hac[1]
c = hac[2]
ha = gets.chomp.split.map(&:to_i)
h2 = ha[0]
a2 = ha[1]

arr = []
while h2 > 0
	if h/a2 > h2/a || h - a2 > 0
		arr << "STRIKE"
		h2 -= a
		h -= a2
	else
		arr << "HEAL"
		h += c - a2
	end
end

puts arr.size
for n in arr
	puts n
end

#!/usr/bin/env ruby

h1, a1, c1 = gets.split.map{|x| x.to_i}
h2, a2 = gets.split.map{|x| x.to_i}

$cnt = 0
$moves = []
while h2 > 0 do
	$cnt += 1
	if h1 <= a2 then
		$moves.push("HEAL")
		h1 += c1
	else
		$moves.push("STRIKE")
		h2 -= a1
	end

	h1 -= a2
end

puts $cnt
puts $moves.join("\n")

h1, a1, c1 = gets.split.map(&:to_i)
h2, a2 = gets.split.map(&:to_i)
s = (h2 - 1) / a1
h = a2 * s < h1 ? 0 : (a2 * s - h1) / c1 + 1
p s + h + 1
h.times {puts 'HEAL'}
(s + 1).times {puts 'STRIKE'}


Tired of boring office work, Denis decided to open a fast food restaurant.On the first day he made $$$a$$$ portions of dumplings, $$$b$$$ portions of cranberry juice and $$$c$$$ pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases to solve. Each of the remaining $$$t$$$ lines contains integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \leq a, b, c \leq 10$$$) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.

For each test case print a single integer — the maximum number of visitors Denis can feed.

NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.

def Solve()
    a,b,c=gets.chomp.split.map(&:to_i).sort.reverse
    ans=0
    if a>=1
        ans+=1
        a-=1
    end
    if b>=1
        ans+=1
        b-=1
    end
    if c>=1
        ans+=1
        c-=1
    end

    if a>=1  && b>=1
        ans+=1
        a-=1
        b-=1
    end
    if b>=1 && c>=1
        ans+=1
        b-=1
        c-=1
    end
    if  c>=1 && a>=1
        ans+=1
        c-=1
        a-=1
    end

    if a>=1 && b>=1 && c>=1
        ans+=1
    end
    puts ans
end

gets.to_i.times do
    Solve()
end

def try_consume(a,b,c)
  return 0 if $a < a || $b < b || $c < c
  $a -= a
  $b -= b
  $c -= c
  1
end

def solve
  $a, $b, $c = gets.split.map{|x| x.to_i}.sort
  ans = 0
  ans += try_consume(1,0,0)
  ans += try_consume(0,1,0)
  ans += try_consume(0,0,1)
  ans += try_consume(1,0,1)
  ans += try_consume(0,1,1)
  ans += try_consume(1,1,0)
  ans += try_consume(1,1,1)
  puts ans
end

t = gets.to_i
t.times { solve }

require 'set'; require 'prime'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  a,b,c = gets.chomp.split.map(&:to_i).sort.reverse
  ans = 0
  if a > 0
    ans += 1
    a-=1
  end
  if b > 0
    ans += 1
    b-=1
  end
  if c > 0
    ans += 1
    c-=1
  end

  if a > 0 && b > 0
    ans += 1
    a-=1
    b-=1
  end
  if a > 0 && c > 0
    ans += 1
    a-=1
    c-=1
  end
  if b > 0 && c > 0
    ans += 1
    b-=1
    c-=1
  end

  if a > 0 && b > 0 && c > 0
    ans += 1
  end
  puts ans
end

T = gets.to_i

T.times do
  a, b, c = gets.split.map(&:to_i)

  cnt = 0

  if a > 0
    a -= 1
    cnt += 1
  end

  if b > 0
    b -= 1
    cnt += 1
  end

  if c > 0
    c -= 1
    cnt += 1
  end

  nums = [a, b, c].sort

  if nums[0] > 0 && nums[2] > 0
    nums[0] -= 1
    nums[2] -= 1
    cnt += 1
  end

  if nums[1] > 0 && nums[2] > 0
    nums[1] -= 1
    nums[2] -= 1
    cnt += 1
  end

  if nums[0] > 0 && nums[1] > 0
    nums[0] -= 1
    nums[1] -= 1
    cnt += 1
  end

  if nums.all? { |n| n > 0 }
    cnt += 1
  end

  puts cnt
end

t = gets.to_i
t.times do
  ans = 0
  a, b, c = gets.split.map(&:to_i).sort.reverse
  if a >= 1
    ans += 1
    a -= 1
  end
  if b >= 1
    ans += 1
    b -= 1
  end
  if c >= 1
    ans += 1
    c -= 1
  end
  if a >= 1 && b >= 1
    ans += 1
    a -= 1
    b -= 1
  end
  if b >= 1 && c >= 1
    ans += 1
    b -= 1
    c -= 1
  end
  if c >= 1 && a >= 1
    ans += 1
    c -= 1
    a -= 1
  end
  if a >= 1 && b >= 1 && c >= 1
    ans += 1
    a -= 1
    b -= 1
    c -= 1
  end
  puts ans
end

t = gets.to_i
t.times do
  d = gets.chomp.split.map(&:to_i).sort.reverse

  ans = 0
  [1, 2, 4, 3, 5, 6, 7].each do |i|
    f = true
    3.times do |j|
      if i & (1 << j) > 0 && d[j] == 0
        f = false
        break
      end
    end

    if f
      ans += 1

      3.times do |j|
        d[j] -= 1 if i & (1 << j) > 0
      end
    end
  end
  puts ans
end


Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li], a[li + 1], ..., a[ri].Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.The mex of a set S is a minimum possible non-negative integer that is not in S.

The first line contains two integers n and m (1 ≤ n, m ≤ 105). The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), that describe the subarray a[li], a[li + 1], ..., a[ri].

In the first line print single integer — the maximum possible minimum mex. In the second line print n integers — the array a. All the elements in a should be between 0 and 109. It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109. If there are multiple solutions, print any of them.

NoteThe first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2.

n, m = gets.chomp.split(" ").map(&:to_i)
x = 1000000000
for i in 0..m-1
  li, ri = gets.chomp.split(" ").map(&:to_i)
  x = [ri - li+1, x].min
end
puts x
for i in 0..n-1
  print (i%x), " "
end

# be name khoda ...
def read_ints; STDIN.gets.split.map(&:to_i); end
n,m = read_ints
a = Array.new
min = -1
m.times{
  l,r = read_ints
  if(min == -1 || r - l + 1 < min)
    min = r-l+1
  end
}
puts min
cur = 0
n.times {
  if(cur >= min)
    cur = 0
  end
  print "#{cur} "
  cur+=1
}

n, m = gets.chomp.split(" ").map(&:to_i)
x = 1000000000
for i in 0..m-1
  li, ri = gets.chomp.split(" ").map(&:to_i)
  x = [ri - li+1, x].min
end
puts x
for i in 0..n-1
  print (i%x)
end


You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai, bi). How many operations will be performed for each of them?

The first line contains the number of pairs n (1  ≤  n  ≤  1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1  ≤  ai,  bi  ≤  109).

Print the sought number of operations for each pair on a single line.

def num (a, b)
    result = 0
    while a > 0 && b > 0 do
        if b > a then
            result += b/a
            b -= b - (b % a)
        else
            result += a/b
            a -= a - (a % b)
        end
    end
    return result
end

n = gets.to_i

pair = []
n.times do |i|
    pair << gets.split.map{|j| j.to_i}
end

n.times do |i|
    result = num(pair[i][0],pair[i][1])
    puts result
end

n = gets.to_i
n.times do
  num = 0
  a = gets.split.map(&:to_i)
  a.reverse! if a[0] > a[1]
  until a[0] == 0
    num += a[1]/a[0]
    a[1] %= a[0]
    a.reverse!
  end
  puts num
end

def run
  n = ARGF.readline
  ARGF.readlines.each do |s|
    a, b = s.chomp.split.map(&:to_i)

    cnt = 0
    while a > 0 and b > 0
      a, b = b, a if a > b
      cnt += b / a
      b = b % a
    end

    puts cnt
  end
end

run if $0 == __FILE__

n = gets.chomp.to_i
(1..n).each { |k|
	a,b = gets.chomp.split(" ").collect! {|x| x.to_i}
	p = 0
	if a<b
		aux = a
		a = b
		b = aux
	end
	while a>0 and b>0
		p += a/b
		aux = a%b
		a = b
		b = aux
	end
	puts p
}

gets.to_i.times {
  a,b=gets.split.map(&:to_i)
  a,b=[a,b].min,[a,b].max

  count=0
  while a!=0
    count+=b/a;
    a,b=b%a,a
  end
  puts count
}

def solve(a,b)
	return 0 if a == 0 or b == 0
	return solve(b,a) if a > b
	b/a + solve(b % a, a)
end

gets.to_i.times do
	a, b = gets.split.map(&:to_i)
	puts solve(a,b)
end

n = gets.to_i

n.times do |i|
	t = gets.split.collect{|x| x.to_i}

	a = t.max
	b = t.min
	i = 0
	while a > 0 and b > 0
		i+=a / b
		k = a%b
		a = [k,b].max
		b = [k,b].min
	end
	puts i
end


Polycarp wrote on a whiteboard an array $$$p$$$ of length $$$n$$$, which is a permutation of numbers from $$$1$$$ to $$$n$$$. In other words, in $$$p$$$ each number from $$$1$$$ to $$$n$$$ occurs exactly once.He also prepared a resulting array $$$a$$$, which is initially empty (that is, it has a length of $$$0$$$).After that, he did exactly $$$n$$$ steps. Each step looked like this:  Look at the leftmost and rightmost elements of $$$p$$$, and pick the smaller of the two. If you picked the leftmost element of $$$p$$$, append it to the left of $$$a$$$; otherwise, if you picked the rightmost element of $$$p$$$, append it to the right of $$$a$$$. The picked element is erased from $$$p$$$. Note that on the last step, $$$p$$$ has a length of $$$1$$$ and its minimum element is both leftmost and rightmost. In this case, Polycarp can choose what role the minimum element plays. In other words, this element can be added to $$$a$$$ both on the left and on the right (at the discretion of Polycarp).Let's look at an example. Let $$$n=4$$$, $$$p=[3, 1, 4, 2]$$$. Initially $$$a=[]$$$. Then: During the first step, the minimum is on the right (with a value of $$$2$$$), so after this step, $$$p=[3,1,4]$$$ and $$$a=[2]$$$ (he added the value $$$2$$$ to the right).  During the second step, the minimum is on the left (with a value of $$$3$$$), so after this step, $$$p=[1,4]$$$ and $$$a=[3,2]$$$ (he added the value $$$3$$$ to the left).  During the third step, the minimum is on the left (with a value of $$$1$$$), so after this step, $$$p=[4]$$$ and $$$a=[1,3,2]$$$ (he added the value $$$1$$$ to the left).  During the fourth step, the minimum is both left and right (this value is $$$4$$$). Let's say Polycarp chose the right option. After this step, $$$p=[]$$$ and $$$a=[1,3,2,4]$$$ (he added the value $$$4$$$ to the right).Thus, a possible value of $$$a$$$ after $$$n$$$ steps could be $$$a=[1,3,2,4]$$$.You are given the final value of the resulting array $$$a$$$. Find any possible initial value for $$$p$$$ that can result the given $$$a$$$, or determine that there is no solution.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Each test case consists of two lines. The first of them contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the elements of the array $$$a$$$. All elements of the $$$a$$$ array are distinct numbers. It is guaranteed that the sum of the values $$$n$$$ over all test cases in the test does not exceed $$$2\cdot10^5$$$.

Print $$$t$$$ lines, each of the lines must contain the answer to the corresponding set of input data: numbers $$$p_1, p_2, \dots, p_n$$$  — any of the possible initial values of the array $$$p$$$, which will lead to the given array $$$a$$$. All elements of $$$p$$$ are distinct integers from $$$1$$$ to $$$n$$$. Thus, if there are several solutions, print any. If there is no solution, then print -1 on the line.

NoteThe first test case in the example is clarified in the main section of the problem statement. There may be other correct answers for this test set.In the second test case, $$$n=1$$$. Thus, there is only one permutation that can be the answer: $$$p=[1]$$$. Indeed, this is the answer to this test case.In the third test case of the example, no matter what permutation you take as $$$p$$$, after applying the $$$n$$$ steps, the result will differ from $$$a=[1, 3, 5, 4, 2]$$$.

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  a = gets.chomp.split(" ").map(&:to_i)
  b = []
  if a[0] == n
    1.upto(n-1) do |i|
      b << a[i]
    end
    b.reverse!
    b.unshift(a[0])
  elsif a[-1] == n
    0.upto(n-2) do |i|
      b << a[i]
    end
    b.reverse!
    b << a[-1]
  end
  if b.size == n
    ans << b
  else
    ans << [-1]
  end
end
ans.each do |arr|
  puts arr.join(" ")
end


You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the description of $$$t$$$ testcases follow. The first line of each test case contains three integers $$$n$$$, $$$x$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$). Each of next $$$m$$$ lines contains the descriptions of the operations; the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).

For each test case print one integer — the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

NoteIn the first test case, it is possible to achieve $$$a_k = 1$$$ for every $$$k$$$. To do so, you may use the following operations:  swap $$$a_k$$$ and $$$a_4$$$;  swap $$$a_2$$$ and $$$a_2$$$;  swap $$$a_5$$$ and $$$a_5$$$. In the second test case, only $$$k = 1$$$ and $$$k = 2$$$ are possible answers. To achieve $$$a_1 = 1$$$, you have to swap $$$a_1$$$ and $$$a_1$$$ during the second operation. To achieve $$$a_2 = 1$$$, you have to swap $$$a_1$$$ and $$$a_2$$$ during the second operation.

gets.to_i.times do
    n, x, m = gets.split.map(&:to_i)
    rg, lf = x, x
    (0...m).each do |i|
        l, r = gets.split.map(&:to_i)
        if [l, lf].max <= [r, rg].min
            lf, rg = [lf, l].min, [rg, r].max
        end
    end
    puts rg - lf + 1
end


Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.

Output the minimum length of the string that may remain after applying the described operations several times.

NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .

gets
s=gets
p (s.count('0')-s.count('1')).abs

# your code goes here

n = gets.to_i
s = gets.chomp

a = 0
i = 0

while i<n do
	if s[i]=='0'
		a += 1
	else
		a -= 1
	end

	i += 1
end

puts "#{a.abs}"

n = gets.to_i
arr = gets.split('')
stac = []
arr.each do |a|
    if a == '1'
        if stac.last == '0'
            stac.pop
        else
            stac.push(a)
        end
    elsif a == '0'
        if stac.last == '1'
            stac.pop
        else
            stac.push(a)
        end
    end
end
puts stac.size

# http://codeforces.com/contest/556/problem/A
n = gets.chomp.to_i
digits = gets.chomp.chars.map { |d| d == '0' ? 1 : -1 }

puts digits.inject(0, :+).abs

n = gets.to_i
s = gets.chomp.to_s.split(//)

xounter = 0
counter = 0
s.each do |x|
    if x == "0"
        counter+=1
    else
        xounter+=1
    end
end
puts (counter-xounter).abs

n = gets.to_i
s = gets.chomp.to_s.split(//)

counter = 0
s.each do |x|
    if x == "0"
        counter+=1
    else
        counter-=1
    end
end
puts counter.abs

n = gets.to_i
s = gets
ans = 0
n.times { |i|
  if s[i] == '0'
    ans +=1
  else
    ans -= 1
  end
}
if ans < 0
  ans = -ans
end
print ans

gets
a=gets.chomp.chars
b=[]
ans=a.size
while !a.empty?
	while !b.empty? && !a.empty?
		if (b.last!=a[0]) then
			ans-=2
			b.pop
			a.shift
		else
			break
		end
	end
	b.push(a.shift)
end
puts ans

t = gets.chomp.to_i
s = gets.chomp

puts t - (2*[s.count('0'),s.count('1')].min)

def read_ints; gets.chomp.split.map(&:to_i) end
n = read_ints[0]
line = gets.chars
ones = line.count("1")
zeros = line.count("0")
puts (ones-zeros).abs

n = gets.to_i
a = gets.each_char.count{|i| i == '1'}
puts n - [ a , n - a].min * 2

length = gets.chomp.to_i
s = gets.chomp
string = s.split("")

# while string.include?('1') && string.include?('0')
# 	for i in (0..string.size-1)
# 		if i != string.size-1
# 			if (string[i].to_i == 0 && string[i+1].to_i == 1) || (string[i].to_i == 1 && string[i+1].to_i == 0)
# 				string.delete_at(i)
# 				string.delete_at(i+1)
# 			end
# 		end
# 	end
# end

if string.count('1') != 0 && string.count('0') != 0 && length > 1
	if string.count('0') == string.count('1')
		puts 0
	elsif string.count('0') > string.count('1')
		length = length - (string.count('1') * 2)
		puts length
	else
		length = length - (string.count('0') * 2)
		puts length
	end
elsif (string.count('1') == 0 || string.count('0') == 0) && length > 1
	puts length
elsif length <= 1
	puts length
end

len = gets.to_i
s = gets

a = 0
b = 0

for i in (0...len)
	s[i] == "0" ? a += 1 : b += 1
end

puts len - 2 * [a, b].min

gets
s = gets.chomp

puts (s.count('1') - s.count('0')).abs

n = gets.chomp.to_i
str = gets.chomp

one = 0
zero = 0

for i in (0..str.length-1)
        if str[i] == "0"
                zero += 1
                else
                one += 1
                end
                end

                puts (one-zero).abs

stringLength = gets.chomp.to_i
string = gets.chomp.split('')

zero = 0
one = 0

string.each do |item|
	if item == '1'
		one += 1
	else
		zero += 1
	end
end

puts stringLength - 2 * [zero, one].min

n = gets.to_i
str = gets.chomp.gsub(/10/,'x').gsub(/01/,'x')
puts n - 2 * str.scan(/x/).size

length = gets.chomp.to_i
s = gets.chomp
string = s.split("")

# while string.include?('1') && string.include?('0')
# 	for i in (0..string.size-1)
# 		if i != string.size-1
# 			if (string[i].to_i == 0 && string[i+1].to_i == 1) || (string[i].to_i == 1 && string[i+1].to_i == 0)
# 				string.delete_at(i)
# 				string.delete_at(i+1)
# 			end
# 		end
# 	end
# end

if string.count('1') != 0 && string.count('0') != 0
	if string.count('0') == string.count('1')
		puts 0
	elsif string.count('0') > string.count('1')
		length = length - (string.count('1') * 2)
		puts length
	else
		length = length - (string.count('0') * 2)
		puts length
	end
end

stringLength = gets.chomp.to_i
string = gets.chomp.split('')

i = 0

until i == string.length || string.length < 2
#	puts i
#	puts string.length

	if string[i] != string[i + 1]
		2.times {string.delete_at(i)}
		i -= 1
	end

	i += 1
end

puts string.length


As you know, Hogwarts has four houses: Gryffindor, Hufflepuff, Ravenclaw and Slytherin. The sorting of the first-years into houses is done by the Sorting Hat. The pupils are called one by one in the alphabetical order, each of them should put a hat on his head and, after some thought, the hat solemnly announces the name of the house the student should enter.At that the Hat is believed to base its considerations on the student's personal qualities: it sends the brave and noble ones to Gryffindor, the smart and shrewd ones — to Ravenclaw, the persistent and honest ones — to Hufflepuff and the clever and cunning ones — to Slytherin. However, a first year student Hermione Granger got very concerned about the forthcoming sorting. She studied all the literature on the Sorting Hat and came to the conclusion that it is much simpler than that. If the relatives of the student have already studied at Hogwarts, the hat puts the student to the same house, where his family used to study. In controversial situations, when the relatives studied in different houses or when they were all Muggles like Hermione's parents, then the Hat sorts the student to the house, to which the least number of first years has been sent at that moment. If there are several such houses, the choice is given to the student himself. Then the student can choose any of the houses, to which the least number of first years has been sent so far. Hermione has already asked the students that are on the list before her about their relatives. Now she and her new friends Harry Potter and Ron Weasley want to find out into what house the Hat will put Hermione.

The first input line contains an integer n (1 ≤ n ≤ 10000). It is the number of students who are in the list before Hermione. The next line contains n symbols. If all the relatives of a student used to study in the same house, then the i-th character in the string coincides with the first letter of the name of this house. Otherwise, the i-th symbol is equal to "?".

Print all the possible houses where Hermione can be sent. The names of the houses should be printed in the alphabetical order, one per line.

NoteConsider the second example. There are only two students before Hermione. The first student is sent to Hufflepuff. The second disciple is given the choice between the houses where the least number of students has been sent, i.e. Gryffindor, Slytherin and Ravenclaw. If he chooses Gryffindor, Hermione is forced to choose between Ravenclaw and Slytherin, if he chooses Ravenclaw, Hermione will choose between Gryffindor and Slytherin, if he chooses Slytherin, Hermione will choose between Gryffindor and Ravenclaw. In the end, the following situation is possible (it depends on the choice of the second student and Hermione). Hermione will end up 1) in Gryffindor, 2) in Ravenclaw, 3) in Slytherin. Note that, despite the fact that in neither case Hermione will be given a choice between all the three options, they are all possible and they should all be printed in the answer. Hermione will not, under any circumstances, end up in Hufflepuff.

require 'set'

p = [71, 72, 82, 83]
n = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]

s = Set.new [[0, 0, 0, 0]]
gets
gets.chomp.each_byte do |c|
   t = Set.new
   s.each do |a|
      if c == 63
         for i in (0..3).select { |y| a[y] == a.min }
            b = a.clone
            b[i] += 1
            t << b
         end
      else
         a[p.index(c)] += 1
         t << a
      end
   end

   s = t
end
for i in (0..3)
    puts n[i] if s.any? {|a| a[i] == a.min}
end

require 'set'

p = [71, 72, 82, 83, 63]
n = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]

s = Set.new [[0, 0, 0, 0]]
gets
gets.each_byte do |c|
   t = Set.new []
   next if !p.include?(c)
   s.each do |a|
      if c == 63
         for i in (0..3)
            if a[i] == a.min
               b = Array.new(a)
               b[i] += 1
               t << b
            end
         end
      else
         a[p.index(c)] += 1
         t << a
      end
   end

   s = t
end
for i in (0..3)
    puts n[i] if s.any? {|a| a[i] == a.min}
end

require 'set'

p = [71, 72, 82, 83]
n = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]

s = Set.new [[0, 0, 0, 0]]
gets
gets.chomp.each_byte do |c|
   t = Set.new []
   s.each do |a|
      if c == 63
         for i in (0..3)
            if a[i] == a.min
               b = Array.new(a)
               b[i] += 1
               t << b
            end
         end
      else
         a[p.index(c)] += 1
         t << a
      end
   end

   s = t
end
for i in (0..3)
    puts n[i] if s.any? {|a| a[i] == a.min}
end


Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by hk - hk + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers h1, h2, ..., hn (1  ≤  hi  ≤  105) representing the heights of the pylons.

Print a single number representing the minimum number of dollars paid by Caisa.

NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.

n, *a = gets(p).split.map(&:to_i)
puts a.max

n=gets
x=gets.split.map{|e| e.to_i}
x.shift(0)
sum=0
ans=0
x.inject(0){|e1,e2|
	sum+=(e2-e1)
	if sum>0 then
		ans+=sum
		sum=0
	end
	e2
}
puts ans

n = gets.to_i
h = gets.split.map{|s| s.to_i}

puts h.max

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

e = 0
cost = 0
last_h = 0

gets.chomp.split(' ').each do |s|
  h = s.to_i
  de = last_h - h + e
  if de < 0
    cost += de.abs
    e += de.abs
  end
  e += last_h - h
  last_h = h
end

puts cost

# coding: utf-8

# if __FILE__ == 0
# end

n = gets.to_i
prev = 0
energy = 0
peak = 0
gets.split.map { |i|
    i = i.to_i
    energy += prev - i
    if energy < peak
        peak = energy
    end
    prev = i
}
if peak < 0
    puts -peak
else
    puts 0
end

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

# $stdin = File.new('rf','r')

n = readline.chomp.to_i
a = [0] + readline.chomp.split(' ').map(&:to_i)
e,m = 0,0

loop do
  cur, nex = a.shift, a.first
  if e < nex - cur
    m += nex - cur - e
    e += nex - cur - e
  end
  e += cur - nex
  break if a.size == 1
end

puts m

n = gets.to_i

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

puts a.max

r = s = d = 0
gets.to_i
gets.chomp.split.map(&:to_i).each { |x|
  d += r - x
  if d < 0
    s -= d
    d = 0
  end
  r = x
}
puts s

#!/usr/bin/env ruby

n = Integer(gets)

h= gets.chomp.split(" ").map(&:to_i)
dollars = 0
h.each do |h|
	dollars = [dollars, h].max
end

puts dollars

#!/usr/bin/env ruby

n = Integer(gets)

h= gets.chomp.split(" ").map(&:to_i)
energy = 0
dollars = 0
c_h = 0
h.each do |h|
	energy+= c_h - h
	c_h = h
	dollars+=[0,energy].min.abs
	energy=[0,energy].max
end

puts dollars

n = gets.to_i
a = gets.split.map { |x| x.to_i }
puts a.max

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

#!/usr/bin/ruby

n = STDIN.readline.to_i
heights = STDIN.readline.split.collect {|s| s.to_i }
heights.unshift(0)

boost, energy = 0, 0
(1..n).each do |pos|
	energy -= heights[pos] - heights[pos-1]
	if energy < 0
		boost -= energy
		energy = 0
	end
end

puts boost

require 'pp'

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

puts m.max

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

gets
arr = gets.split.map { |x| x.to_i }
k = arr.first
arr.shift
arr.each do |x|
  k += (x - k) if k < x
end
puts k

n=gets
x=gets.split.map{|e| e.to_i}
x.shift(0)
sum=0
x.inject(0){|e1,e2|
	sum+=(e2-e1)
	e2
}
puts sum

# coding: utf-8

# if __FILE__ == 0
# end

n = gets.to_i
prev = 0
energy = 0
gets.split.map { |i|
    i = i.to_i
    energy += prev - i
    prev = i
}
if energy < 0
    puts -energy
else
    puts 0
end

# coding: utf-8

# if __FILE__ == 0
# end

n = gets.to_i
prev = 0
energy = 0
gets.split.map { |i|
    i = i.to_i
    energy += prev - i
    prev = i
}

puts energy

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

# $stdin = File.new('rf','r')

n = readline.chomp.to_i
a = [0] + readline.chomp.split(' ').map(&:to_i)
e = 0

loop do
  e += a.shift - a.first
  break if a.size == 1
end

puts [0, -e].max

gets.to_i
puts -gets.chomp.split.map(&:to_i).inject([0, 0]) { |a, x| a[0] += a[1] - x; a[1] = x; a }[0]

n = gets.split
puts gets.split.map(&:to_s).max


The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^6$$$), where $$$p_i$$$ — the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \le y_i \le x_i \le n$$$) — the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.

For each query, print a single integer — the maximum total value of items received for free for one purchase.

NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$.

n, q = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i).sort.reverse
sums = [0]
ps.each { |p| sums << p + sums.last }
rs = []
q.times do
  x, y = gets.split.map(&:to_i)
  rs << sums[x] - sums[x - y]
end
puts rs.join("\n")

n, q = gets.split.map &:to_i
p = gets.split.map(&:to_i).sort
blah = 0
prefix_sum = []
for i in (0...p.size)
  blah += p[i]
  prefix_sum.push(blah)
end
q.times{
  x, y = gets.split.map &:to_i
  if x == n
    puts prefix_sum[-x+y-1]
  else
    puts prefix_sum[-x+y-1] - prefix_sum[-x-1]
  end
}

def solve(cs, x, y)
   cs[-x + y - 1] - cs[-x - 1]
end

n, q = gets.chomp.split.map(&:to_i)
xs = gets.chomp.split.map(&:to_i).sort
cs = [0]
xs.each do |x|
    cs << x + cs[-1]
end

results = []

q.times do
    x, y = gets.chomp.split.map(&:to_i)
    results << solve(cs, x, y)
end

puts results

n, q = gets.split.map(&:to_i)
p = gets.split.map(&:to_i).sort
i = 0
psum = p.map{|e| i+=e }
psum.unshift(0)

q.times do
  x, y = gets.split.map(&:to_i)

  puts psum[n-x+y] - psum[n-x]
end

n,q = gets.chomp.split.map(&:to_i)
p = gets.chomp.split.map(&:to_i).sort
c = [p[0]]
1.upto(n-1) do |i|
  c[i] = c[i-1] + p[i]
end
#puts c.inspect
q.times do
  x,y = gets.chomp.split.map(&:to_i)
  #puts c[n-x+y-1]
  #puts c[n-x-1]
  puts c[n-x+y-1] - (n-x-1 >= 0 ? c[n-x-1] : 0)
end


Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.

The first line contains four integers n, k, a and b (1 ≤ k ≤ n ≤ 105, 0 ≤ a, b ≤ n) — the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n.

If it is impossible to drink n cups of tea, print "NO" (without quotes). Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them.

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

inverse = false
a = []
if g < b
  inverse = true
  g, b = b, g
end

if (b + 1) * k < g
  puts "NO"
  exit
end

while g != b and b > 0
  cnt = [k, g - (b - 1)].min
  g -= cnt
  b -= 1
  cnt.times {a.push(true)}
  a.push(false)
end

while g > 0
  g -= 1
  a.push(true)
  if b > 0
    b -= 1
    a.push(false)
  end
end

if inverse
  a.map!(&:!)
end

puts a.map {|x| x ? 'G' : 'B'}.join

n, k, a, b = gets.chomp.split(" ").map(&:to_i)
s = ''
if a<=b
  ctr = 1
else
  ctr = -1
end
a1 = [a,b].min # a1 = b
b1 = [a,b].max #
if b1 > k*(a1+1)
  print "NO"
else
  while(b1 - a1 > k)
    if (ctr == 1)
      s = s + "B"*k + "G"
    else
      s = s + "G"*k + "B"
    end
    b1-=k
    a1-=1
  end
  if ctr == 1
    s += "B"*(b1-a1)
    s += "GB"*a1
  else
    s += "G"*(b1-a1)
    s +="BG"*a1
  end
  puts s
end

n,k,a,b=gets.split.map &:to_i
x=?G
y=?B
x,y,a,b=y,x,b,a if a>b

q=[b,k].min

r=[]
i=0
while b>0
    if i.even?
        t=[b, q].min
        r<<y*t
        b-=t
    else
        r<<x if a>0
        a-=1
    end
    i+=1
end

if a<0
    puts "NO"
else
    if a>0
        r<<x
        a-=1
    end
    i=1
    while a>0
        r[i]+=x
        if r[i].size>k
            puts a
            r="NO"
            break
        end
        a-=1
        i+=2
        i=1 if i>=r.size
    end
    puts (r=="NO" ? r : r*'')
end

n,k,a,b=gets.split.map &:to_i
x=?G
y=?B
x,y,a,b=y,x,b,a if a>b

q=[b,k].min
p=[[a/(b/q), 1].max, a, k].min

r=''
i=0
while a>0 or b>0
    if i.even?
        t=[b, q].min
        r<<y*t
        b-=t
    else
        t=[a, p].min
        r<<x*t
        a-=t
    end
    i+=1
end
if r.include?(x*(k+1)) or r.include?((y*(k+1)))
    puts "NO"
else
    puts r
end

n,k,a,b=gets.split.map &:to_i
x=?G
y=?B
x,y,a,b=y,x,b,a if a>b

q=[b,k].min

r=[]
i=0
while b>0
    if i.even?
        t=[b, q].min
        r<<y*t
        b-=t
    else
        r<<x if a>0
        a-=1
    end
    i+=1
end
if a<0
    puts "NO"
else
    if a>0
        r<<x
        a-=1
    end
    i=1
    while a>0
        r[i] << x
        if r[i].size>k
            r="NO"
            break
        end
        a-=1
        i=(i+2) % r.size
    end
    puts (r=="NO" ? r : r*'')
end