Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes.

Output one integer — the maximal possible distance between time periods.

NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0.

n=gets.chomp.to_i
chess_start=[]
chess_end=[]
n.times do
    time=gets.chomp.split
    #puts "#{time[0]} #{time[1]}"
    chess_start<<time[0].to_i
    chess_end<<time[1].to_i
end
chess_start.sort!
chess_end.sort!
#puts chess_start.join(" ")
#puts chess_end.join(" ")
program_start=[]
program_end=[]
m=gets.chomp.to_i
m.times do
    time=gets.chomp.split
    #puts "#{time[0]} #{time[1]}"
    program_start<<time[0].to_i
    program_end<<time[1].to_i
end
program_start.sort!
program_end.sort!
#puts program_start.join(" ")
#puts program_end.join(" ")

rest=program_start[-1] - chess_end[0]
#puts "program maxest start time=#{program_start[-1]} chess minest end time=#{chess_end[0]}"
#puts "chess maxest start time=#{chess_start[-1]} program minest end time=#{program_end[0]}"
if chess_start[-1]-program_end[0] > rest
    rest = chess_start[-1]-program_end[0]
end
if rest < 0
    puts 0
else
    puts rest
end

n = gets.to_i
nt = n.times.map{gets.split.map(&:to_i)}
m = gets.to_i
mt = m.times.map{gets.split.map(&:to_i)}
mx = 0
mx = [mt.max_by{|l, r| l}[0] - nt.min_by{|l, r| r}[1], mx].max
mx = [nt.max_by{|l, r| l}[0] - mt.min_by{|l, r| r}[1], mx].max
p mx

n = gets.to_i

chess = []

n.times do
  chess << gets.strip.split(' ').map(&:to_i)
end

m = gets.to_i

prog = []

m.times do
  prog << gets.strip.split(' ').map(&:to_i)
end

chess.sort! { |x,y| x[1] <=> y[1] }
prog.sort! { |x,y| y[0] <=> x[0] }

max_diff = 0

# chess.each do |c|
#   prog.each do |p|
#     break if c[0] - p[1] <= 0 && p[0] - c[1] <= 0
#     break if c[0] - p[1] <= max_diff && p[0] - c[1] <= max_diff
#     max_diff = [c[0] - p[1], max_diff].max
#     max_diff = [p[0] - c[1], max_diff].max
#   end
# end

# puts max_diff

lowest_in_chess = chess[0][1]
highest_in_prog = prog[0][0]
max_diff = [highest_in_prog - lowest_in_chess, max_diff].max

chess.sort! { |x,y| y[0] <=> x[0] }
prog.sort! { |x,y| x[1] <=> y[1] }
highest_in_chess = chess[0][0]
lowest_in_prog = prog[0][1]

max_diff = [highest_in_chess - lowest_in_prog, max_diff].max

puts max_diff

def f()
  lo, hi = 10**9, 0
  gets.to_i.times do
    l, r = gets.split.map { |s| s.to_i }
    if lo > r
      lo = r
    end
    if hi < l
      hi = l
    end
  end
  return lo, hi
end

a, b = f
c, d = f
p [0, b - c, d - a].max

def f()
  lo, hi = 10**9, 0
  gets.to_i.times do
    l, r = gets.split.map(&:to_i)
    if lo > r
      lo = r
    end
    if hi < l
      hi = l
    end
  end
  return lo, hi
end

a, b = f
c, d = f
p [0, b - c, d - a].max

n = gets.to_i

chess = []

n.times do
  chess << gets.strip.split(' ').map(&:to_i)
end

m = gets.to_i

prog = []

m.times do
  prog << gets.strip.split(' ').map(&:to_i)
end

chess.sort! { |x,y| x[0] <=> y[0] }
prog.sort! { |x,y| y[0] <=> x[0] }

max_diff = 0

chess.each do |c|
  prog.each do |p|
    break if p[0] <= c[1]
    max_diff = [c[1] - p[0], max_diff].max
    max_diff = [p[0] - c[1], max_diff].max
  end
end

puts max_diff


It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right.Unfortunately, Joe didn't switch the last security system off. On the plus side, he knows the way it works.Every minute the security system calculates the total amount of diamonds for each two adjacent cells (for the cells between whose numbers difference equals 1). As a result of this check we get an n - 1 sums. If at least one of the sums differs from the corresponding sum received during the previous check, then the security system is triggered.Joe can move the diamonds from one cell to another between the security system's checks. He manages to move them no more than m times between two checks. One of the three following operations is regarded as moving a diamond: moving a diamond from any cell to any other one, moving a diamond from any cell to Joe's pocket, moving a diamond from Joe's pocket to any cell. Initially Joe's pocket is empty, and it can carry an unlimited amount of diamonds. It is considered that before all Joe's actions the system performs at least one check.In the morning the bank employees will come, which is why Joe has to leave the bank before that moment. Joe has only k minutes left before morning, and on each of these k minutes he can perform no more than m operations. All that remains in Joe's pocket, is considered his loot.Calculate the largest amount of diamonds Joe can carry with him. Don't forget that the security system shouldn't be triggered (even after Joe leaves the bank) and Joe should leave before morning.

The first line contains integers n, m and k (1 ≤ n ≤ 104, 1 ≤ m, k ≤ 109). The next line contains n numbers. The i-th number is equal to the amount of diamonds in the i-th cell — it is an integer from 0 to 105.

Print a single number — the maximum number of diamonds Joe can steal.

NoteIn the second sample Joe can act like this:The diamonds' initial positions are 4 1 3.During the first period of time Joe moves a diamond from the 1-th cell to the 2-th one and a diamond from the 3-th cell to his pocket.By the end of the first period the diamonds' positions are 3 2 2. The check finds no difference and the security system doesn't go off.During the second period Joe moves a diamond from the 3-rd cell to the 2-nd one and puts a diamond from the 1-st cell to his pocket.By the end of the second period the diamonds' positions are 2 3 1. The check finds no difference again and the security system doesn't go off.Now Joe leaves with 2 diamonds in his pocket.

n, m, k = gets.split.map(&:to_i)
if n.even?
	b = 0
else
	a = gets.split.map(&:to_i)
	b = m / ((n + 1) / 2) * k
	a.each_with_index do |j, i|
		b = [b, j].min if i.even?
	end
end
puts b


On a random day, Neko found $$$n$$$ treasure chests and $$$m$$$ keys. The $$$i$$$-th chest has an integer $$$a_i$$$ written on it and the $$$j$$$-th key has an integer $$$b_j$$$ on it. Neko knows those chests contain the powerful mysterious green Grapes, thus Neko wants to open as many treasure chests as possible.The $$$j$$$-th key can be used to unlock the $$$i$$$-th chest if and only if the sum of the key number and the chest number is an odd number. Formally, $$$a_i + b_j \equiv 1 \pmod{2}$$$. One key can be used to open at most one chest, and one chest can be opened at most once.Find the maximum number of chests Neko can open.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^5$$$) — the number of chests and the number of keys. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the numbers written on the treasure chests. The third line contains $$$m$$$ integers $$$b_1, b_2, \ldots, b_m$$$ ($$$1 \leq b_i \leq 10^9$$$) — the numbers written on the keys.

Print the maximum number of chests you can open.

NoteIn the first example, one possible way to unlock $$$3$$$ chests is as follows:  Use first key to unlock the fifth chest,  Use third key to unlock the second chest,  Use fourth key to unlock the first chest. In the second example, you can use the only key to unlock any single chest (note that one key can't be used twice).In the third example, no key can unlock the given chest.

N, M = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)

a_odds = A.count(&:odd?)
a_evens = A.count(&:even?)
b_odds = B.count(&:odd?)
b_evens = B.count(&:even?)

puts [a_odds, b_evens].min + [a_evens, b_odds].min

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

asodd = as.count { |a| a.odd? }
aseven = n - asodd

bsodd = bs.count { |b| b.odd? }
bseven = m - bsodd

puts [asodd, bseven].min + [aseven, bsodd].min

n,m = gets.split.map(&:to_i)
a = gets.split.map{|i|i.to_i%2}
b = gets.split.map{|i|i.to_i%2}
puts [a.count(0),b.count(1)].min+[a.count(1),b.count(0)].min

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

a_even = a.select{|e| e.even? }.size
a_odd = n - a_even

b_even = b.select{|e| e.even? }.size
b_odd = m - b_even

max = [a_even, b_odd].min + [a_odd, b_even].min
p max

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

cntC0 = 0
cntC1 = 0
cntK0 = 0
cntK1 = 0

chests.each do |c|
  if c % 2 == 0
    cntC0 += 1
  elsif c % 2 == 1
    cntC1 += 1
  end
end

keys.each do |k|
  if k % 2 == 0
    cntK0 += 1
  elsif k % 2 == 1
    cntK1 += 1
  end
end

puts [cntC0, cntK1].min + [cntC1, cntK0].min

n, m = gets.split.map &:to_i
a = gets.split.map &:to_i
b = gets.split.map &:to_i
f = a.select { |x| x%2 == 0 }.size
s = b.select { |x| x%2 == 0 }.size
puts [f, b.size - s].min + [a.size - f, s].min


We often go to supermarkets to buy some fruits or vegetables, and on the tag there prints the price for a kilo. But in some supermarkets, when asked how much the items are, the clerk will say that $$$a$$$ yuan for $$$b$$$ kilos (You don't need to care about what "yuan" is), the same as $$$a/b$$$ yuan for a kilo.Now imagine you'd like to buy $$$m$$$ kilos of apples. You've asked $$$n$$$ supermarkets and got the prices. Find the minimum cost for those apples.You can assume that there are enough apples in all supermarkets.

The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 5\,000$$$, $$$1 \leq m \leq 100$$$), denoting that there are $$$n$$$ supermarkets and you want to buy $$$m$$$ kilos of apples. The following $$$n$$$ lines describe the information of the supermarkets. Each line contains two positive integers $$$a, b$$$ ($$$1 \leq a, b \leq 100$$$), denoting that in this supermarket, you are supposed to pay $$$a$$$ yuan for $$$b$$$ kilos of apples.

The only line, denoting the minimum cost for $$$m$$$ kilos of apples. Please make sure that the absolute or relative error between your answer and the correct answer won't exceed $$$10^{-6}$$$. Formally, let your answer be $$$x$$$, and the jury's answer be $$$y$$$. Your answer is considered correct if $$$\frac{|x - y|}{\max{(1, |y|)}} \le 10^{-6}$$$.

NoteIn the first sample, you are supposed to buy $$$5$$$ kilos of apples in supermarket $$$3$$$. The cost is $$$5/3$$$ yuan.In the second sample, you are supposed to buy $$$1$$$ kilo of apples in supermarket $$$2$$$. The cost is $$$98/99$$$ yuan.

n,m = gets.chomp.split

n = n.to_i
m = m.to_f

# price = Array.new(n)
tprice = Array.new(n)

for i in 0...n
    a,b = gets.chomp.split
    tprice[i] = a.to_f / b.to_f
end

puts (tprice.min)*m

n,m=gets.split.map &:to_i
ans=1000000000.0
n.times do
    a,b=gets.split.map &:to_f
    cost=m*(a/b)
    ans=[ans,cost].min
end
p ans

n,m=gets.split.map &:to_i
ans=1000000000.0
n.times do
    a,b=gets.split.map &:to_f
    cost=m*(a/b)
    ans=ans<cost ? ans : cost
end
p ans

n , m = gets.split.map(&:to_i)
ar = []
n.times do
  s = gets.chomp.split.map(&:to_i)
  ar << m / (s[1] / (s[0] + 0.0))
end
puts ar.min

n, m = gets.split.map(&:to_i)
x = 10**9
n.times do
  a, b = gets.split.map(&:to_f)
  x = [x, a/b].min
end
puts x * m

n, m=gets.split.map &:to_i
puts "%.9f" % (((1..n).map{
    a, b=gets.split.map &:to_i
    a.to_r/b.to_r
}.min)*m)

inp = gets.chomp.split(" ")
score = []

wantbuy = inp[1].to_f

inp[0].to_i.times{

mag = gets.chomp.split(" ")
score.push((mag[0].to_f/mag[1].to_f)*wantbuy)
}
puts score.min.round(8)

n,m = gets.split.map(&:to_i)
puts n.times.map{ gets.split.map(&:to_f).inject(:/) }.min * m

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

bargains = []
n.times do
    bargains << gets.split().map { |s| s.to_i }
end

best_bargain = 2<<2048
bargains.each do |bargain|
    best_bargain = [best_bargain, bargain[0]/Float(bargain[1])].min
end

puts (best_bargain*m).round(8)

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

n.times{
    a, b = gets.split.map(&:to_i)
    ans = [ ans, (a * m) / b.to_f ].min
}

p ans

n, m = gets.split.map{|x| x.to_i}
t, f = 0.0, 101.0
n.times do
    a, b = gets.split.map{|x| x.to_i + 0.0}
    f = [f, a/b].min
    t = f*m
end
puts t


You are given one integer $$$n$$$ ($$$n > 1$$$).Recall that a permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation of length $$$5$$$, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n = 3$$$ but there is $$$4$$$ in the array).Your task is to find a permutation $$$p$$$ of length $$$n$$$ that there is no index $$$i$$$ ($$$1 \le i \le n$$$) such that $$$p_i = i$$$ (so, for all $$$i$$$ from $$$1$$$ to $$$n$$$ the condition $$$p_i \ne i$$$ should be satisfied).You have to answer $$$t$$$ independent test cases.If there are several answers, you can print any. It can be proven that the answer exists for each $$$n > 1$$$.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the permutation you have to find.

For each test case, print $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ — a permutation that there is no index $$$i$$$ ($$$1 \le i \le n$$$) such that $$$p_i = i$$$ (so, for all $$$i$$$ from $$$1$$$ to $$$n$$$ the condition $$$p_i \ne i$$$ should be satisfied). If there are several answers, you can print any. It can be proven that the answer exists for each $$$n > 1$$$.

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = (1..n).to_a
  arr << arr.shift
  puts arr.join(' ')
end

t = gets.to_i

1.upto t do
  n = gets.to_i
  list = (1..n).to_a.reverse
  if n.odd?
    list[n/2], list[n/2+1] = list[n/2+1], list[n/2]
  end
  puts list.join(" ")
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    arr = [*1..n]
    i = arr.pop
    arr.unshift(i)
    puts arr.join(" ")
end

gets.to_i.times do
  x=gets.to_i
  if x==1
    puts 1
  else
    puts ([*2..x]+[1]).join(" ")
  end
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = (1..n).to_a
  puts arr.reverse.join(' ')
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = (1..n).to_a
  arr.map{|el| el + 1}
  arr[0] = n
  arr[-1] = 1
  puts arr.join(' ')
end

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  arr = (1..n).to_a
  arr = arr.map{|el| el + 1}
  arr[0] = n
  arr[-1] = 1
  puts arr.join(' ')
end

t = gets.chomp.to_i
t.times do
    n = gets.chomp.to_i
    arr = [*1..n]
    i = []
    until arr == []
        i << arr.pop
        if arr == []
            break
        end
        i << arr.shift
    end
    puts i.join(" ")
end

gets.to_i.times do
  puts [*1..gets.to_i].join(" ")
end


The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.

The first line contains an integer number n (1  ≤  n  ≤  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.

n = gets.to_i
a = []
scores = {}
whens = {}
(0...n).each do |i|
    ee = gets.split
    a << [ee[0], ee[1].to_i]
    player = ee[0]
    pts = ee[1].to_i
    if scores.include? player
        scores[player] += pts
    else
        scores[player] = pts
    end
end
sc = scores.collect{|t| t[1]}
mx = sc.max
winners = {}
scores.each do |t|
    winners[t[0]] = 0 if t[1] == mx
end
(0...n).each do |i|
#     a << [ee[0], ee[1].to_i]
    player = a[i][0]
    pts = a[i][1]
    if winners.include? player
        winners[player] += pts
        if winners[player] >= mx
            puts player
            break
        end
    end
end

a={}
c={}
z={}
l=[]
gets.to_i.times{
	q,w=gets.split
	a[q]=a[q].to_i+w.to_i;
	l+=[[q,w]]
}
m=a.values.max
l.each{|q,w|
	c[q]=c[q].to_i+w.to_i;
	if c[q]>=m and a[q]==m then
		puts q
		exit
	end
}

# frozen_string_literal: true

lines = gets.to_i

score_map = {}
at_index_by_name = {}
1.upto(lines) do |i|
  name, score = gets.split
  score = score.to_i

  score_map[name] ||= 0
  score_map[name] += score

  at_index_by_name[name] ||= []
  at_index_by_name[name] << [score_map[name], i]
end

scores = score_map.to_a.sort_by(&:last)
puts(
  scores
    .select { |score| scores.last.last == score.last }
    .min_by { |score| at_index_by_name[score.first].find { |e| e.first >= score.last }.last }
    .first
)

n = gets.to_i
names = Array.new
scores = Array.new
winn = Array.new
wins = Array.new
n.times do
  name, score = gets.split(" ")
  score = score.to_i
  index = nil
  0.upto(names.size-1) do |i|
    if names[i] == name
      index = i
      scores[index] += score
      break
    end
  end
  if index.nil?
    index = names.size
    names << name
    scores << score
  end
  winn << index
  wins << score
end
m = scores.max
scoresim = [0]*names.size
winner = -1
n.times do |i|
  scoresim[winn[i]] += wins[i]
  if scoresim[winn[i]] >= m and scores[winn[i]] == m
    winner = winn[i]
    break
  end
end
puts names[winner]

log = []
scores = Hash.new(0)
check = Hash.new(0)
gets.to_i.times{
    n,q = gets.split
    scores[n] += q.to_i
    log << [ n, q ]
}
m = scores.values.max
log.each{ | n, q |
    check[n] += q.to_i
    if check[n] >= m and scores[n] == m then
        puts n
        exit
    end
}

input = []
gets.to_i.times { input << gets }

s = Hash.new(0)
input.each do |i|
  name, score = i.split
  s[name] += score.to_i
end

max = s.values.max

ss = Hash.new(0)
input.each do |i|
  name, score = i.split
  ss[name] += score.to_i
  if ss[name] >= max && s[name] == max
    puts name
    break
  end
end

def process(m, ss)
  max = m.values.max
  maxes = m.select {|k, v| v == max}

  res = nil
  idx = 1001

  if maxes.size > 1
    ss = ss.select {|k, v| maxes.include? k}
    ss.each do |k, v|
      sum = 0
      v.each do |vv|
        sum += vv.score
        if sum >= max || vv.index > idx
          if res == nil || vv.index < idx
            res = k
            idx = vv.index
          end
          break
        end
      end
    end
    return res
  end

  maxes.keys[0]
end

num = STDIN.gets.chomp.to_i

S = Struct.new(:index, :score)
m = {}
s = {}

n = 0
while n < num
  n += 1
  line = STDIN.gets
  line.chomp!
  name, score = line.split
  score = score.to_i
  if m.include? name
    m[name] = m[name] + score
  else
    m[name] = score
  end
  if s.include? name
    s[name] << S.new(n, score)
  else
    s[name] = [S.new(n, score)]
  end
end

print process(m, s)

h = {}
n = gets.to_i
l = []
n.times { |i|
  a, b = gets.split
  l << [a,b]
  if h.key? a
    h[a] += b.to_i
  else
    h[a] = b.to_i
  end
}

max = -1000 * n - 1
indexes = []
h.each do |a, b|
  if b > max
    max = b
    indexes = [a]
  elsif b == max
    indexes << a
  end
end

h.clear

n.times { |i|

  a, b = l[i]

  if h.key? a
    h[a] += b.to_i
  else
    h[a] = b.to_i
  end

  if h[a] >= max and indexes.include? a
    print a
    exit(0)
  end

}

#!/usr/bin/ruby

n = gets.to_i
records = []
records = (1..n).map do
  name, score = gets.split
  {name: name, score: score.to_i}
end

table = {}
records.each do |rec|
  name = rec[:name]
  table[name] ||= 0
  table[name] += rec[:score]
end

max = table.values.max
table2 = {}
records.each do |rec|
  name = rec[:name]
  table2[name] ||= 0
  table2[name] += rec[:score]
  if table2[name] >= max and table[name] == max
    puts name
    exit
  end
end

input = gets.chomp.to_i
lines=Array.new
players = Hash.new
winner  = 0
input.times do
  lines.push gets.chomp
  player , points = lines.at(lines.length-1).split(" ")
  players[player] = players[player].to_i + points.to_i
end
players.each do |k,v|
  winner = v if v > winner
end
answers = players.select do |k ,v|
  v==winner
end
players=Hash.new
lines.each do |i|
    player , points = i.split(" ")
    players[player] = players[player].to_i + points.to_i
    if answers.key? player
       if winner <= players[player]
         puts player
         break
       end
    end
end

n = gets.to_i
ans = Hash.new
rec = Array.new
for i in 0...n do
  name, point = gets.split
  name = name.to_sym
  point = point.to_i

  if ans[name].nil?
    ans[name] = point
  else
    ans[name] = ans[name] + point
  end

  rec[i] = name, ans[name]
end

temp = ans.to_a
max_num = temp.max { |a, b| a[1] <=> b[1] }[1]
ans_index = 0

for r in rec do
  if r[1] >= max_num && ans[r[0]] == max_num
    ans_index = r[0]
    break
  end
end

puts ans_index

#!/usr/bin/env ruby

n = gets.chomp!.to_i
h1 = {}
a = []
n.times do
  name, round = gets.chomp!.split(" ")
  round = round.to_i
  h1[name] = h1[name].to_i + round
  a << [name, round.to_i]
end

max_score = h1.values.max
h2 = {}
a.each do | e |
  h2[e[0]] = h2[e[0]].to_i + e[1]
  if h2[e[0]] >= max_score and h1[e[0]] == max_score
    puts e[0]
    exit 0
  end
end

n=gets.chomp!.to_i
memo=Hash.new(0)
result=[]
n.times do
  result << gets.chomp.split
end
result.each do |name,score|
  memo[name]+=score.to_i
end
max=memo.values.max
memo.each_key do |key|
  if memo[key] == max
    memo[key]=0
  else
    memo[key] =-10000
  end
end
result.each do |name,score|
  memo[name]+=score.to_i
  if memo[name] >= max
    puts name
    break
  end
end

#!/usr/bin/env ruby

t = gets.to_i
h1 = Hash.new(0)
h2 = Hash.new(0)
a = Array.new(t)
b = Array.new(t)
m = -1
winner = ""

for i in 0...t

  s = gets.split(' ')

  a[i] = s[0]
  b[i] = s[1].to_i

  h1[a[i]] += b[i]

end

h1.each_pair { |key, val|
  if val > m
    m = val
  end
}

for i in 0...t

  h2[a[i]] += b[i]
  if h2[a[i]] >= m && h1[a[i]] == m
    winner = a[i]
    break
  end

end

puts winner

n=gets.chomp.to_i
nc=0
@hash={}
@hash_total={}
loop do
	break if nc == n
	input=gets.chomp.split(" ")
	k=0
	if nc >= 1
		@hash.each_key do |plr_nm|
			if plr_nm!=input[0]
				k+=1
			end
		end
		if k==@hash.length
			@hash[input [0]]=[0]
			@hash[input [0]][nc]=input[1].to_i
		else
		@hash[input [0]][nc]=input[1].to_i
		end
	else
		@hash[input [0]]=[input[1].to_i]
	end

	nc+=1
end

def Total(key,array)
    k=0
	array.each do|l|
		if l== nil
			l=0
		end
	      k=k+l
	end
    @hash_total[key]=k
end
@hash.each_pair do|a,b|
	Total(a,b)
end

def Tiebreaker(a,b)
   ka=0
   ba=0
   k=0
   @hash[a[0]].each do|cn|
		if cn== nil
			cn=0
		end
		k=k+cn
		ka+=1
		break if k >= a[1]
	end
	k=0
   @hash[b[0]].each do|cn|
        if cn== nil
			cn=0
		end
		k=k+cn
		ba+=1
		break if k >= b[1]
	end
	if ka>ba
		return b
	else
		return a
	end
end

win= @hash_total.inject do |memo,n|
	if memo[1]>n[1]
		memo
	elsif memo[1]==n[1]
		Tiebreaker(memo,n)
	else
		n
	end
end
puts win[0]

num=Hash.new(0)
turn=Hash.new(0)
array=[]
a=gets.chomp.to_i
0.upto(a-1) do |i|
temp=gets.chomp.split(" ")
num[temp[0]]+=temp[1].to_i
array<<temp
end
high=num.values.sort.reverse[0]
winner=num.keys

winner.each do |i|

if num[i]==high
t=0
loop do
if array[t][0]==i
num[i]-=array[t][1].to_i
end
t+=1
if num[i]<=0
turn[i]=t
break
end
break if t==a
end
end

end
high=turn.values.sort[0]
ans=turn.key(high)
puts "#{ans}"

n = gets.to_i
data = []
score = {}
n.times do
    a,b = gets.split(' ')
    c = b.to_i
    score[a] ||= 0
    score[a] += c
    data <<= [a,c]
end

mx = score.values.max

score2 = {}
for v in data do
    nm,sc = v
    score2[nm] ||= 0
    score2[nm] += sc
    if (mx == score[nm]) and (score2[nm] >= mx)
        puts nm
        exit
    end
end

# http://codeforces.com/problemset/problem/2/A

Round = Struct.new(:player, :score)

class WinnerCalculator
  def self.get_winner(scoreboard)
    rounds = []
    scoreboard.each do |round_line|
      player, score = round_line.split
      rounds << Round.new(player, score.to_i)
    end

    scoring = Hash.new(0)
    rounds.each do |round|
      scoring[round.player] += round.score
    end
    max_score = scoring.values.max
    players_with_max_score = scoring.select { |player, score| score == max_score }

    if players_with_max_score.size == 1
      return players_with_max_score.keys.first
    end

    tiebreak_scoring = Hash.new(0)
    rounds.each do |round|
      tiebreak_scoring[round.player] += round.score
      if tiebreak_scoring[round.player] >= max_score && scoring[round.player] == max_score
        return round.player
      end
    end
  end
end

if __FILE__ == $0
  scoreboard = []
  gets.to_i.times { scoreboard << gets }
  winner = WinnerCalculator.get_winner(scoreboard)
  puts winner
end

scoring = Hash.new(0)
scoreboard = []
gets.to_i.times do
  player, score = gets.split
  scoring[player] += score.to_i
  scoreboard << [player, score.to_i]
end

max_score = scoring.values.max

tiebreak_scoring = Hash.new(0)
scoreboard.each do |player, score|
  tiebreak_scoring[player] += score.to_i
  if scoring[player] == max_score && tiebreak_scoring[player] >= max_score
    puts player
    break
  end
end

steps = gets.chomp.to_i

winner = nil
competitors = {}
step_logs = []

steps.times do
  step_result = gets.chomp.split
  step_winner = step_result[0]
  step_winner_score = step_result[1].to_i

  step_logs << [step_winner, step_winner_score]

  winner ||= step_winner
  competitors[step_winner] ||= 0

  competitors[step_winner] += step_winner_score

  winner = step_winner if competitors[step_winner] > competitors[winner]
end

winner_definition = {}

step_logs.each do |step_result|
  step_winner = step_result[0]
  step_winner_score = step_result[1]

  winner_definition[step_winner] ||= 0

  winner_definition[step_winner] += step_winner_score

  if (winner_definition[step_winner] >= competitors[winner]) && (competitors[step_winner] >= competitors[winner])
    puts step_winner
    break
  end
end

h = Hash.new {|h, k| h[k] = [[-1, 0, 0]]}
num_turns = gets.chomp.to_i
num_turns.times {|turn|
  name, score = gets.chomp.split
  score = score.to_i
  prev = h[name].last
  h[name] << [turn, score, prev.last + score]
}

players = h.keys
max_score = -1
max_players = []
players.each {|player; player_score|
  player_score = h[player].last.last
  if player_score > max_score
    max_score = player_score
    max_players = [player]
  elsif player_score == max_score
    max_score = player_score
    max_players << player
  end
}

winner = if max_players.size > 1
  max_players.map {|player|
    [h[player].detect {|(turn, _, score)| if score >= max_score; turn; end},
     player]
  }.sort_by {|(score, _)| score}.first.last
else
  max_players.first
end
puts winner

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
#=================================

n=gets.to_i

data = []
hs = Hash.new(0)

n.times{
	name, points = gets.split

	data << [name, points.to_i]
	hs[name]+=points.to_i
}

max_points = hs.values.max

players = hs.keys.select{|k| hs[k]==max_points}

hs2 = Hash.new(0)
data.each{|name, points|
	next if !players.include? name

	hs2[name]+=points

	if hs2[name]>=max_points
		puts name
		break
	end
}

n = gets.to_i
h = Hash.new
names = []
scores = []
winners = []

for i in 0...n

  s, k = gets.chomp.split
  k = k.to_i

  h[s] = 0 if h[s].nil?

  h[s] += k

  names.push(s)
  scores.push(k)
end

max = h.values.max

h.each do |k,v|
  winners.push(k) if v >= max
end

winners = winners.uniq

h.clear

for i in 0...n
  if winners.include?(names[i])
    h[names[i]] = 0 if h[names[i]].nil?
    h[names[i]] += scores[i]
    if h[names[i]] >= max
      puts names[i]
      exit
    end
  end
end

# coding: utf-8

n = gets.to_i
h = {}
st = []
n.times {
    name, score = gets.split
    score = score.to_i
    h[name] ||= 0
    h[name] += score
    st << [name, score]
}
max = h.values.max
cands = []
for k,v in h
    if v == max
        cands << k
    end
end

if cands.length == 1
    puts cands[0]
else
    h2 = {}
    for s in st
        next if cands.index(s[0]) == nil
        h2[s[0]] ||= 0
        h2[s[0]] += s[1]
        if h2[s[0]] >= max
            puts s[0]
            break
        end
    end
end

a={}
c={}
z={}
l=[]
gets.to_i.times{
	q,w=gets.split
	a[q]=a[q].to_i+w.to_i;
	l+=[[q,w]]
}
m=a.values.max
l.each{|q,w|
	c[q]=c[q].to_i+w.to_i;
	if c[q]>=m and a[q]==m then
		puts q
		exit
	end
}

num_lines = gets().chomp.to_i
scores = {}
log = []
num_lines.times{
|i|
  name, score = gets().chomp.split(/[ ]+/)
  score = score.to_i
  if(scores.has_key?(name)) then
  scores[name] += score
  else
  scores[name] = score
  end
  log << [name, scores[name], i]
}

scores_a = scores.to_a

max_score = scores_a.max {
|player1,player2|
  player1[1] <=> player2[1]
}[1]

top_scores = scores_a.select {
|player|
  player[1] == max_score
}

winner = log.select{
|line|
  top_scores.collect {
  |plr|
    plr[0]
  }.index(line[0]) &&
  line[1] >= max_score
}.min{
|line1,line2|
  line1[2] <=> line2[2]
}[0]

puts winner

n = gets.to_i
r = []
for i in 0 ... n
  a,b = gets.split
  r << [a, b.to_i]
end

h1 = Hash.new{0}
r.each do |name,val|
  h1[name] += val
end

maxi = h1.max{|x,y| x[1] <=> y[1]}[1]

h2 = Hash.new{0}
r.each do |name,val|
  h2[name] += val
  if (h1[name] == maxi && h2[name] >= maxi)
    puts name
    break
  end
end

def getIndex(val, h)
  if (h.key?(val))
    return h[val]
  end
  index = h.size
  return h[val] = index
end

n = gets.to_i
h = {}
last = []
sum = []

names = []
values = []

for i in 0 ... n
  name,val = gets.split
  index = getIndex(name,h)
  val = val.to_i
  if (index < sum.size)
    sum[index] += val
    last[index] = i
  else
    sum << val
    last << i
  end
  names << name
  values << val
end

ans = ""
fastest = n
maxi = sum.max
h.each do |key,index|
  next if (sum[index] != maxi)
  tsum, tmp = 0, n
  for i in 0 ... n
    next if (names[i] != key)
    tsum += values[i]
    if (tsum >= maxi)
      tmp = i
      break
    end
  end
  if (tmp < fastest)
    fastest, ans = tmp,key
  end
end

=begin
maxi = sum.max
fastest = n
h.each do |key,index|
  if (sum[index] == maxi &&  last[index] < fastest)
    fastest = last[index]
    ans = key
  end
end
=end

puts ans

n = gets.to_i
r = []
n.times do
  w, s = gets.split
  r << [w, s.to_i]
end

a = Hash.new(0)
r.each do |w, s|
  a[w] += s
end
mx = a.values.max

b = Hash.new(0)
r.each do |w, s|
  b[w] += s
  if b[w] >= mx and a[w] == mx
    puts w
    exit
  end
end

n = gets.to_i

max = 0
players = Hash.new(0)
rounds = []
n.times do
	name, score = gets.split
	score = score.to_i
	rounds << [name, score]
end

players = rounds.inject(Hash.new(0)) { |h, round| h[round[0]] += round[1]; h }
max = players.max_by { |k, v| v}[1]
winners = players.select { |k, v| v == max }
players = rounds.inject(Hash.new(0)) do |h, round|
	player = round[0]
	h[player] += round[1]
	if (h[player] >= max) && winners.member?(player)
		puts player
		break
	end
	h
end

scores = Hash.new(0)
in_array = []

n = gets.to_i
n.times do
	l = gets.split(" ")
	scores[l[0]] += l[1].to_i
	in_array << [l[0], l[1]]
end

tally = Hash.new(0)
max = scores.values.max
in_array.each do |score|
	tally[score[0]] += score[1].to_i
	if (max == scores[score[0]].to_i) && (tally[score[0]].to_i >= max)
		puts score[0]
		exit
	end
end

#http://codeforces.com/problemset/problem/2/A

n = gets.to_i
dir = Hash.new(0)
step = Array.new
max_val = 0
max_name = Array.new

for i in 1..n
    name, score = gets.chomp.strip.split(" ")
    score = score.to_i
    dir[name] += score
    record = Hash["name" => name, "score" => dir[name]]
    step << record
end

dir.each_key do |key|
    if dir[key] > max_val
        max_val = dir[key]
        max_name.clear
        max_name << key
    elsif dir[key] == max_val
        max_name << key
    end
end

flag = 0
if max_name.size == 1
    puts max_name[0]
else
    for i in 0...step.size
        if step[i]["score"] >= max_val
            for j in 0...max_name.size
                if step[i]["name"] == max_name[j] and flag == 0
                    puts max_name[j]
                    flag = 1
                end
            end
        end
    end
end

#!/usr/bin/env ruby

class Transaction < Struct.new(:index, :value, :result)
end

$players_scores = Hash.new
$operation_index = 0

def process_score(score_string)
	parts = score_string.split(' ')
	name = parts[0]
	value = parts[1].to_i

	if (!$players_scores.include?(name))
		$players_scores[name] = Array.new
		$players_scores[name] << Transaction.new($operation_index, value, value)
	else
		player_info = $players_scores[name]
		$players_scores[name] << Transaction.new($operation_index, value, player_info[player_info.count - 1][:result] + value)
	end

	$operation_index += 1
end

# results for testing
# match_results = []
# match_results << "andrew 3"
# match_results << "andrew 2"
# match_results << "andrew 1"
# match_results << "mike 5"
# match_results << "andrew -1"
# match_results << "john 5"

# match_results << "andrew 3"
# match_results << "andrew 2"
# match_results << "mike 5"

repeats = gets.to_i
match_results = []

while (repeats > 0)
	match_results << gets.strip
	repeats -= 1
end

for score_string in match_results
	process_score(score_string)
end

winning_players = Array.new
max_score = 0

for score in $players_scores.values
	if (score[score.count - 1][:result] > max_score)
		winning_players.clear
		max_score = score[score.count - 1][:result]
		winning_players << score
	elsif score[score.count - 1][:result] == max_score
		winning_players << score
	end
end

min_index = $operation_index
winner = winning_players[0]

for score_history in winning_players
	for transaction in score_history
		if transaction[:result] >= max_score && transaction[:index] < min_index
			min_index = transaction[:index]
			winner = score_history
		end
	end
end

puts $players_scores.invert[winner]

n = STDIN.readline.to_i
score = Hash.new
t = []

n.times do |i|
	t << STDIN.readline.split
	# print STDIN.readline.split
	# print t
	t[i][1] = t[i][1].to_i
	if score[t[i][0]] == nil ;
		score[t[i][0]] = 0
	end
	score[t[i][0]] += t[i][1]
end

maxscore = 0
score.each_value do |i|
	maxscore = i if i > maxscore
end

iscore = Hash.new
ans = ""
n.times do |i|
	if iscore[t[i][0]] == nil ;
		iscore[t[i][0]] = 0
	end
	iscore[t[i][0]] += t[i][1]
	ans = t[i][0]; break if iscore[t[i][0]] >= maxscore &&
							 score[t[i][0]] == maxscore
end
print ans

n = gets.to_i
a = n.times.map{gets.split}
h = Hash.new(0)
a.each{|name, s| h[name] += s.to_i}
mx = h.max_by{|name, s| s}[1]
h2 = Hash.new(0)
a.each do |name, s|
  h2[name] += s.to_i
  if h[name] == mx && h2[name] >= mx
    puts name
    break
  end
end

n = gets.to_i
a = n.times.map{gets.split}
h1 = a.each_with_object(Hash.new(0)){|(x, y), h| h[x] += y.to_i}
mx = h1.values.max
h2 = Hash.new(0)
a.each do |name, s|
  h2[name] += s.to_i
  if h1[name] == mx && h2[name] >= mx
    puts name
    break
  end
end

final = {}

n = gets.to_i
names = []
scores = []
n.times do
  a = gets.split(/\s+/)
  name = a[0]
  score = a[1].to_i
  if final[name].nil? then
    final[name] = 0
  end
  final[name] += score
  names << name
  scores << score
end

max = 0
final.each{|key, value| max = value if max < value}

total = {}
n.times do |i|
  name = names[i]
  score = scores[i]
  if total[name].nil? then
    total[name] = 0
  end
  total[name] += score
  if total[name] >= max && final[name] == max then
    puts name
    break
  end
end

num_lines = gets().chomp.to_i
scores = {}
scores_fset ={}

addscore = -> (fn, maxscore, index) do
  (-> (score) {
      prev = fn.call(score)
      return prev if prev >= 0
      return index if score <= maxscore
      return -1
  })
end

num_lines.times do |index|
  line = gets().chomp
  name, score = line.split
  score = score.to_i
  scores[name] ||= 0
  scores[name] += score

  scores_fset[name] ||= -> (x) do
    (-> () {
      return index if x <= score
      return -1
    }).call()
  end

  if scores_fset[name].call(scores[name]) == -1
    scores_fset[name] = addscore.call(scores_fset[name], scores[name], index)
  end
end

top_score = scores.values.max
top_scorers = scores.select {|k, v| v == top_score}
puts top_scorers.min_by {|k, v| scores_fset[k].call(top_score)}[0]

N = gets.to_i
h = Hash.new { |hash, key| hash[key] = 0 }
a = []
N.times do
  n, p = gets.split
  a << [n, p.to_i]
  h[n] += p.to_i
end

m = h.values.max
a.reject! { |x| h[x[0]] < m }
h = Hash.new { |hash, key| hash[key] = 0 }
a.each do |n, p|
  h[n] += p
  if h[n] >= m
    puts n
    exit
  end
end

n = gets.chomp.to_i

log = []
total = {}

n.times do |i|
    line = gets.chomp.split(" ")
    player = line[0]
    cur_score = line[1].to_i
    log << [player, cur_score]
    score = total[player]
    total[player] = score.nil? ? cur_score : score + cur_score
end

max_score = total.values.max
players_with_max_score = total.select{|k, v| v == max_score }

if players_with_max_score.length > 1
    tot = {}
    log.each do |row|
        if players_with_max_score.keys.include? row[0]
            score = tot[row[0]]
            tot[row[0]] = score.nil? ? row[1] : score + row[1]
            if tot[row[0]] >= max_score
                puts row[0]
                exit
            end
        end

    end
else
    puts players_with_max_score.keys.first
end

num=Hash.new(0)
turn=Hash.new(0)
array=[]
a=gets.chomp.to_i
0.upto(a-1) do |i|
temp=gets.chomp.split(" ")
num[temp[0]]+=temp[1].to_i
array<<temp
end
high=num.values.sort.reverse[0]
winner=num.keys

winner.each do |i|

if num[i]==high
t=0
loop do
if array[t][0]==i
num[i]-=array[t][1].to_i
end
t+=1
if num[i]<=0
turn[i]=t
break
end
break if t==a
end
end

end
high=turn.values.sort[0]
ans=turn.key(high)
puts "#{ans}"

 a={}
c={}
z={}
l=[]
gets.to_i.times{
	q,w=gets.split
	a[q]=a[q].to_i+w.to_i;
	l+=[[q,w]]
}
m=a.values.max
l.each{|q,w|
	c[q]=c[q].to_i+w.to_i;
	if c[q]>=m and a[q]==m then
		puts q
		exit
	end
}

n = gets.to_i
lst = []
tot = {}
n.times do
  name, score = gets.split
  score = score.to_i
  lst << [name, score]
  tot[name] ||= 0
  tot[name] += score
end

m = tot.values.max

lst.reject! { |elem| tot[elem[0]] < m}
#puts lst

tot = {}
for name,score in lst do
  tot[name] ||= 0
  tot[name] += score
  if tot[name] >= m
    puts name
    break
  end
end

n = gets.to_i
h = []
n.times do
  name, score = gets.split
  score = score.to_i
  h << [name, score]
end

a = {}
h.each do |con|
  a[con[0]] ||= 0
  a[con[0]] += con[1]
end

m = a.max {|x,y| x[1] <=> y[1]}[1]

b = Hash.new(0)
h.each do |con|
  b[con[0]] += con[1]
  if a[con[0]] == m  && b[con[0]] >=m
    puts con[0]
    exit
  end
end

a={}
c={}
z={}
l=[]
gets.to_i.times{
	q,w=gets.split
	a[q]=a[q].to_i+w.to_i;
	l+=[[q,w]]
}
m=a.values.max
l.each{|q,w|
	c[q]=c[q].to_i+w.to_i;
	if c[q]>=m and a[q]==m then
		puts q
		exit
	end
}

n = gets.to_i

m = Array.new

a = {}

n.times do
	k = gets.chomp.split(" ")
	key = k[0]
	value = k[1].to_i
	if a[ key ].nil? then
		a[ key ] = value
	else
		a[ key ] += value
	end
	m << k
end

max = a.values.max

b = {}

m.each{ |s|
	key = s[0]
	value = s[1].to_i
	if b[ key ].nil? then
		b[ key ] = value
	else
		b[ key ] += value
	end
	if a[ key ] == max and b [ key ] >= max then
		puts key
		break
	end
}

log = []
scores = Hash.new(0)
check = Hash.new(0)
gets.to_i.times{
    n,q=gets.split
    scores[n]+=q.to_i
    log << [q,n]
}
m = scores.values.max
log.each{|q,n|
    check[n] += q.to_i
    if check[n] >= m and scores[n] == m then
        puts n
        exit
    end
}

players = Hash.new(0)
games = []
gets.to_i.times do |i|
  name, point = gets.chomp.split
  point = point.to_i
  games << [name, point]
  players[name] += point
end
sorted_players = players.sort{|a, b| b[1] <=> a[1]}
max = sorted_players[0][1]
max_players = {}
sorted_players.each do |s|
  break if s[1] < max
  max_players[s[0]] = 0
end

games.each do |game|
  if max_players.has_key?(game[0])
    max_players[game[0]] += game[1]
    if max_players[game[0]] >= max
      puts game[0]
      exit
    end
  end
end

n = gets.chomp.to_i
h = Hash.new
as = Array.new
for i in 1..n
	s = gets.chomp
	as.push( s )
end
for i in 1..n
	nm,sc = as[i-1].split(/ /)
	sc = sc.to_i
	sc += h[nm] if h.has_key?(nm)
	h[nm] = sc
end
hv = h.to_a.sort {|a,b|
	b[1] <=> a[1]
}

if hv.length == 1 || hv[0][1] > hv[1][1]
	puts hv[0][0]
else
	hnm = Hash.new
	for i in 0..hv.length-1
		break if hv[0][1] > hv[i][1]
		hnm[hv[i][0]] = 1
	end

	h.clear
	for i in 1..n
		nm,sc = as[i-1].split(/ /)
		sc = sc.to_i
		sc += h[nm] if h.has_key?(nm)
		h[nm] = sc
		if sc >= hv[0][1] && hnm.has_key?(nm)
			puts nm
			exit
		end
	end
end

n=gets.to_i
v=[]
n.times do
	s,w=gets.split
	v << [s,w.to_i]
end
a=Hash.new(0)
v.each{|s,w|a[s]+=w}
m=a.max{|x,y|x[1]<=>y[1]}[1]
f=Hash.new(0)
v.each{|s,w|
	f[s]+=w
	if a[s]==m and f[s]>=m then
		puts s
		exit
	end
}

table = {}
lined = []
ARGF.each_line do |line|
  if ARGF.lineno != 1
    name, mark = line.split
    if !table.has_key?(name)
      table[name] = [mark.to_i]
    else
      table[name] += [table[name].last + mark.to_i]
    end
    lined.push({:name => name, :mark => table[name].last})
  end
end

maxNames = []
max = 0

table.keys.each do |name|
   if max < table[name].last
     maxNames = [name]
     max = table[name].last
   elsif max == table[name].last
     maxNames.push name
   end
end

if maxNames.length == 1
  puts maxNames[0]
else
  lined.each do |val|
    if val[:mark] >= max and maxNames.include? val[:name]
      puts val[:name]
      break
    end
  end
end

#!/usr/bin/ruby
n=gets.chomp.to_i
h=Hash.new;h.default=0
a=Array.new
n.times{|z|
  s=gets.chomp.split(" ")
  s[1]=s[1].to_i
  h[s[0]]+=s[1]
  a.push(s)
}
m=h.values.max
h.each_key{|k| h[k]=(h[k]==m)?0:nil}

#re-read
a.each{|i|
  if h[i[0]]
    h[i[0]]+=i[1]
    if h[i[0]]>=m then puts i[0]; exit end
  end
}

n = gets.to_i
r = []
n.times do
	w, s = gets.split
	r << [w, s.to_i]
end

a = Hash.new(0)
r.each do |w,s|
	a[w] += s
end
m = a.max{|x,y| x[1] <=> y[1] }[1]

b = Hash.new(0)
r.each do |w,s|
	b[w] += s
	if a[w] == m && b[w] >= m then
		puts w
		exit
	end
end

n = gets.to_i
ary = []
hash = Hash.new 0
n.times do
	list = gets.split
	name = list[0]
	score = list[1].to_i
	hash.has_key?(name) ? hash[name] += score : hash[name] = score
	ary << [name, hash[name]]
end
maximum = hash.values.max
candidates = hash.select {|key, value| value == maximum}
ary.each do |entry|
	if candidates.key?(entry[0]) && entry[1] >= maximum
		puts entry[0]
		break
	end
end

h = {}
hh = {}
for name,score in $<.read.scan(/(\S+) (\S+)/)
    t = h[name] = (h[name]||0)+score.to_i
    for i in 0..t
        hh[i] = (hh[i]||[])+[name]
    end
end
max = h.values.max
puts hh[max].find{|x|h[x]==max}

n=STDIN.gets.chomp.to_i
players={}
n.times {|i|
  player,score=STDIN.gets.chomp.split(' ')
  if players.key?(player)
    scores=players[player]
    players[player]<<[score.to_i+scores[scores.length-1][0],i]
  else
    players[player]=[[score.to_i,i]]
  end
}
max=0
winners=[]
players.each_pair {|player,scores|
  score=scores[scores.length-1][0]
  if max<score
    winners=[player]
    max=score
  elsif max==score
    winners<<player
  end
}

min_idx=10000
winner=''
winners.each {|player|
  players[player].each {|score_idx|
    score=score_idx[0]
    idx=score_idx[1]
    if max<=score && idx<min_idx
      min_idx=idx
      winner=player
    end
  }
}
print(winner,"\n")

A={}
b={}
l=[]
gets.to_i.times{
    q,w=gets.split;
    A[q]=A[q].to_i+w.to_i;
    l+=[[q,w]]

}
m=A.values.max
l.each{|q,w|
 b[q]=b[q].to_i+w.to_i;
if b[q]>=m and A[q]==m then
    puts q
    exit
end
}

# Codeforces, Problem 2A
# http://codeforces.com/contest/1/problem/C
# Nate Collings

def get_names_scores(num)
  names = []
  scores = []
  num.times do
    player, score = gets.chomp.split("\s")
    names << player
    scores << score.to_i
  end
  return names, scores
end

def get_max(players)
  max = players.values.map { |v| v }.max
  with_max = players.select { |_,v| v == max}
  return max, with_max
end

def run_round(rounds, names, scores, players=nil, second=false)
  max, with_max = get_max(players) if second
  players = {}
  rounds.times do |round|
    player = names[round]
    score = scores[round]
    if !second || with_max.has_key?(player)
      score += players[player] if players.has_key?(player)
      players[player] = score
      return player if second && score >= max
    end
  end
  players
end

def first_round(rounds, names, scores)
  run_round(rounds, names, scores)
end

def second_round(rounds, names, scores, players)
  run_round(rounds, names, scores, players, true)
end

def solve
  rounds = gets.chomp.to_i
  names, scores = get_names_scores(rounds)

  candidates = first_round(rounds, names, scores)
  return candidates.keys[0] if candidates.length == 1
  return second_round(rounds, names, scores, candidates)
end

puts solve

log = []
scores = Hash.new(0)
gets.to_i.times{
    n,q=gets.split
    scores[n]+=q.to_i
    log << [q,n]
}
m = scores.values.max
log.each{|q,n|
    if q.to_i>=m then
        p n
        exit
    end
}

n = gets.to_i
a = Hash.new([0])
n.times do |_|
	w, s = gets.split
	a[w] = a[w][0] + s.to_i, -_
end
puts a.max{|a,b| a[1] <=> b[1] }[0]

n = gets.to_i
h = Hash.new
max = 0
name = ''

for i in 1..n
  s, k = gets.chomp.split
  k = k.to_i
  if h[s].nil?
    h[s] = k
  else
    h[s] += k
  end
  if h[s] > max
    max = h[s]
    name = s
  end
end

puts name

def process(m, ss)
  max = m.values.max
  maxes = m.select {|k, v| v == max}

  res = nil
  idx = 1001

  if maxes.size > 1
    ss.each do |k, v|
      sum = 0
      v.each do |vv|
        sum += vv.score
        if sum >= max || vv.index > idx
          if res == nil || vv.index < idx
            res = k
            idx = vv.index
          end
          break
        end
      end
    end
    return res
  end

  maxes.keys[0]
end

num = STDIN.gets.chomp.to_i

S = Struct.new(:index, :score)
m = {}
s = {}

n = 0
while n < num
  n += 1
  line = STDIN.gets
  line.chomp!
  name, score = line.split
  score = score.to_i
  if m.include? name
    m[name] = m[name] + score
  else
    m[name] = score
  end
  if s.include? name
    s[name] << S.new(n, score)
  else
    s[name] = [S.new(n, score)]
  end
end

print process(m, s)

n = gets.to_i
r = []
for i in 0 ... n
  a,b = gets.split
  r << [a, b.to_i]
end

h1 = Hash.new{0}
r.each do |name,val|
  h1[name] += val
end

maxi = r.max{|x,y| x[1] <=> y[1]}[1]

h2 = Hash.new{0}
r.each do |name,val|
  h2[name] += val
  if (h1[name] == maxi && h2[name] >= maxi)
    puts name
    break
  end
end

log = []
scores = Hash.new(0)
check = Hash.new(0)
gets.to_i.times{
    n,q=gets.split
    scores[n]+=q.to_i
    log << [q,n]
}
m = scores.values.max
log.each{|q,n|
    check[n]+=q.to_i
    if check[n] >= m
        print n
        exit
    end
}

def getIndex(val, h)
  if (h.key?(val))
    return h[val]
  end
  index = h.size
  return h[val] = index
end

n = gets.to_i
h = {}
last = []
sum = []

for i in 0 ... n
  name,val = gets.split
  index = getIndex(name,h)
  val = val.to_i
  if (index < sum.size)
    sum[index] += val
    last[index] = i
  else
    sum << val
    last << i
  end
end

ans = ""
maxi = sum.max
fastest = n
h.each do |key,index|
  if (sum[index] == maxi &&  last[index] < fastest)
    fastest = last[index]
    ans = key
  end
end
puts ans

scores = {}
gets.to_i.times do |i|
  name, score = gets.split
  score = score.to_i
  if scores.has_key? name
    if scores[name][2] < scores[name][0]+score
      scores[name][1] = i
      scores[name][2] = scores[name][0]+score
    end
    scores[name][0] += score
  else
    scores[name] = [score, i, score]
  end
end

scores = scores.to_a.sort_by! { |key, value| -value[0] }
max_value = scores[0]
#puts scores.inspect
scores.each do |v|
  if v[1][0]<max_value[1][0]
    break
  elsif v[1][1]<max_value[1][1]
    max_value = v
  end

end
puts max_value[0]

n = gets.to_i
h = {}
ans = '', mx = -1e9
n.times do
  s = gets.split(' ')
  h[s[0]] = 0 if (h.has_key?(s[0]) == false)
  h[s[0]] += s[1].to_i
  if h[s[0]] > mx
    ans = s[0]
    mx = h[s[0]]
  end
end
puts ans

n = STDIN.readline.to_i
score = Hash.new
t = []

n.times do |i|
	t << STDIN.readline.split
	# print STDIN.readline.split
	# print t
	t[i][1] = t[i][1].to_i
	if score[t[i][0]] == nil ;
		score[t[i][0]] = 0
	end
	score[t[i][0]] += t[i][1]
end

maxscore = 0
score.each_value do |i|
	maxscore = i if i > maxscore
end

score.clear
ans = ""
n.times do |i|
	if score[t[i][0]] == nil ;
		score[t[i][0]] = 0
	end
	score[t[i][0]] += t[i][1]
	ans = t[i][0]; break if score[t[i][0]] >= maxscore
end
print ans

log = []
scores = Hash.new(0)
check = Hash.new(0)
gets.to_i.times{
    n,q=gets.split
    scores[n]+=q.to_i
    log << [q,n]
}
m = scores.values.max
log.each{|q,n|
    check[n] += q.to_i
    if check[n] >= m and scores[n] == q.to_i then
        puts n
        exit
    end
}

# Codeforces, Problem 2A
# http://codeforces.com/contest/1/problem/C
# Nate Collings

Player = Struct.new(:score, :round)

players = {}
rounds = gets.chomp.to_i

rounds.times do |round|
  player, score = gets.chomp.split("\s")
  score = score.to_i
  if players.has_key?(player)
    players[player].score += score
    players[player].round = round
  else
    players[player] = Player.new(score, round)
  end
end

max = players.values.map { |v| v.score }.max
with_max = players.select { |_,v| v.score == max }
winner = with_max.min_by { |_,v| v.round }[0]

puts winner

num_lines = gets().chomp.to_i
players_info = {}
num_lines.times{
  |i|
  name, score = gets().chomp.split(/[ ]+/)
  score = score.to_i
  if(players_info.has_key?(name)) then
    players_info[name][0] += score
    players_info[name][1] = i
  else
    players_info[name] = []
    players_info[name][0] = score
    players_info[name][1] = i
  end
}

puts players_info.to_a.sort {
  |a,b|
  (((b[1][0] <=> a[1][0]) * 2 + (a[1][1] <=> b[1][1])) <=> 0)
}[0][0]

n = gets.to_i

h = Hash.new
ins = Array.new
n.times do
  ins.push(gets)
  s = ins[-1].split(' ')
  h[s[0]] = 0 if (h.has_key?(s[0]) == false)
  h[s[0]] += s[1].to_i
end
mx = h.values.max
b = h.select {|k, v| v == mx}

h.clear()
ins.each do |s|
  s = s.split(' ')
  h[s[0]] = 0 if (h.has_key?(s[0]) == false)
  h[s[0]] += s[1].to_i
  if h[s[0]] == mx and b.has_key?(s[0])
    puts s[0]
    break
  end
end

#!/usr/bin/env ruby

n = gets.chomp!.to_i
scores = {}
scores['max-scorer'] = nil
n.times do
  name, round = gets.chomp!.split(" ")
  max_score = scores[scores['max-scorer']].to_i
  curr_score = round.to_i + scores[name].to_i
  scores[name] = curr_score
  scores['max-scorer'] = name if (curr_score > max_score)
end

puts scores['max-scorer']

#!/usr/bin/env ruby

h = Hash.new(0)
t = gets.to_i
m = -1
winner = ""

for i in 0...t

  s = gets.split(' ')

  a = s[0]
  b = s[1].to_i

  h[a] += b

  if h[a] > m
    m = h[a]
    winner = a
  end

end

puts winner

n = gets.to_i
ans = Hash.new
for i in 0...n do
  name, point = gets.split
  name = name.to_sym
  point = point.to_i

  if ans[name].nil?
    ans[name] = point, i
  else
    ans[name][0] = ans[name][0] + point
  end

  ans[name][1] = i
end

ans = ans.to_a
ans.sort! { |a, b| b[1][0] <=> a[1][0] }

i = 0
n = ans.size - 1
final = ans[0]
final_next = final

while i < n && final_next[1][0] == final[1][0]
  if final_next[1][1] < final[1][1]
    final = final_next
    final_next = ans[i + 1]
  else
    final_next = ans[i + 1]
  end
  i = i + 1
end

if final_next[1][1] < final[1][1] && final_next[1][0] == final[1][0]
  final = final_next
end

p final[0].to_s

table = {}
lined = []
ARGF.each_line do |line|
  if ARGF.lineno != 1
    name, mark = line.split
    if !table.has_key?(name)
      table[name] = [mark.to_i]
    else
      table[name] += [table[name].last + mark.to_i]
    end
    lined.push({:name => name, :mark => table[name].last})
  end
end

maxNames = []
max = 0

table.keys.each do |name|
   if max < table[name].last
     maxNames = [name]
     max = table[name].last
   elsif max = table[name].last
     maxNames.push name
   end
end

if maxNames.length == 1
  puts maxNames[0]
else
  lined.each do |val|
    if val[:mark] >= max
      puts val[:name]
      break
    end
  end
end

n = gets.to_i
ans = Hash.new
rec = Array.new
for i in 0...n do
  name, point = gets.split
  name = name.to_sym
  point = point.to_i

  if ans[name].nil?
    ans[name] = point
  else
    ans[name] = ans[name] + point
  end

  rec[i] = name, ans[name]
end

ans = ans.to_a
max_num = ans.max { |a, b| a[1] <=> b[1] }[1]
ans_index = 0

for r in rec do
  if r[1] >= max_num
    ans_index = r[0]
    break
  end
end

puts ans_index

n = gets.chomp.to_i
h = Hash.new
as = Array.new
for i in 1..n
	s = gets.chomp
	as.push( s )
end
for i in 1..n
	nm,sc = as[i-1].split(/ /)
	sc = sc.to_i
	sc += h[nm] if h.has_key?(nm)
	h[nm] = sc
end
hv = h.to_a.sort {|a,b|
	b[1] <=> a[1]
}

if hv.length == 1 || hv[0][1] > hv[1][1]
	puts hv[0][0]
else
	h.clear
	for i in 1..n
		nm,sc = as[i-1].split(/ /)
		sc = sc.to_i
		sc += h[nm] if h.has_key?(nm)
		h[nm] = sc
		if sc >= hv[0][1]
			puts nm
			exit
		end
	end
end

#!/usr/bin/env ruby

$global_hash = Hash.new
$max_score = 0
$leader = ""

def process_score(score_string)
	parts = score_string.split(' ')
	key = parts[0]
	value = parts[1].to_i

	if ($global_hash.has_key? key)
		$global_hash[key] += value
	else
		$global_hash[key] = value
	end

	if ($global_hash[key] > $max_score)
		$max_score = $global_hash[key]
		$leader = key
	end
end

#results for testing
# match_results = []
# match_results << "andrew 3"
# match_results << "andrew 2"
# match_results << "mike 5"

repeats = gets.to_i
match_results = []

while (repeats > 0)
	match_results << gets.strip
	repeats -= 1
end

for score_string in match_results
	process_score(score_string)
end

puts $leader

n=gets.chomp!.to_i
memo=Hash.new
score=[]
n.times do
  score << gets.chomp
end
n.times do |j|
  tmp=score[j].split
  if memo.key?(tmp[0])
    memo[tmp[0]]+=tmp[1].to_i
  else
    memo[tmp[0]]=tmp[1].to_i
  end
end
max=memo.values.max
memo.clear()
n.times do |j|
  tmp=score[j].split
  if memo.key?(tmp[0])
    memo[tmp[0]]+=tmp[1].to_i
  else
    memo[tmp[0]]=tmp[1].to_i
  end
  if memo[tmp[0]]>=max
    puts tmp[0]
    break
  end
end

# frozen_string_literal: true

lines = gets.to_i

score_map = {}
at_index_by_name = {}
1.upto(lines) do |i|
  name, score = gets.split
  score = score.to_i

  score_map[name] ||= 0
  score_map[name] += score

  at_index_by_name[name] ||= {
    score: -99_999_999,
    index: 9_999_999
  }

  next unless at_index_by_name[name][:score] < score_map[name]

  at_index_by_name[name] = {
    score: score_map[name],
    index: i
  }
end

scores = score_map.to_a.sort_by(&:last).reverse
puts(
  scores
    .select { |score| scores.last.last == score.last }
    .min_by { |score| at_index_by_name[score.first][:index] }
    .first
)

# frozen_string_literal: true

lines = gets.to_i

score_map = {}
at_index_by_name = {}
1.upto(lines) do |i|
  name, score = gets.split
  score = score.to_i

  score_map[name] ||= 0
  score_map[name] += score

  at_index_by_name[name] ||= {}

  next if at_index_by_name[name][score_map[name]]

  at_index_by_name[name][score_map[name]] = i
end

scores = score_map.to_a.sort_by(&:last)
puts(
  scores
    .select { |score| scores.last.last == score.last }
    .min_by { |score| at_index_by_name[score.first][score.last] }
    .first
)

# Codeforces, Problem 2A
# http://codeforces.com/contest/1/problem/C
# Nate Collings

players = {}
max = 0
winner = nil
rounds = gets.chomp.to_i

rounds.times do
  player, score = gets.chomp.split("\s")
  score = score.to_i
  players[player] = players.has_key?(player) ? players[player] += score : score
  if players[player] > max
    winner = player
    max = players[player]
  end
end

puts winner

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
#=================================

n=gets.to_i

data = []
hs = Hash.new(0)

n.times{
	name, points = gets.split

	data << [name, points.to_i]
	hs[name]+=points.to_i
}

max_points = hs.values.max

hs2 = Hash.new(0)
data.each{|name, points|
	hs2[name]+=points

	if hs2[name]==max_points
		puts name
		break
	end
}

num_lines = gets().chomp.to_i
players_info = {}
num_lines.times{
  |i|
  name, score = gets().chomp.split(/[ ]+/)
  score = score.to_i
  if(players_info.has_key?(name)) then
    if(score != 0) then
      players_info[name][0] += score
      players_info[name][1] = i
    end
  else
    players_info[name] = []
    players_info[name][0] = score
    players_info[name][1] = i
  end
}

puts players_info.to_a.sort {
  |a,b|
  (((b[1][0] <=> a[1][0]) * 3 + (a[1][1] <=> b[1][1])) <=> 0)
}[0][0]

input = gets.chomp.to_i
lines=Array.new
players = Hash.new
winner  = 0
won=''
input.times do
  lines.push gets.chomp
  player , points = lines.at(lines.length-1).split(" ")
  players[player] = players[player].to_i + points.to_i
end
players.each do |k,v|
  winner = v if v > winner
end
answers = players.select do |k ,v|
  v==winner
end
players=Hash.new
lines.each do|i|
    player , points = i.split(" ")
    players[player] = players[player].to_i + points.to_i
    if winner == players[player] and answers.key? player
      won=player
      break
    end
end
puts won

n=gets.chomp!.to_i
memo=Hash.new
premax=-1111
max=-1000
name=""
n.times do
  tmp=gets.chomp!.split()
  if memo.key?(tmp[0])
    memo[tmp[0]]+=tmp[1].to_i
  else
    memo[tmp[0]]=tmp[1].to_i
  end
  max=-1000
  tmpname=""
  memo.each do |key,value|
    if max<value
      max=value
      tmpname=key
    end
  end
  if premax != max
    name=tmpname
  end
  premax=max
end
puts name

#!/usr/bin/env ruby

class Player < Struct.new(:score, :index)
end

$players_scores = Hash.new
$operation_index = 0

def process_score(score_string)
	parts = score_string.split(' ')
	key = parts[0]
	value = parts[1].to_i

	if (!$players_scores.include? key)
		$players_scores[key] = Player.new(value, $operation_index)
	else
		$players_scores[key][:score] += value
		if value >= 0
			$players_scores[key][:index] = $operation_index
		else
			$players_scores[key][:index] = 0
		end
	end

	$operation_index += 1
end

# results for testing
# match_results = []
# match_results << "andrew 3"
# match_results << "andrew 2"
# match_results << "andrew 1"
# match_results << "mike 5"
# match_results << "andrew -1"
# match_results << "john 5"

# match_results << "andrew 3"
# match_results << "andrew 2"
# match_results << "mike 5"

repeats = gets.to_i
match_results = []

while (repeats > 0)
	match_results << gets.strip
	repeats -= 1
end

for score_string in match_results
	process_score(score_string)
end

players = $players_scores.values
players.sort! { |a,b| a[:score] == b [:score] ? a[:index] <=> b[:index] : b[:score] <=> a[:score]}

puts $players_scores.invert[players[0]]

# frozen_string_literal: true

lines = gets.to_i

score_map = {}
at_index_by_name = {}
1.upto(lines) do |i|
  name, score = gets.split
  score = score.to_i

  score_map[name] ||= 0
  score_map[name] += score

  at_index_by_name[name] ||= {
    score: score_map[name],
    index: i
  }

  next unless at_index_by_name[name][:score] < score_map[name]

  at_index_by_name[name] = {
    score: score_map[name],
    index: i
  }
end

scores = score_map.to_a.sort_by(&:last)
puts(
  scores
    .select { |score| scores.last.last == score.last }
    .min_by { |score| at_index_by_name[score.first][:index] }
    .first
)

def process(m, ss)
  max = m.values.max
  maxes = m.select {|k, v| v == max}

  while maxes.size > 1 && !ss.empty?
    s = ss.pop()
    if s.score > 0 && maxes.include?(s.name)
      maxes.delete s.name
    end
  end

  maxes.keys()[0]
end

num = STDIN.gets.chomp.to_i

S = Struct.new(:name, :score)
m = {}
s = []

n = 0
while n < num
  n += 1
  line = STDIN.gets
  line.chomp!
  name, score = line.split
  score = score.to_i
  if m.include? name
    m[name] = m[name] + score
  else
    m[name] = score
  end
  s << S.new(name, score)
end

print process(m, s)

# coding: utf-8

n = gets.to_i
h = {}
st = []
n.times {
    name, score = gets.split
    score = score.to_i
    h[name] ||= 0
    h[name] += score if score >= 0
    st << [name, score]
}
max = h.values.max
cands = []
for k,v in h
    if v == max
        cands << k
    end
end
if cands.length == 1
    puts cands[0]
else
    h2 = {}
    for s in st
        h2[s[0]] ||= 0
        h2[s[0]] += s[1] if s[1] >= 0
        if h2[s[0]] >= max
            puts s[0]
            break
        end
    end
end

# frozen_string_literal: true

lines = gets.to_i

score_map = {}
at_index_by_name = {}
1.upto(lines) do |i|
  name, score = gets.split
  score = score.to_i

  score_map[name] ||= 0
  score_map[name] += score

  at_index_by_name[name] ||= {
    score: 0,
    index: 0
  }

  next unless at_index_by_name[name][:score] <= score_map[name]

  at_index_by_name[name] = {
    score: score_map[name],
    index: i
  }
end

scores = score_map.sort_by(&:last)
puts(
  scores
    .select { |score| scores.last.last == score.last }
    .min_by { |score| at_index_by_name[score.first][:index] }
    .first
)

num_lines = gets().chomp.to_i
players_info = {}
num_lines.times{
  |i|
  name, score = gets().chomp.split(/[ ]+/)
  score = score.to_i
  if(players_info.has_key?(name)) then
      players_info[name][0] += score
      if(score > 0) then players_info[name][1] = i end
  else
    players_info[name] = []
    players_info[name][0] = score
    players_info[name][1] = i
  end
}

puts players_info.to_a.sort {
  |a,b|
  (((b[1][0] <=> a[1][0]) * 2 + (a[1][1] <=> b[1][1])) <=> 0)
}[0][0]

n = gets.to_i
h = Hash.new(0)
p = ''
n.times do
  name, score = gets.split
  score = score.to_i
  h[name] += score
  p = name if h[name] > h[p]
end
mx = h.max_by{|name, s| s}
puts mx[1] == h[p] ? p : mx[0]

h = {}
n = gets.to_i
n.times { |i|
  a, b = gets.split
  if h.key? a
    h[a] = [h[a][0] + b.to_i, h[a][0] + b.to_i > h[a][2] ? i : h[a][1], h[a][0] + b.to_i > h[a][2] ? h[a][0] + b.to_i : h[a][2] ]
  else
    h[a] = [b.to_i, i, b.to_i]
  end
}

max2 = -1000 * n - 1
max1 = n
index = ''

h.each do |a, b|
  if b[2] > max2
    max2 = b[2]
    max1 = b[1]
    index = a
  elsif b[2] == max2 and b[1] < max1
    max1 = b[1]
    index = a
  end
end

print index

def getIndex(val, h)
  if (h.key?(val))
    return h[val]
  end
  index = h.size
  return h[val] = index
end

n = gets.to_i
h = {}
input = []
sum = []
inputLog = []

for i in 0 ... n
  name,val = gets.split
  index = getIndex(name,h)
  val = val.to_i
  input << val
  if (index < sum.size)
    sum[index] += val
  else
    sum << val
    inputLog << []
  end
  inputLog[index] << i
end

ans = ""
maxi = sum.max
fastest = n
h.each do |key,index|
  if (sum[index] == maxi)
    sum,tmp = 0,0
    for i in 0 ... inputLog[index].size
      sum += input[inputLog[index][i]];
      if (sum >= maxi)
        tmp = inputLog[index][i];
       break
      end
    end
    if (tmp < fastest)
      ans = key
      fastest = tmp
    end
  end
end
puts ans

require 'set'

n = gets.to_i

h = Hash.new
a = Array.new
b = Array.new
n.times do
  s = gets.split(' ')
  h[s[0]] = 0 if (h.has_key?(s[0]) == false)
  h[s[0]] += s[1].to_i
  a.push(s[0])
  b.push(h[s[0]])
end
mx = h.values.max

d = Set.new
h.each do |k, v|
  d.add(k) if v == mx
end

a.each_index do |i|
  if d.include? (a[i]) and b[i] == mx
    puts a[i]
    break
  end
end

num_lines = gets().chomp.to_i
players_info = {}
num_lines.times{
  |i|
  name, score = gets().chomp.split(/[ ]+/)
  score = score.to_i
  if(players_info.has_key?(name)) then
    players_info[name][0] += score
    players_info[name][1] = i
  else
    players_info[name] = []
    players_info[name][0] = score
    players_info[name][1] = i
  end
}

puts players_info.to_a.sort {
  |a,b|
  (((b[1][0] <=> a[1][0]) * 2 + (a[1][1] <=> b[1][1])) <=> 0)
}[0][0]

s = Hash.new(0)
t = {}
gets.to_i.times do |i|
  name, score = gets.split
  s[name] += score.to_i
  t[name] = i
end

max = s.values.max
puts t.select { |k, v| s[k] == max }.min_by {|k, v| v}.first

def getIndex(val, h)
  if (h.key?(val))
    return h[val]
  end
  index = h.size
  return h[val] = index
end

n = gets.to_i
h = {}
sum = []
last = []

for i in 0 ... n
  name,val = gets.split
  index = getIndex(name,h)
  val = val.to_i
  if (index < sum.size)
    sum[index] += val
    last[index] = i
  else
    sum << val
    last << i
  end
end

ans = ""
maxi = sum.max
fastest = n
h.each do |key,value|
  if (sum[value] == maxi && last[value] < fastest)
    ans = key
    fastest = last[value]
  end
end
puts ans

A={}
b={}
l=[]
gets.to_i.times{
    q,w=gets.split;
    A[q]=A[q].to_i+w.to_i;
    l+=[[q,w]]

}
m=A.values.max
l.each{|q,w|
 b[q]=b[q].to_i+w.to_i;
if b[q]>=m then
    puts q
    exit
end
}

n = gets.to_i
a = n.times.map{gets.split}
h = Hash.new(0)
a.each{|name, s| h[name] += s.to_i}
mx = h.max_by{|name, s| s}[1]
h2 = Hash.new(0)
a.each do |name, s|
  h2[name] += s.to_i
  if h2[name] == mx
    puts name
    break
  end
end

#!/usr/bin/env ruby

h = Hash.new(0)
t = gets.to_i
m = -1
winner = ""

for i in 0...t

  s = gets.split(' ')

  a = s[0]
  b = s[1].to_i

  h[a] += b

  if h[a] > m
    m = h[a]
    winner = a
  end

end

puts winner

players = {}
gets.to_i.times do |i|
  name, point = gets.chomp.split
  players[name] ||= {:point => 0, :last => nil}
  players[name][:point] += point.to_i
  players[name][:last] = i
end
result = players.sort{|a, b| (b[1][:point] <=> a[1][:point]).nonzero? || a[1][:last] <=> b[1][:last]}
#p result
puts result[0][0]

log = []
scores = Hash.new(0)
check = Hash.new(0)
gets.to_i.times{
    n,q=gets.split
    scores[n]+=q.to_i
    log << [q,n]
}
m = scores.values.max
log.each{|q,n|
    check[n]+=q.to_i
    if check[n] >= m
        print n
        exit
    end
}

# Codeforces, Problem 2A
# http://codeforces.com/contest/1/problem/C
# Nate Collings

players = {}
max = 0
winner = nil
rounds = gets.chomp.to_i

rounds.times do
  player, score = gets.chomp.split("\s")
  score = score.to_i
  players[player] = players.has_key?(player) ? players[player] += score : score
  players[player] = -1 if score < 0
  if players[player] > max
    winner = player
    max = players[player]
  end
end

puts winner

h = {}
n = gets.to_i
l = []
n.times { |i|
  a, b = gets.split
  l << [a,b]
  if h.key? a
    h[a] += b.to_i
  else
    h[a] = b.to_i
  end
}

max = -1000 * n - 1
h.each do |a, b|
  if b > max
    max = b
  end
end

h.clear

n.times { |i|

  a, b = l[i]

  if h.key? a
    h[a] += b.to_i
  else
    h[a] = b.to_i
  end

  if h[a] >= max
    print a
    exit(0)
  end

}

num_lines = gets().chomp.to_i
top_score = 0
scores = {}
scores_fset ={}

addscore = -> (fn, maxscore, index) do
  (-> (score) {
      prev = fn.call(score)
      return prev if prev
      return index if score <= maxscore
      return -1
  })
end

num_lines.times do |index|
  line = gets().chomp
  name, score = line.split
  score = score.to_i
  scores[name] ||= 0
  scores[name] += score

  scores_fset[name] ||= -> (x) do
    (-> () {
      return index if x <= score
      return -1
    }).call()
  end

  if scores_fset[name].call(scores[name]) == -1
    scores_fset[name] = addscore.call(scores_fset[name], scores[name], index)
  end

  top_score = scores[name] if scores[name] > top_score
end

top_scorers = scores.select {|k, v| v == scores.values.max}
puts top_scorers.min_by {|k, v| scores_fset[k].call(top_score)}[0]

table = {}
lined = []
ARGF.each_line do |line|
  if ARGF.lineno != 1
    name, mark = line.split
    if !table.has_key?(name)
      table[name] = [mark.to_i]
    else
      table[name] += [table[name].last + mark.to_i]
    end
    lined.push({:name => name, :mark => table[name].last})
  end
end

maxNames = []
max = 0

table.keys.each do |name|
   if max < table[name].last
     maxNames = [name]
     max = table[name].last
   elsif max == table[name].last
     puts "Add #{name} with #{max}"
   end
end

if maxNames.length == 1
  puts maxNames[0]
else
  lined.each do |val|
    if val[:mark] >= max
      puts val[:name]
      break
    end
  end
end

A={}
b={}
l=[]
gets.to_i.times{
    q,w=gets.split;
    A[q]=A[q].to_i+w.to_i;
    l+=[[q,w]]

}
m=A.values.max
l.each{|q,w|
 b[q]=b[q].to_i+w.to_i;
if b[q]>=m and A[q]=m then
    puts q
    exit
end
}

winner = ""
max_score = 0
scoreboard = Hash.new(0)
gets.to_i.times do
  player, score = gets.split
  scoreboard[player] += score.to_i
  if scoreboard[player] > max_score
    winner = player
    max_score = scoreboard[player]
  end
end

puts winner

log = []
scores = Hash.new(0)
gets.to_i.times{
    n,q=gets.split
    scores[n]+=q.to_i
    log << [q,n]
}
m = scores.values.max
log.each{|q,n|
    if q.to_i>=m then
        print n
        exit
    end
}

h = {}
n = gets.to_i
n.times { |i|
  a, b = gets.split
  if h.key? a
    h[a] = [h[a][0] + b.to_i, h[a][0] + b.to_i > h[a][2] ? i : h[a][1], h[a][0] + b.to_i > h[a][2] ? h[a][0] + b.to_i : h[a][2] ]
  else
    h[a] = [b.to_i, i, b.to_i]
  end
}

max2 = -1000 * n - 1
max1 = n
index = ''

h.each do |a, b|
  if b[2] > max2
    max2 = b[2]
    max1 = b[1]
    index = a
  elsif b[2] == max2 and b[1] < max1
    max1 = b[1]
    index = a
  end
end

print index

idx = 0
table = {}
ARGF.each_line do |line|
  if ARGF.lineno != 1
    name, mark = line.split
    if !table.has_key?(name)
      table[name] = {'mark' => mark.to_i, 'pos' => idx}
    else
      table[name]['mark'] += mark.to_i
      table[name]['pos'] = idx
    end
    idx = idx + 1
  end
end

maxMark = 0
minIdx = 0
max = ''
table.keys.each do |key|
  val = table[key]
  if maxMark < val['mark']
    maxMark = val['mark']
    minIdx = val['pos']
    max = key
  elsif maxMark == val['mark'] && minIdx > val['pos']
    minIdx = val['pos']
    max = key
  end
end

puts max

num_lines = gets().chomp.to_i
top_score = 0
scores = {}
scores_fset ={}

addscore = -> (fn, maxscore, index) do
  (-> (score) {
      prev = fn.call(score)
      return prev if prev
      return index if score <= maxscore
      return false
  })
end

num_lines.times do |index|
  line = gets().chomp
  name, score = line.split
  score = score.to_i
  scores[name] ||= 0
  scores[name] += score

  scores_fset[name] ||= -> (x) do
    (-> () {
      return index if x <= score
      return false
    }).call()
  end

  unless scores_fset[name].call(scores[name])
    scores_fset[name] = addscore.call(scores_fset[name], scores[name], index)
  end

  top_score = scores[name] if scores[name] > top_score
end

puts top_scorers = scores.select {|k, v| v == scores.values.max}
puts top_scorers.min_by {|k, v| scores_fset[k].call(top_score)}[0]

#http://codeforces.com/problemset/problem/2/A

n = gets.to_i
dir = Hash.new(0)
step = Array.new
max_val = 0
max_name = Array.new

for i in 1..n
    name, score = gets.chomp.strip.split(" ")
    score = score.to_i
    dir[name] += score
    record = Hash["name" => name, "score" => dir[name]]
    step << record
end

dir.each_key do |key|
    if dir[key] > max_val
        max_val = dir[key]
        max_name << key
    elsif dir[key] == max_val
        max_name << key
    end
end

flag = 0
if max_name.size == 1
    puts max_name[0]
else
    for i in 0...step.size
        if step[i]["score"] >= max_val
            for j in 0...max_name.size
                if step[i]["name"] == max_name[j] and flag == 0
                    puts max_name[j]
                    flag = 1
                end
            end
        end
    end
end

def getIndex(val, h)
  if (h.key?(val))
    return h[val]
  end
  index = h.size
  return h[val] = index
end

n = gets.to_i
h = {}
input = []
sum = []
inputLog = []

for i in 0 ... n
  name,val = gets.split
  index = getIndex(name,h)
  val = val.to_i
  input << val
  if (index < sum.size)
    sum[index] += val
  else
    sum << val
    inputLog << []
  end
  inputLog[index] << i
end

ans = ""
maxi = sum.max
fastest = n
h.each do |key,index|
  if (sum[index] == maxi)
    sum,tmp = 0,0
    for i in 0 ... inputLog[index].size
      sum += input[inputLog[index][i]];
      if (sum > maxi)
        tmp = inputLog[index][i];
       break
      end
    end
    if (tmp < fastest)
      ans = key
      fastest = tmp
    end
  end
end
puts ans

n=gets.chomp.to_i
nc=0
@hash={}
@hash_total={}
loop do
	break if nc == n
	input=gets.chomp.split(" ")
	k=0
	if nc >= 1
		@hash.each_key do |plr_nm|
			if plr_nm!=input[0]
				k+=1
			end
		end
		if k==@hash.length
			@hash[input [0]]=[input[1].to_i]
		else
		@hash[input [0]]=@hash[input [0]]+[input[1].to_i]
		end
	else
		@hash[input [0]]=[input[1].to_i]
	end

	nc+=1
end
def Total(key,array)
    k=0
	array.each do|l|
	      k=k+l
	end
    @hash_total[key]=k
end
@hash.each_pair do|a,b|
	Total(a,b)
end

def Tiebreaker(a,b)
   ka=0
   ba=0
   k=0
   @hash[a[0]].each do|cn|
		k=k+cn
		ka+=1
		break if k >= a[1]
	end
	k=0
   @hash[b[0]].each do|cn|
		k=k+cn
		ba+=1
		break if k >= b[1]
	end
	if ka>ba
		return b
	else
		return a
	end
end

win= @hash_total.inject do |memo,n|
 if memo[1]>n[1]
	memo
 elsif memo[1]=n[1]
     Tiebreaker(memo,n)
 else
	n
end
end
puts win[0]

n = gets.chomp.to_i
h = Hash.new(n)
hsnm = ""
hssc = 0
for i in 1..n
	nm,sc = gets.chomp.split(/ /)
	sc = sc.to_i
	sc += h[nm] if h.has_key?(nm)
	h[nm] = sc
	if hssc < sc
		hsnm = nm
		hssc = sc
	end
end
puts hsnm

h = {}
hh = {}
for name,score in $<.read.scan(/(\S+) (\S+)/)
    t = h[name] = (h[name]||0)+score.to_i
    hh[t] = name unless hh[t]
end
puts hh[h.map(&:last).max]

log = []
scores = Hash.new(0)
check = Hash.new(0)
gets.to_i.times{
    n,q=gets.split
    scores[n]+=q.to_i
    log << [q,n]
}
m = scores.values.max
log.each{|q,n|
    check[n] += q.to_i
    if check[n] >= m and scores[n] == q.to_i then
        puts n
        exit
    end
}

# frozen_string_literal: true

lines = gets.to_i

score_map = {}
at_index_by_name = {}
1.upto(lines) do |i|
  name, score = gets.split
  score = score.to_i

  score_map[name] ||= 0
  score_map[name] += score

  at_index_by_name[name] ||= {
    score: -99_999_999,
    index: 9_999_999
  }

  next unless at_index_by_name[name][:score] < score_map[name]

  at_index_by_name[name] = {
    score: score_map[name],
    index: i
  }
end

scores = score_map.to_a.sort_by(&:last)
puts(
  scores
    .select { |score| scores.last.last == score.last }
    .min_by { |score| at_index_by_name[score.first][:index] }
    .first
)

#!/usr/bin/env ruby

$global_hash = Hash.new
$max_score = 0
$leader = ""

if ($global_hash.has_key? "key")
	$global_hash["key"] += 2
else
	$global_hash["key"] = 2
end

def process_score(score_string)
	parts = score_string.split(' ')
	key = parts[0]
	value = parts[1].to_i

	if ($global_hash.has_key? key)
		$global_hash[key] += value
	else
		$global_hash[key] = value
	end

	if ($global_hash[key] > $max_score)
		$max_score = $global_hash[key]
		$leader = key
	end
end

#results for testing
# match_results = []
# match_results << "andrew 3"
# match_results << "andrew 2"
# match_results << "mike 5"

repeats = gets.to_i
match_results = []

while (repeats > 0)
	match_results << gets.strip
	repeats -= 1
end

for score_string in match_results
	process_score(score_string)
end

puts $leader

scores = {}
history = {}
gets.to_i.times do |i|
  name, score = gets.split
  score = score.to_i
  history[i] = [name, score]
  if scores.has_key? name
    scores[name] = scores[name]+score
  else
    scores[name] = score
  end
end

scores = scores.to_a.sort_by! { |key, value| -value }
m = scores[0][1]
scores = {}
#puts m
history.each do |k,v|
  name = v[0]
  score = v[1]
  if scores.has_key? name
    scores[name] = scores[name]+score
  else
    scores[name] = score
  end
  #puts "#{scores.inspect} #{scores[name]}"
  if scores[name] >=m
    puts name
    break
  end
end

players = {}
gets.to_i.times do |i|
  name, point = gets.chomp.split
  players[name] ||= {:point => 0, :max => nil, :max_at => nil}
  players[name][:point] += point.to_i
  if players[name][:max].nil? || players[name][:point] >  players[name][:max]
    players[name][:max] = players[name][:max]
    players[name][:max_at] = i
  end
end
puts players.sort{|a, b| (b[1][:max] <=> a[1][:max]).nonzero? || a[1][:max_at] <=> b[1][:max_at]}[0][0]

A={}
b={}
l=[]
gets.to_i.times{
    q,w=gets.split;
    A[q]=A[q].to_i+w.to_i;
     b[q]=b[q].to_i+w.to_i;
    l+=[[q,w]]

}
m=A.values.max
l.each{|q,w|

if b[q]>=m and A[q]=m then
    puts q
    exit
end
}

# coding: utf-8

n = gets.to_i
h = {}
st = []
n.times {
    name, score = gets.split
    score = score.to_i
    h[name] ||= 0
    h[name] += score
    st << [name, score]
}
max = h.values.max
cands = []
for k,v in h
    if v == max
        cands << k
    end
end
if cands.length == 1
    puts cands[0]
else
    h2 = {}
    for s in st
        h2[s[0]] ||= 0
        h2[s[0]] += s[1]
        if h2[s[0]] == max
            puts s[0]
            break
        end
    end
end

h = {}
n = gets.to_i
l = []
n.times { |i|
  a, b = gets.split
  l << [a,b]
  if h.key? a
    h[a] += b.to_i
  else
    h[a] = b.to_i
  end
}

max = -1000 * n - 1
h.each do |a, b|
  if b > max
    max = b
  end
end

h.clear

n.times { |i|

  a, b = l[i]

  if h.key? a
    h[a] += b.to_i
  else
    h[a] = b.to_i
  end

  if h[a] >= max
    print a
    exit(0)
  end

}

steps = gets.chomp.to_i

winner = nil
competitors = {}

steps.times do
  step_result = gets.chomp.split
  step_winner = step_result[0]
  step_winner_score = step_result[1].to_i
  winner ||= step_winner
  competitors[step_winner] ||= 0
  competitors[step_winner] += step_winner_score
  winner = step_winner if competitors[winner] < competitors[step_winner]
end

puts winner

# coding: utf-8

n = gets.to_i
h = {}
st = []
n.times {
    name, score = gets.split
    score = score.to_i
    h[name] ||= 0
    h[name] += score
    st << [name, score]
}
max = h.values.max
cands = []
for k,v in h
    if v == max
        cands << k
    end
end
if cands.length == 1
    puts cands[0]
else
    h2 = {}
    for s in st
        h2[s[0]] ||= 0
        h2[s[0]] += s[1]
        if h2[s[0]] >= max
            puts s[0]
            break
        end
    end
end

n=gets.chomp.to_i

names=[]
values=[]

a=0
while a<n
	data=gets.chomp.split
	name=data[0].to_s
	value=data[1].to_i

	names.push(name)
	values.push(value)
	a+=1
end

sortnames=[]
sortvalues=[]

max=0
maxvalue=0
for i in (0..values.length-1)
	if sortnames.length==0
		sortnames.push(names[i])
		sortvalues.push(values[i])
		maxvalue=sortvalues[i]
		max=i
	else

		flag = false

		for k in (0..sortnames.length-1)
			if sortnames[k]==names[i]
				flag = true
				sortvalues[k]+=values[i]
				if sortvalues[k]>maxvalue
					maxvalue=sortvalues[k]
					max=k
				end
				break
			end
		end

		if !flag
			sortnames.push(names[i])
			sortvalues.push(values[i])
			if values[i]>maxvalue
				maxvalue=values[i]
				max=sortnames.length-1
			end
		end
	end
end

puts sortnames[max]

n=gets.chomp!.to_i
memo=Hash.new
score=[]
n.times do
  score << gets.chomp
end
n.times do |j|
  tmp=score[j].split
  if memo.key?(tmp[0])
    memo[tmp[0]]+=tmp[1].to_i
  else
    memo[tmp[0]]=tmp[1].to_i
  end
end
max=memo.values.max
memo.clear()
n.times do |j|
  tmp=score[j].split
  if memo.key?(tmp[0])
    memo[tmp[0]]+=tmp[1].to_i
  else
    memo[tmp[0]]=tmp[1].to_i
  end
  if memo[tmp[0]]==max
    puts tmp[0]
    break
  end
end

s = Hash.new(0)
t = {}
gets.to_i.times do |i|
  name, score = gets.split
  s[name] += score.to_i
  t[name] = i
end

min = s.values.min
puts t.select { |k, v| s[k] == min }.min_by {|k, v| v}.first

n = gets.to_i
h = Hash.new
names = []
scores = []

for i in 0...n

  s, k = gets.chomp.split
  k = k.to_i

  if h[s].nil?
    h[s] = 0
  end

  h[s] += k

  names.push(s)
  scores.push(k)
end

max = h.values.max
h.clear

for i in 0...n
  if h[names[i]].nil?
    h[names[i]] = 0
  end
  h[names[i]] += scores[i]
  if h[names[i]] >= max
    puts names[i]
    exit
  end
end


The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.There are $$$n+1$$$ checkpoints on the trail. They are numbered by $$$0$$$, $$$1$$$, ..., $$$n$$$. A runner must start at checkpoint $$$0$$$ and finish at checkpoint $$$n$$$. No checkpoint is skippable — he must run from checkpoint $$$0$$$ to checkpoint $$$1$$$, then from checkpoint $$$1$$$ to checkpoint $$$2$$$ and so on. Look at the picture in notes section for clarification.Between any two adjacent checkpoints, there are $$$m$$$ different paths to choose. For any $$$1\le i\le n$$$, to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$, a runner can choose exactly one from the $$$m$$$ possible paths. The length of the $$$j$$$-th path between checkpoint $$$i-1$$$ and $$$i$$$ is $$$b_{i,j}$$$ for any $$$1\le j\le m$$$ and $$$1\le i\le n$$$.To test the trail, we have $$$m$$$ runners. Each runner must run from the checkpoint $$$0$$$ to the checkpoint $$$n$$$ once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length $$$l_i$$$ between checkpoint $$$i-1$$$ and $$$i$$$ ($$$1\le i\le n$$$), his tiredness is $$$$$$\min_{i=1}^n l_i,$$$$$$ i. e. the minimum length of the paths he takes.Please arrange the paths of the $$$m$$$ runners to minimize the sum of tiredness of them.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n,m \leq 100$$$). The $$$i$$$-th of the next $$$n$$$ lines contains $$$m$$$ integers $$$b_{i,1}$$$, $$$b_{i,2}$$$, ..., $$$b_{i,m}$$$ ($$$1 \le b_{i,j} \le 10^9$$$). It is guaranteed that the sum of $$$n\cdot m$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, output $$$n$$$ lines. The $$$j$$$-th number in the $$$i$$$-th line should contain the length of the path that runner $$$j$$$ chooses to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$. There should be exactly $$$m$$$ integers in the $$$i$$$-th line and these integers should form a permuatation of $$$b_{i, 1}$$$, ..., $$$b_{i, m}$$$ for all $$$1\le i\le n$$$. If there are multiple answers, print any.

NoteIn the first case, the sum of tiredness is $$$\min(2,5) + \min(3,3) + \min(4,1) = 6$$$.  In the second case, the sum of tiredness is $$$\min(2,4,3) + \min(3,1,5) = 3$$$.

t = gets.to_s.to_i
1.upto(t) do |casenum|
  checkpoints, paths = gets.to_s.split.map {|x| x.to_i }

  a = []
  checkpoints.times do
    a.push(gets.to_s.split.map {|x| x.to_i }.sort)
  end

  results = []

  paths.times do
    result = []
    best = a[0][0]
    best_i = 0
    a.each.with_index do |x, i|
      if x[0] < best
        best = x[0]
        best_i = i
      end
    end
    a.each_index do |i|
      if i == best_i
        result.push(a[i].shift)
      else
        result.push(a[i].pop)
      end
    end
    results.push(result)
  end
  0.upto(checkpoints - 1) do |i|
    printf("%s\n", 0.upto(paths - 1).map {|j| results[j][i] }.join(" "))
  end
end


In order to write a string, Atilla needs to first learn all letters that are contained in the string.Atilla needs to write a message which can be represented as a string $$$s$$$. He asks you what is the minimum alphabet size required so that one can write this message.The alphabet of size $$$x$$$ ($$$1 \leq x \leq 26$$$) contains only the first $$$x$$$ Latin letters. For example an alphabet of size $$$4$$$ contains only the characters $$$\texttt{a}$$$, $$$\texttt{b}$$$, $$$\texttt{c}$$$ and $$$\texttt{d}$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of lowercase Latin letters.

For each test case, output a single integer — the minimum alphabet size required to so that Atilla can write his message $$$s$$$.

5

1

a

4

down

10

codeforces

3

bcf

5

zzzzz

NoteFor the first test case, Atilla needs to know only the character $$$\texttt{a}$$$, so the alphabet of size $$$1$$$ which only contains $$$\texttt{a}$$$ is enough.For the second test case, Atilla needs to know the characters $$$\texttt{d}$$$, $$$\texttt{o}$$$, $$$\texttt{w}$$$, $$$\texttt{n}$$$. The smallest alphabet size that contains all of them is $$$23$$$ (such alphabet can be represented as the string $$$\texttt{abcdefghijklmnopqrstuvw}$$$).

main = -> {
  n = gets.to_i
  s = gets.chomp.chars
  s.max.ord - 'a'.ord + 1
}

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

gets.to_i.times {
    gets
    s=gets.chars.map(&:ord)
    puts s.max.to_i-96
}

=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
    p gets.chars.map{|x|x.ord}.max-"a".ord+1

end

gets.to_i.times{
    gets
    s=gets.chars.map{|x|x.ord-97}
    p s.max+1
}


You are given two integers $$$x$$$ and $$$y$$$. You want to choose two strictly positive (greater than zero) integers $$$a$$$ and $$$b$$$, and then apply the following operation to $$$x$$$ exactly $$$a$$$ times: replace $$$x$$$ with $$$b \cdot x$$$.You want to find two positive integers $$$a$$$ and $$$b$$$ such that $$$x$$$ becomes equal to $$$y$$$ after this process. If there are multiple possible pairs, you can choose any of them. If there is no such pair, report it.For example:   if $$$x = 3$$$ and $$$y = 75$$$, you may choose $$$a = 2$$$ and $$$b = 5$$$, so that $$$x$$$ becomes equal to $$$3 \cdot 5 \cdot 5 = 75$$$;  if $$$x = 100$$$ and $$$y = 100$$$, you may choose $$$a = 3$$$ and $$$b = 1$$$, so that $$$x$$$ becomes equal to $$$100 \cdot 1 \cdot 1 \cdot 1 = 100$$$;  if $$$x = 42$$$ and $$$y = 13$$$, there is no answer since you cannot decrease $$$x$$$ with the given operations.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of one line containing two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le 100$$$).

If it is possible to choose a pair of positive integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$ after the aforementioned process, print these two integers. The integers you print should be not less than $$$1$$$ and not greater than $$$10^9$$$ (it can be shown that if the answer exists, there is a pair of integers $$$a$$$ and $$$b$$$ meeting these constraints). If there are multiple such pairs, print any of them. If it is impossible to choose a pair of integers $$$a$$$ and $$$b$$$ so that $$$x$$$ becomes $$$y$$$, print the integer $$$0$$$ twice.

def try(i, y)
  cnt = 0
  while y % i == 0
    cnt += 1
    y /= i
  end

  return nil unless y == 1
  cnt
end

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

  if y % x != 0
    puts '0 0'
    next
  end

  y /= x

  if y == 1
    puts '1 1'
    next
  end

  i = 2
  found = false
  while i <= y
    j = try(i, y)
    if j
      puts "#{j} #{i}"
      found = true
      break
    end

    i += 1
  end

  next if found
  puts '0 0'
end

pow = (1..10).flat_map do |a|
  (1..100).map do |b|
    [b ** a, [a, b]]
  end
end.to_h

gets.to_i.times do
  x, y = gets.split.map(&:to_i)
  if y >= x && y % x == 0 && pow[y / x]
    puts pow[y / x].join(" ")
  else
    puts "0 0"
  end
end

for t in 1..gets.to_i do
	a=gets.split
	a[0]=a[0].to_i
	a[1]=a[1].to_i
	c=a[0]
	d=a[1]

	if d%c==0
		print 1,' ',d.div(c),"\n"
	else
		print 0,' ',0,"\n"
	end
end

t=gets.chomp.to_i
t.times do
    s= gets.chomp.split
    x=s[0].to_i
    y=s[1].to_i
    if (y % x ==0)
        puts "#{1} #{y/x}"
    else
        puts "#{0} #{0}"
    end
end

def try(i, y)
  cnt = 0
  while y % i == 0
    cnt += 1
    y /= i
  end

  return nil unless y == 1
  cnt
end

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

  if y % x != 0
    puts '0 0'
    next
  end

  y /= x

  if y == 1
    puts '1 1'
    next
  end

  i = 2
  found = false
  while i * i <= y
    j = try(i, y)
    if j
      puts "#{j} #{i}"
      found = true
      break
    end

    i += 1
  end

  next if found
  puts '0 0'
end

pow = (1..10).flat_map do |a|
  (1..10).map do |b|
    [b ** a, [a, b]]
  end
end.to_h

gets.to_i.times do
  x, y = gets.split.map(&:to_i)
  if y >= x && y % x == 0 && pow[y / x]
    puts pow[y / x].join(" ")
  else
    puts "0 0"
  end
end


Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.Return the maximum number of rows that she can make completely clean.

The first line of input will be a single integer n (1 ≤ n ≤ 100). The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.

The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.

NoteIn the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.In the second sample, everything is already clean, so Ohana doesn't need to do anything.

n = gets.chomp.to_i
arr = Hash.new{0}
n.times do
arr[gets.chomp]+=1
end
max = 0
arr.each do |key,value|
	if value > max
	max = value
	end
end
print max

=begin
4
0101
1000
1111
0101

3
111
111
111
=end

def function
b=gets.chomp.to_i
string_array=[]
b.times do |i|
a=gets.chomp
string_array.push(a)
end
count_array=[]
0.upto string_array.length-1 do |i|
count_array.push(string_array.count(string_array[i]))
end
puts count_array.max
end
function

rows = gets.to_i
row_hash = {}
(rows).times do
    row_val = gets
    if row_hash.include?(row_val)
        row_hash[row_val]+=1
    else
        row_hash[row_val] = 1
    end
end
puts (row_hash.max_by{|k, v| v}).last

$pair = {}

def sweep(arr, row)
		str = arr[row] * ""
		if $pair.has_key?(str)
			$pair[str] += 1
		else
			$pair[str] = 1
		end
end

=begin
def count(arr, col)
	l = 0
	(0...arr[0].length).each do |iterNum|
		l += 1 if arr[iterNum][0] == 0
	end

	l
end

def cleanCount(arr)
	l = 0

	(0...arr[0].length).each do |iterNum|
		str = arr[iterNum] * ""
		l += 1 if str == ("1" * arr[0].length)
	end

	l
end
=end

n = gets.chomp.to_i
room = []
countArr = []

(0...n).each do |iter|
	room << (gets.chomp.split('').map {|item| item.to_i})
end

(0...n).each do |iter|
	countArr << sweep(room, iter)
	#print $pair
	#puts ''
end

max = 0
$pair.each_value do |val|
	max = val if max < val
end

puts max

n = gets.to_i
s = {}
n.times do |i|
  r = gets.chomp
  s[r] ||= 0
  s[r] += 1
end

puts s.values.max

n,h = gets.to_i,{}
(1..n).each{
    r = gets.strip
    h[r] ||= 0
    h[r] += 1
}
p h.values.max

n = gets.to_i
a = n.times.map{gets.chomp}
p a.uniq.reduce(0){|mx, x| mx = [mx, a.count(x)].max}

n = gets().chomp().to_i
b = []

n.times{
        b.push(gets().chomp())
}

c=b.sort{|x,y| x <=> y}

str=c[0]
max = 1
temp =1
for i in (1..c.length-1)
        if c[i]==str
                temp+=1

        else
                str=c[i]
                if temp > max
                        max = temp
                end
                temp=1
        end

end

if temp > max
        max = temp
end

puts max

n = gets().chomp().to_i
b = []

n.times{
        s = gets().chomp().split('')
        a = []
        for i in (0..n-1)
                if s[i]=='0'
                        a.push("#{i+1}")
                end
        end
        if a.length()==0
                a.push("0")
        end
        b.push(a.join(''))
}

c=b.sort{|x,y| x.length <=> y.length}

str=c[0]
max = 1
temp =1
for i in (1..c.length-1)
        if c[i]==str
                temp+=1

        else
                str=c[i]
                if temp > max
                        max = temp
                end
                temp=1
        end

end

puts max


You are given an array of n elements, you must make it a co-prime array in as few moves as possible.In each move you can insert any positive integral number you want not greater than 109 in any place in the array.An array is co-prime if any two adjacent numbers of it are co-prime.In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of elements in the given array. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

Print integer k on the first line — the least number of elements needed to add to the array a to make it co-prime. The second line should contain n + k integers aj — the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by adding k elements to it. If there are multiple answers you can print any one of them.

gets;a=gets.split.map(&:to_i);b=[a[0],*a.each_cons(2).flat_map{|x,y|x.gcd(y)==1 ? [y] : [1,y]}];p b.size-a.size;puts b*' '

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

n = readline.to_i
arr = readline.split(' ').collect(&:to_i)
ct = 0
res = []
0.upto(arr.length - 2) do |ind|
  a, b = arr[ind], arr[ind + 1]
  res += [a]
  if gcd(a, b) != 1
    ct += 1
    res += [1]
  end
end
res += [arr.last]
puts ct
res.each_with_index do |n, i|
  if i != 0
    print " "
  end
  print n
end
puts ""

a=gets.chomp.to_i
b=gets.chomp.split(" ").map{|i| i.to_i}
ans=[]
p=0
0.upto(a-2) do |i|
    if b[i].gcd(b[i+1])!=1
      ans << b[i]
      ans << 1
      p+=1
    else
        ans << b[i]
    end
end
ans << b[a-1]
puts "#{p}"
puts ans.join(" ")

def gcd(a,b)
	return b>0 ? gcd(b,a%b) : a
end

n=gets.to_i
a=gets.split(' ')
s=0
for i in 1..a.size-1
	s+=1 if gcd(a[i].to_i,a[i-1].to_i)>1
end
puts s
print a[0]
for i in 1..a.size-1
	print " 1" if gcd(a[i].to_i,a[i-1].to_i)>1
	print " "+a[i]
end
puts

a=gets.chomp.to_i
b=gets.chomp.split(" ").map{|i| i.to_i}
ans=[]
0.upto(a-2) do |i|
    if b[i].gcd(b[i+1])!=1
      ans << b[i]
      ans << 1
    else
        ans << b[i]
    end
end
ans << b[a-1]
puts ans.join(" ")

def gcd(a,b)
	return b>0 ? gcd(b,a%b) : a
end

n=gets.to_i
a=gets.split(' ')
print a[0]
for i in 1..a.size-1
	print " 1" if gcd(a[i].to_i,a[i-1].to_i)>1
	print " "+a[i]
end
puts