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.

var n = parseInt(readline());
var i, r, s = {}, h = [], w = [], max = 0;

function get_winners() {
    for (var u in s) {
        if (!w.length){
            w.push(u);
            max = s[u];
        } else {
            if (s[u] > max) {
                max = s[u];
                w = [u];
            } else if (s[u] === max) {
                w.push(u);
            }
        }
    }

    if (w.length === 1) return w[0];
    for (var i=0; i<h.length; i++){
        if (w.indexOf(h[i][0]) > -1 && h[i][1] >= max){
            return h[i][0];
        }
    }
}

for (i=0; i<n; i++){
    r = readline().split(' ');

    if (r[0] in s)
        s[r[0]] += parseInt(r[1]);
    else
        s[r[0]] = parseInt(r[1]);

    h.push([r[0],s[r[0]]]);
}

print(get_winners());

var step = readline();
var gamers = [];
var mass = []

for(var i=0;i<step;i++){
	//заполняем массив ходов
	mass[i] = readline().split(" ");
	addScore(mass[i][0],mass[i][1]);
}

//запоняем турнирную таблицу и сортируем её, на первом месте те кто больщше набрал
function addScore(name,score) {
	var index = gamers.findIndex(function(el,index,arr){
		return el.name == name;
	})
	if(index == -1) {
		gamers.push({name:name,score:parseInt(score,10)});
	} else {
		gamers[index].score += parseInt(score,10);
	}
	gamers.sort(function(a,b){
		if(a.score<b.score) return 1;
		if(a.score>b.score) return -1;
		if(a.score==b.score) return 0;
	})
}

//находим максимум
var maxScore = gamers[0].score;

//если победителей несколько то выбираем того из них, кто первый за всю игру набрал максимум
if(gamers[0].score == gamers[1].score) {
	//находим полный список всех набравших максимум
	var winners = gamers.filter(function(el){
		return el.score == maxScore;
	})

	//учитиываем только ходы тех кто набрал максимум, фильтруем массив ходов
	mass = mass.filter(function(el,index,arr){
		var ind = winners.findIndex(function(el2,inde2x,arr2){
			return el2.name == el[0];
		})
		if( ind > -1 ) {
			return true
		}else{
			return false
		}
	})

	var gamers2 = [];

	//заполняем турнирную таблицу до тех пор, пока один из них не наберет максимум, тот и победитель
	for(var i=0;i<mass.length;i++){
		var index = gamers2.findIndex(function(el,index,arr){
			return el.name == mass[i][0];
		})
		if(index == -1) {
			gamers2.push({name:mass[i][0],score:parseInt(mass[i][1],10)});
			if(gamers2[gamers2.length-1].score>= maxScore) {
				write(gamers2[gamers2.length-1].name);
				break;
			}
		} else {
			gamers2[index].score += parseInt(mass[i][1],10);
			if(gamers2[index].score>= maxScore) {
				write(gamers2[index].name);
				break;
			}
		}
	}
} else {
	write(gamers[0].name);
}

var step = readline();
var gamers = [];
var winner = "";
var mass = []
for(var i=0;i<step;i++){
	mass[i] = readline().split(" ");
	addScore(mass[i][0],mass[i][1]);
}

function addScore(name,score) {
	var index = gamers.findIndex(function(el,index,arr){
		return el.name == name;
	})
	if(index == -1) {
		gamers.push({name:name,score:parseInt(score,10)});
	} else {
		gamers[index].score += parseInt(score,10);
	}
	gamers.sort(function(a,b){
		if(a.score<b.score) return 1;
		if(a.score>b.score) return -1;
		if(a.score==b.score) return 0;
	})
}

var maxScore = gamers[0].score;
if(gamers[0].score == gamers[1].score) {
	var winners = gamers.filter(function(el){
		return el.score == maxScore;
	})
	mass = mass.filter(function(el,index,arr){
		var ind = winners.findIndex(function(el2,inde2x,arr2){
			return el2.name == el[0];
		})
		if( ind > -1 ) {
			return true
		}else{
			return false
		}
	})
	//write(mass.length);
	var gamers2 = [];

	for(var i=0;i<mass.length;i++){
		var index = gamers2.findIndex(function(el,index,arr){
			return el.name == mass[i][0];
		})
		if(index == -1) {
			gamers2.push({name:mass[i][0],score:parseInt(mass[i][1],10)});
			if(gamers2[gamers2.length-1].score>= maxScore) {
				write(gamers2[gamers2.length-1].name);
				break;
			}
		} else {
			gamers2[index].score += parseInt(mass[i][1],10);
			if(gamers2[index].score>= maxScore) {
				write(gamers2[index].name);
				break;
			}
		}
	}
} else {
	write(gamers[0].name);
}

run();

function run() {
  var scores = scoreboard();

  var lines = Number(readline()),
      log = [],
      line;
  for (var i = 0; i < lines; i++) {
    line = readline();
    log.push(line);
    scores.addScore.apply(null, line.split(' '));
  }

  var result = scores.result();

  print(getWinner(log, result.winners, result.hiscore));
}

function scoreboard() {
  var scores = {};
  return {
    // record a round
    addScore: function(player, score) {
      score = Number(score);
      if (!scores[player]) scores[player] = score;
      else scores[player] += score;
    },
    result: function() {
      var players = Object.getOwnPropertyNames(scores),
          player,
          hiscore = -Infinity;

      // iterate through the scores object to find the highest score
      for (i = 0; i < players.length; i++) {
        player = players[i];
        hiscore = Math.max(hiscore, scores[player]);
      }

      // find the players that have the highest score
      var winners = [];
      for (i = 0; i < players.length; i++) {
        player = players[i];
        if (scores[player] === hiscore) winners.push(player);
      }

      return {
        hiscore: hiscore,
        winners: winners
      };
    },

  }
}

function getWinner(logs, winners, hiscore) {
  var scores = {},
      line, player, score;
  for (var i = 0; i < logs.length; i++) {
    line = logs[i].split(' ');
    player = line[0];
    score = Number(line[1]);

    if (!scores[player]) scores[player] = score;
    else scores[player] += score;

    if (scores[player] >= hiscore && winners.indexOf(player) !== -1) return player;
  }
}

/*
 Modification test of the solution
originally coded by aleksey.danchin.
*/

var n = readline(), m = {}, t = [], r = [], k, y, s;

while (n--) {
	s = readline().split(' ');
	m[s[0]] = m[s[0]] ? m[s[0]] + +s[1] : +s[1];
	t.push([s[0], m[s[0]]]);
}

for (y in m) r.push(m[y]);
k = Math.max(...r);

print(t.find(e => e[1] >= k && m[e[0]] === k)[0]);

var count = parseInt(readline());
var input = [];

for (var i = 0; i < count; i++) {
  input.push(readline());
}

var finalScores = {};
for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    finalScores[name] = (finalScores[name] || 0) + roundScore;
  }
}

// find maxScore of finalScores
var maxScore = Object.keys(finalScores).reduce(function(acc, name) {
  return Math.max(acc, finalScores[name]);
}, 0);

// first player with at least maxScore
var scores = {};
for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    if (finalScores[name] !== maxScore) {
      continue;
    }

    scores[name] = (scores[name] || 0) + roundScore;
    if (scores[name] >= maxScore) {
      print(name);
      break;
    }
  }
}

var count = parseInt(readline());
var input = [];

for (var i = 0; i < count; i++) {
  input.push(readline());
}

var players = {};
var scores = {}; // map score to players with that score in chron order

for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    // remove player from old score list
    var oldScore = players[name];
    if (Number.isInteger(oldScore)) {
      var playersList = scores[oldScore.toString()];
      if (Array.isArray(playersList)) {
        var nameIndex = playersList.indexOf(name);
        if (nameIndex !== -1) {
          playersList.splice(nameIndex, 1);
          if (playersList.length == 0) {
            // remove from scores hash
            delete scores[oldScore.toString()];
          }
        }
      }
    }

    oldScore = oldScore || 0;
    var newScore = oldScore + roundScore;

    // update score
    players[name] = newScore;
    scores[newScore.toString()] = scores[newScore.toString()] || [];
    scores[newScore.toString()].push(name);
  }
}

// list of players ending with max score
var scoresList = Object.keys(scores);
if (scoresList.length > 0) {
  scoresList.sort(function(a, b) {
    return parseInt(b) - parseInt(a);
  });
  var maxScore = scoresList[0];
  var playersList = scores[maxScore];
}

// first player with at least max roundScore
var finalPlayers = {};
for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    if (playersList.indexOf(name) !== -1) {
      finalPlayers[name] = finalPlayers[name] || 0;
      finalPlayers[name] += roundScore;

      if (finalPlayers[name] >= maxScore) {
        print(name);
        break;
      }
    }
  }
}

var N = readline() - 0;
//var N = 3;

var originalData = [];
//var originalData = [ ["mike","3"] , ["andrew" , "5"] , ["mike" , "2"]] ;

var initHash = {};

var bestKey;

for (var i = 0 ; i < N ; i++)
{
    originalData[i] = readline().split(' ');
    var name = originalData[i][0];
    var scoreDelt = parseInt(originalData[i][1]);

    initHash[ name ] = (initHash[name] || 0 ) + scoreDelt;

    if (initHash[name] > (initHash[bestKey] || -1<<63))
    {
        bestKey = name;
    }
}

for (var i = 0 ; i < N ; i++)
{
    var name = originalData[i][0];
    if (initHash[name] > (initHash[bestKey] || -1<<63))
    {
        bestKey = name;
    }
}

var secondHash = {};
var BestScore = initHash[bestKey];
var winner = "";
debugger;

for (var i = 0 ; i < N ; i++)
{
    var name = originalData[i][0];
    var scoreDelt = parseInt(originalData[i][1]);

    var current = (secondHash[name] || 0) + scoreDelt;
    secondHash[name] = current;

    if (current >= BestScore && BestScore == initHash[name] )
    {
        winner = name;
        break;
    }
}

print(winner);
//console.log(winner);

var nRounds = parseInt(readline());
var lines = [];
var d = {};
for(var n=nRounds ; n > 0; n--) {
    var oneLine = readline();
    lines.push(oneLine);
    var line = oneLine.split(' ');
    var name = line[0];
    var score = parseInt(line[1]);
    if (!d[name]) d[name] = 0;
    d[name] += score;
    //print(".." + name + " = " + score + " === " + d[name]);
}

var highestScore = -999999;
for (var key in d) {
  if (d.hasOwnProperty(key)) {
      if (d[key] > highestScore) highestScore = d[key];
  }
}
//print("highestScore="+highestScore);

var names = {};
for (var key in d) {
    if (d.hasOwnProperty(key)) {
        if (d[key] >= highestScore) {
            names[key] = key;
            //print("name="+key);
        }
    }
}

var d = {};
var highestName = "";
for(var n=0 ; n < nRounds; n++) {
    var oneLine = lines[n];
    var line = oneLine.split(' ');
    var name = line[0];
    var score = parseInt(line[1]);
    if (!d[name]) d[name] = 0;
    d[name] += score;
    //print(".." + name + " = " + score + " === " + d[name]);
    if (d[name] >= highestScore) {
        //print(" found highestScore with name: "+name);
        if (names[name]) {
            //print(" .. AND they are a winner.");
            highestName = name;
            break;
        }
    }
}

print(highestName);

t = parseInt(readline());

i = 0;
rounds = [];
scores = {};

for(round=0; round<t; round++) {
    rounds[round] = readline().split(' ');

    player = rounds[round][0];
    change = parseInt(rounds[round][1]);

    if (scores[player] === undefined) scores[player] = change;
    else scores[player] += change;
}

const max = Object.keys(scores).reduce(
    (a, b) => Math.max(a,scores[b]), Number.NEGATIVE_INFINITY
);

const bestScorers = Object.keys(scores).filter(player => scores[player] == max);

winner = null;
scores = {};

for(round=0; round<t && winner === null; round++) {
    player = rounds[round][0];
    change = parseInt(rounds[round][1]);

    if (bestScorers.includes(player)) {
        if (scores[player] === undefined) scores[player] = change;
        else scores[player] += change;

        if(scores[player] >= max) winner = player;
    }
}

print(winner);

var c = parseInt( readline() );

var map = {};
var points = [];
var names = [];
for(var i=0; i<c; i++){
	var line = readline().split(' ');
	var key = '$'+line[0];
	var point = parseInt(line[1]);
	var name = line[0];
	points.push(point);
	names.push(name);

	if(map[key]){
		map[key].point += point;
		//map[key].step = i;
	}else{
		map[key]={
			name: line[0],
			point: point
		}
	}
}

var winner = {
	point:-1E9,
	step:1E9
}
var max = -1E9;
//console.log( map );
for(var key in map){
	var p = map[key].point;
	if( p > max ){
		max = p;
	}
}

var map2 = {}
for(var i=0;i<c;i++){
	var point = points[i];
	var key = '$'+names[i];
	if(map2[key]){
		map2[key].point += point;
		//map[key].step = i;
	}else{
		map2[key]={
			name: line[0],
			point: point
		}
	}

	if(map[key].point == max && map2[key].point>=max){
		print( names[i] );
		break;
	}
}

function rda(){ return readline().split(" ").map(Number); }
function rdn(){ return Number(readline()); }

var n = rdn();
var inp = [];
for(var i = 0; i < n; i++){
    var x = readline().split(" ");
    x[1] = Number(x[1]);
    inp.push(x);
}

var game = {};
for(var i = 0; i < n; i++){
    if(!game[inp[i][0]]){
        game[inp[i][0]] = inp[i][1];
    }else{
        game[inp[i][0]] += inp[i][1];
    }
}

var max = -Infinity;
var winners = [];
for(var name in game){
    max = Math.max(max, game[name]);
}
for(var name in game){
    if(game[name] == max) winners.push(name);
}
delete game;

var game2 = {};
for(var i = 0; i < n; i++){
    if(!game2[inp[i][0]]){
        game2[inp[i][0]] = inp[i][1];
    }else{
        game2[inp[i][0]] += inp[i][1];
    }
    if(game2[inp[i][0]] >= max && winners.indexOf(inp[i][0]) != -1){
        write(inp[i][0]);
        break;
    }
}

var n = +readline();

var userScores = {}, userRounds = [], maxScore = 0, firstUsers = {};

for (var i = 0; i < n; i++) {
  var arr = readline().split(' '),
      name = arr[0],
      score = +arr[1];

  var newScore = (userScores[name] || 0) + score;
  userScores[name] = newScore;

  userRounds[i] = {
    name : name,
    score : newScore
  }

}

//console.log(userScores, userRounds);

var maxScore = 0, bestUsers = [], bestUserRounds = 0;
for (var name in userScores) {
  if (userScores[name] > maxScore) {
    maxScore = userScores[name];
    bestUsers = [name];
  } else if (userScores[name] === maxScore) {
    bestUsers.push(name);
  }
}

//console.log(userRounds);

if (bestUsers.length === 1) print(bestUsers[0]);
else {
  for (var i =0, l = userRounds.length; i < l; i++) {
    if (bestUsers.indexOf(userRounds[i].name) >= 0 && userRounds[i].score >= maxScore) {
      print(userRounds[i].name);
      break;
    }
  }
}

main();

function main() {
    const count = readline();
    var players = {};
    var playersEnd = {};
    var turns = [];
    var winner = "";
    for (var i = 0; i < count; i++) {
        var nameScore = readline().split(" ");
        var name = nameScore[0];
        var score = +nameScore[1];
        players[name] = players[name] ? players[name] + score : score;
        turns.push(nameScore);
    }

    var maxScore = Object.keys(players).reduce( (max, player) => {
        return max = players[player] > max ? players[player] : max;
    }, 0);

    for (var i = 0; i < turns.length; i++) {
        var nameEnd = turns[i][0];
        var scoreEnd = +turns[i][1];
        playersEnd[nameEnd] = playersEnd[nameEnd] ? playersEnd[nameEnd] + scoreEnd : scoreEnd;
        if (playersEnd[nameEnd] >= maxScore && players[nameEnd] === maxScore) {
            winner = nameEnd;
            break;
        }
    }
    print(winner);
}

;(function () {
	var n = +readline(), m = {}, t = [], k = 0;

	while (n--) {
		var s = readline().split(' ');
		m[s[0]] = m[s[0]] ? m[s[0]] + +s[1] : +s[1];
		t.push([s[0], m[s[0]]]);
	}

	k = Math.max.apply(null, (function () {
		var ret = [];
		for (var key in m) ret.push(m[key]);
		return ret;
	})());

	print(t.filter(function (e) { return e[1] >= k && m[e[0]] === k; })[0][0]);

}).call(this)

  var n = +readline()
  var rs = []
  var v
  for (var t = 0; t < n; t++) {
    rs.push(readline().split(' '))
  }
  var sc = rs.reduce(function (a, l) {
    a[l[0]] = (a[l[0]] || 0) + +l[1]
    return a
  }, {})
  var ms = 0
  var mso = {}
  for (var p in sc) {
    if (sc[p] > ms) {
      mso = {}
      mso[p] = true
      ms = sc[p]
    } else if (sc[p] == ms) {
      mso[p] = true
    }
  }
  var vs = Object.keys(mso)
  if (vs.length == 1)
    v = vs[0]
  if (!v) {
    sc = {}
    for (t = 0; t < n; t++) {
      p = rs[t][0]
      s = +rs[t][1]
      if (((sc[p] = (sc[p] || 0) + s) >= ms) && mso[p]) {
        v = p
        break
      }
    }
  }
  print(v)

const n = parseInt(readline());
const tour = [];
const gamers = {};
const gamers2 = {};
for(var i = 0; i < n; i++) {
  var ans = readline().split(' ');
  tour.push({ name: ans[0], value: parseInt(ans[1]) });
}
tour.forEach(item => {
  const name = item.name, value = item.value;
  gamers[name] = gamers[name] ? gamers[name] + value : value;
});
var max = 0;
for(var key in gamers) {
  max = gamers[key] > max ? gamers[key] : max;
}
for(var i = 0; i < n; i++) {
  var name = tour[i].name, value = tour[i].value;
  gamers2[name] = gamers2[name] ? gamers2[name] + value : value;
  if(gamers[name] === max && gamers2[name] >= max) {
    print(name);
    break;
  }
}

var intGamesCount=Number(readline().trim());
//print('intGamesCount:'+intGamesCount);
var arrPlayers=[];
var arrScores=[];
var arrGames=[];
var strName='';
var intGameScore=0;
var intBestScore=0;
var i=0; // Current player index
var s='';
var arrGame=['',0];
var arrPlayerGames=[''];
var arrPretenders=[];

for (var intGame=0;intGame<intGamesCount;intGame++){
    arrGame=readline().split(' ');
    strName=String(arrGame[0]);
    intGameScore=Number(arrGame[1]);
    i=arrPlayers.indexOf(strName);
//    print('strName:intGameScore:i ['+strName+':'+intGameScore+':'+i+']');
    if (i<0) {
        arrPlayers.push(strName);
        arrScores.push(intGameScore);
        arrGames.push([]);
        arrGames[arrGames.length-1].push([intGameScore,intGame]);
//        print('arrGames[i]:'+arrGames[arrGames.length-1]);
//        print(strName+' game score '+intGameScore);
    } else {
        arrScores[i]=arrScores[i]+intGameScore;
        intBestScore=arrGames[i][arrGames[i].length-1][0];
//        print(strName+' update score from '+intBestScore+' to '+arrScores[i]);
        if (arrScores[i]>intBestScore) {
//            arrGames[i]=arrScores[i]+':'+intGame+':'+arrGames[i];
            arrGames[i].push([arrScores[i],intGame]);
//            print('arrGames[i]:'+arrGames[i]);
        }
    }
}

intBestScore=0;

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore<arrScores[i]) {
        intBestScore=arrScores[i];
    }
}

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore===arrScores[i]) {
        arrPretenders.push(i);
    }
}
//print('intBestScore:'+intBestScore);
//print('arrPretenders:'+arrPretenders);

intGame=intGamesCount+1;
strName='';

for (var intPretender of arrPretenders) {
    for (var i=0;i<arrGames[intPretender].length;i++) {
        if ((arrGames[intPretender][i][0]>=intBestScore) && (arrGames[intPretender][i][1]<intGame)) {
            intGame=arrGames[intPretender][i][1];
            strName=arrPlayers[intPretender];
            break;
        }
    }
}
//print('intGame:'+intGame);
print(strName);

var intGamesCount=Number(readline().trim());
var arrPlayers=[];
var arrScores=[];
var arrGames=[];
var strName='';
var intGameScore=0;
var intBestScore=0;
var i=0; // Current player index
var s='';
var arrGame=['',0];
var arrPretenders=[];

for (var intGame=0;intGame<intGamesCount;intGame++){
    arrGame=readline().split(' ');
    strName=String(arrGame[0]);
    intGameScore=Number(arrGame[1]);
    i=arrPlayers.indexOf(strName);
    if (i<0) {
        arrPlayers.push(strName);
        arrScores.push(intGameScore);
        arrGames.push([]);
        arrGames[arrGames.length-1].push([intGameScore,intGame]);
    } else {
        arrScores[i]=arrScores[i]+intGameScore;
        intBestScore=arrGames[i][arrGames[i].length-1][0];
        if (arrScores[i]>intBestScore) {
            arrGames[i].push([arrScores[i],intGame]);
        }
    }
}

intBestScore=0;

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore<arrScores[i]) {
        intBestScore=arrScores[i];
    }
}

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore===arrScores[i]) {
        arrPretenders.push(i);
    }
}

intGame=intGamesCount+1;
strName='';

for (var intPretender of arrPretenders) {
    for (var i=0;i<arrGames[intPretender].length;i++) {
        if ((arrGames[intPretender][i][0]>=intBestScore) && (arrGames[intPretender][i][1]<intGame)) {
            intGame=arrGames[intPretender][i][1];
            strName=arrPlayers[intPretender];
            break;
        }
    }
}

print(strName);

var intGamesCount=Number(readline().trim());
//print('intGamesCount:'+intGamesCount);
var arrPlayers=[];
var arrScores=[];
var arrGames=[];
var strName='';
var intGameScore=0;
var intBestScore=0;
var i=0; // Current player index
var s='';
var arrGame=['',0];
var arrPlayerGames=[''];
var arrPretenders=[];

for (var intGame=0;intGame<intGamesCount;intGame++){
    arrGame=readline().split(' ');
    strName=String(arrGame[0]);
    intGameScore=Number(arrGame[1]);
    i=arrPlayers.indexOf(strName);
//    print('strName:intGameScore:i ['+strName+':'+intGameScore+':'+i+']');
    if (i<0) {
        arrPlayers.push(strName);
        arrScores.push(intGameScore);
        arrGames.push([]);
        arrGames[arrGames.length-1].push([intGameScore,intGame]);
//        print('arrGames[i]:'+arrGames[arrGames.length-1]);
//        print(strName+' game score '+intGameScore);
    } else {
        arrScores[i]=arrScores[i]+intGameScore;
        intBestScore=arrGames[i][arrGames[i].length-1][0];
//        print(strName+' update score from '+intBestScore+' to '+arrScores[i]);
        if (arrScores[i]>intBestScore) {
//            arrGames[i]=arrScores[i]+':'+intGame+':'+arrGames[i];
            arrGames[i].push([arrScores[i],intGame]);
//            print('arrGames[i]:'+arrGames[i]);
        }
    }
}

intBestScore=0;

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore<arrScores[i]) {
        intBestScore=arrScores[i];
    }
}

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore===arrScores[i]) {
        arrPretenders.push(i);
    }
}
//print('intBestScore:'+intBestScore);
//print('arrPretenders:'+arrPretenders);

intGame=intGamesCount+1;
strName='';

for (var i=0;i<arrPretenders.length;i++) {
    intPretender=arrPretenders[i];
    for (var j=0;j<arrGames[intPretender].length;j++) {
        if ((arrGames[intPretender][j][0]>=intBestScore) && (arrGames[intPretender][j][1]<intGame)) {
            intGame=arrGames[intPretender][j][1];
            strName=arrPlayers[intPretender];
            break;
        }
    }
}
//print('intGame:'+intGame);
print(strName);

var intGamesCount=Number(readline().trim());
//print('intGamesCount:'+intGamesCount);
var arrPlayers=[];
var arrScores=[];
var arrGames=[];
var strName='';
var intGameScore=0;
var intBestScore=0;
var i=0; // Current player index
var s='';
var arrGame=['',0];
var arrPlayerGames=[''];
var arrPretenders=[];

for (var intGame=0;intGame<intGamesCount;intGame++){
    arrGame=readline().split(' ');
    strName=String(arrGame[0]);
    intGameScore=Number(arrGame[1]);
    i=arrPlayers.indexOf(strName);
//    print('strName:intGameScore:i ['+strName+':'+intGameScore+':'+i+']');
    if (i<0) {
        arrPlayers.push(strName);
        arrScores.push(intGameScore);
        arrGames.push([]);
        arrGames[arrGames.length-1].push([intGameScore,intGame]);
//        print('arrGames[i]:'+arrGames[arrGames.length-1]);
//        print(strName+' game score '+intGameScore);
    } else {
        arrScores[i]=arrScores[i]+intGameScore;
        intBestScore=arrGames[i][arrGames[i].length-1][0];
//        print(strName+' update score from '+intBestScore+' to '+arrScores[i]);
        if (arrScores[i]>intBestScore) {
//            arrGames[i]=arrScores[i]+':'+intGame+':'+arrGames[i];
            arrGames[i].push([arrScores[i],intGame]);
//            print('arrGames[i]:'+arrGames[i]);
        }
    }
}

intBestScore=0;

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore<arrScores[i]) {
        intBestScore=arrScores[i];
    }
}

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore===arrScores[i]) {
        arrPretenders.push(i);
    }
}
//print('intBestScore:'+intBestScore);
//print('arrPretenders:'+arrPretenders);

intGame=intGamesCount+1;
strName='';

for (var i=0;i<arrPretenders.length;i++) {
    intPretender=arrPretenders[i];
    for (var j=0;j<arrGames[intPretender].length;j++) {
        if ((arrGames[intPretender][j][0]>=intBestScore) && (arrGames[intPretender][j][1]<intGame)) {
            intGame=arrGames[intPretender][j][1];
            strName=arrPlayers[intPretender];
        }
    }
}
//print('intGame:'+intGame);
print(strName);

n=Number(readline());
line=[]
score={}
for (i=0;i<n;i++) {
	line[i]=readline().split(" ");
	line[i][1]=Number(line[i][1]);
	if (line[i][0] in score) score[line[i][0]]+=line[i][1];
	else score[line[i][0]]=line[i][1];
}
max=0;
top={};
for (name in score) {
	if (score[name]>max) {
		max=score[name];
		top={};
		top[name]=true;
	} else if (score[name]==max)
		top[name]=true;
}
for (name in score) score[name]=0;
for (i=0;i<n;i++)
	if (line[i][0] in top) {
		score[line[i][0]]+=line[i][1];
		if (score[line[i][0]]>=max) {
			print(line[i][0]);
			break;
		}
	}

rounds = parseInt(readline())

inputs = []
while (rounds > 0) {
    inputs.push(readline())
    rounds--
}

var scores = {}
var winner = {
    name: "",
    score: 0
}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (scores[splitItem[0]] != null) {
            var foundScore = scores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            scores[splitItem[0]] = foundScore
            //print("Found Score: " + splitItem[0] + " " + splitItem[1] + " " + scores[splitItem[0]])
        } else {
            scores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            //print("New Score: " + splitItem[0] + " " + scores[splitItem[0]])
        }

    }
}

var highestTotalScore = 0
for (item in scores) {
    score = scores[item]
    if (score > highestTotalScore)
    {
        highestTotalScore = score
    }
}

//print(highestTotalScore)
var testScores = {}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (testScores[splitItem[0]] != null) {
            var foundScore = testScores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            testScores[splitItem[0]] = foundScore
            if (testScores[splitItem[0]] >= highestTotalScore && scores[splitItem[0]] == highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = testScores[splitItem[0]]
                break;
            }
            //print("Found Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        } else {
            testScores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            if (newScore >= highestTotalScore && scores[splitItem[0]] == highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = newScore
                break;
            }
            //print("New Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        }
    }
}

print(winner.name)

function main()
{
    xh={};
    line=[];
    var ans;
    n=Number(readline());
    for(i=1;i<=n;i++)
    {
        line[i]=readline().split(" ");
        line[i][1]=Number(line[i][1]);
        if(line[i][0] in xh) xh[line[i][0]]+=line[i][1];
        else xh[line[i][0]]=line[i][1];
    }
    maxs=Number(-1);
    for(name in xh)
    {
        if(xh[name]>maxs) maxs=xh[name];
        //print(name,xh[name]);
    }
    for(name in xh)
        if(xh[name]<maxs) xh[name]=-100000000;
        else xh[name]=0;
    for(i=1;i<=n;i++)
    {
        xh[line[i][0]]+=line[i][1];
        if(xh[line[i][0]]>=maxs) {ans=line[i][0];break;}
    }
    print(ans);
}
main();

var numberOfRoundsPlayed = Number(readline());

var roundInfo;
var scores = {};
var scoreLog = [];
for(var i = 0; i < numberOfRoundsPlayed; i++) {
    roundInfo = readline();
    roundInfo = roundInfo.split(" ");
    var player = roundInfo[0];
    var playerScore = parseInt(roundInfo[1]);

    if (player in scores) scores[player] += playerScore;
    else scores[player] = playerScore;
    // print(`i: ${i}\tplayer: ${player}\tscore: ${playerScore}\ttotal: ${scores[player]}`);

    scoreLog.push([player, scores[player]]);
}

// print('===');
// print(`scores: ${JSON.stringify(scores)}`);
// print(`scoreLog: ${JSON.stringify(scoreLog)}`);
var max = -1;
var winners = [];
for (var p in scores) {
    if (scores[p] > max) {
        max = scores[p];
        winners = [p];
    } else if (scores[p] === max) {
        winners.push(p);
    }
}

scoreLog.some(e => {
    // print(e);
    if (winners.indexOf(e[0]) > -1 && e[1] >= max) {
        print(e[0]);
        return true;
    }
})

var num = Number(readline());

var round, player, score;
var scores = {};
var log = [];
for(var i = 0; i < num; i++) {
    round= readline().split(" ");
    player = round[0];
    score = parseInt(round[1]);
    if (player in scores) scores[player] += score;
    else scores[player] = score;
    log.push([player, scores[player]]);
}

var playerList = Object.keys(scores);

var max = scores[playerList.sort((a, b) => scores[b] - scores[a])[0]];

var winners = playerList.filter(player => scores[player] === max)

log.some(e => {
    player = e[0]; score = e[1];
    if (winners.includes(player) && score >= max) {
        print(player); return true;
    }
})

var num = Number(readline());

var round, player, score;
var scores = {};
var log = [];
for(var i = 0; i < num; i++) {
    round= readline().split(" ");
    player = round[0];
    score = parseInt(round[1]);
    if (player in scores) scores[player] += score;
    else scores[player] = score;
    log.push([player, scores[player]]);
}

var playerList = Object.keys(scores).slice(0);

var winnerScore = playerList.sort((a, b) => {
    // print(`a: ${a}, score: ${scores[a]}`);
    // print(`b: ${b}, score: ${scores[b]}`);
    return scores[b] - scores[a];
})[0];
winnerScore = scores[winnerScore];

// print(winnerScore)

var winnerList = playerList.filter(player => {
    return scores[player] === winnerScore;
})

log.some(e => {
    if (winnerList.includes(e[0]) && e[1] >= winnerScore) {
        print(e[0]);
        return true;
    }
})

var num = Number(readline());

var round, player, score;
var scores = {};
var log = [];
for(var i = 0; i < num; i++) {
    round= readline().split(" ");
    player = round[0];
    score = parseInt(round[1]);
    if (player in scores) scores[player] += score;
    else scores[player] = score;
    log.push([player, scores[player]]);
    // print(`i: ${i}\tplayer: ${player}\tscore: ${playerScore}\ttotal: ${scores[player]}`);
}

// print('===');
// print(`scores: ${JSON.stringify(scores)}`);
// print(`log: ${JSON.stringify(log)}`);
var max = -1;
var winners = [];
for (player in scores) {
    if (scores[player] > max) {
        max = scores[player];
        winners = [player];
    } else if (scores[player] === max) {
        winners.push(player);
    }
}

log.some(e => {
    player = e[0];
    score = e[1];
    if (winners.indexOf(player) > -1 && score >= max) {
        print(player);
        return true;
    }
})

const readline = require('readline');
const rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout,
	terminal: false
});
const last = array => array[array.length - 1];

const table = [];
let n, counter = 0;

rl.on('line', line => {
	if (!n) {
		n = parseInt(line);
	} else {
		const [name, resS] = line.split(' ');
		const res = parseInt(resS);

		let userIndex = table.findIndex(i => i.name === name);
		if (userIndex < 0) {
			userIndex = table.length;
			table.push({
				name,
				log: [],
				score: res
			});
			table[userIndex].log[counter] = res;
		} else {
			const log = table[userIndex].log;
			const score = last(log) + res;
			table[userIndex].score = score;
			table[userIndex].log[counter] = score;
		}

		counter++;
		if (counter === n) {
			let max = 0;
			for (let i = 0; i < table.length; i++) {
				if (table[i].score > max) {
					max = table[i].score;
				}
			}
			const winners = table.filter(i => i.score === max);
			if (winners.length === 1) {
				console.log(winners[0].name);
			} else {
				console.log(
					winners.map(i => {
						i.first = i.log.findIndex(j => j && j >= max);
						return i;
					}).sort((a, b) => {
						if (a.first < b.first) {
							return -1;
						}
						if (a.first > b.first) {
							return 1;
						}
						return 0;
					})[0].name
				);
			}
			rl.close();
		}
	}
});

const solve = (t, players) => {
    let map = new Map();
    for (let i = 0; i < t; i++) {
        let p = players[i];
        if (map.has(p[0])) {
            map.set(p[0], p[1] + map.get(p[0]));
        } else {
            map.set(p[0], p[1]);
        }
    }
    let sMap = sortMap(map, players);
    return sMap.keys().next().value;
};

const sortMap = (map, players) => { // sort map based on value, if value same, sort based on index who scored at least m points first
    return new Map([...map].sort((a, b) => {
        if (a[1] == b[1]) {
            let score = a[1];
            let aIdx;
            let bIdx;
            let aSum = 0;
            let bSum = 0;
            for (let i = 0; i < players.length; i++) {
                let p = players[i];
                if (i == players.length - 1) aIdx = i;
                if (aSum >= score) {
                    aIdx = i - 1;
                    break;
                }
                if (p[0] == a[0]) {
                    aSum += p[1];
                }
            }
            for (let i = 0; i < players.length; i++) {
                let p = players[i];
                if (i == players.length - 1) bIdx = i;
                if (bSum >= score) {
                    bIdx = i - 1;
                    break;
                }
                if (p[0] == b[0]) {
                    bSum += p[1];
                }
            }
            return aIdx - bIdx;
        }
        return b[1] - a[1];
    }));
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" "));
    });

    rl.on('close', () => {
        let t = Number(input[0][0]);
        let players = input.slice(1).map(x => [x[0], Number(x[1])]);
        console.log(solve(t, players));
    });

};

main()

const solve = (t, players) => {
    let map = new Map();
    for (let i = 0; i < t; i++) {
        let p = players[i];
        if (map.has(p[0])) {
            map.set(p[0], p[1] + map.get(p[0]));
        } else {
            map.set(p[0], p[1]);
        }
    }
    let sMap = sortMapByKey(map, players);
    return sMap.keys().next().value;
};

const sortMapByKey = (map, players) => {
    return new Map([...map].sort((a, b) => {
        if (a[1] == b[1]) {
            let score = a[1];
            let aIdx;
            let bIdx;
            let aSum = 0;
            let bSum = 0;
            for (let i = 0; i < players.length; i++) {
                let p = players[i];
                if (i == players.length - 1) aIdx = i;
                if (aSum >= score) {
                    aIdx = i - 1;
                    break;
                }
                if (p[0] == a[0]) {
                    aSum += p[1];
                }
            }
            for (let i = 0; i < players.length; i++) {
                let p = players[i];
                if (i == players.length - 1) bIdx = i;
                if (bSum >= score) {
                    bIdx = i - 1;
                    break;
                }
                if (p[0] == b[0]) {
                    bSum += p[1];
                }
            }
            return aIdx - bIdx;
        }
        return b[1] - a[1];
    }));
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" "));
    });

    rl.on('close', () => {
        let t = Number(input[0][0]);
        let players = input.slice(1).map(x => [x[0], Number(x[1])]);
        console.log(solve(t, players));
    });

};

main()

var i = ''
var lines = [];
var N = 0;
var arr = [];

process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  lines = i.split(EOL) /*your input text, split by lines*/
  main();
})
function debug(item) {
  if (N == 5) console.log(item);
}

function readline() {
  return lines.shift();
}

function main() {
  debug(lines.length);
  debug(lines);
  N = readline() - 0;
  arr = [];
  for (let i = 0; i < N; i++) {
    let str = readline();
    arr.push(str.trim());
  }

  console.log(winner(arr));
}

function winner(arr) {
  let hash = {};
  let rounds = [];
  let max = -1;

  for (let str of arr) {
    let [username, newPoint] = str.split(' ');
    newPoint -= 0;
    let point = hash[username] ? hash[username] + newPoint : newPoint;
    hash[username] = point;
    rounds.push({
      username, point
    })
  }

  let keys = Object.keys(hash);
  let values = keys.map(k => hash[k]);
  max = Math.max.apply(null, values);

  let candidates = keys.filter(k => hash[k] == max);
  if (candidates.length == 1) return candidates[0];

  debug(rounds);
  debug(candidates);

  for (let round of rounds) {
    if (candidates.indexOf(round.username) > -1 && round.point >= max) {
      return round.username;
    }
  }
}

function get_with_default(m, k, d) {
  return m.has(k) ? m.get(k) : d;
};

function player_points(pps) {
  const m = new Map();
  for (const pp of pps) {
    const [a, b] = pp.split(/\s+/);
    const pts = get_with_default(m, a, 0) + Number(b);
    m.set(a, pts);
  }
  return m;
};

function players_with_max_points(m) {
  const plyrs = new Set();
  let pts_max = (- Infinity);
  for (const [a, b] of m.entries()) {
    if (b > pts_max) {
      plyrs.clear();
      plyrs.add(a);
      pts_max = b;
    } else if (b === pts_max) {
      plyrs.add(a);
    } else {
      // do nothing ...
    }
  }
  return [pts_max, plyrs];
};

function first_to_reach_max_points(pts_max, plyrs, pps) {
  const m = new Map();
  for (const pp of pps) {
    const [a, b] = pp.split(/\s+/);
    if (plyrs.has(a)) {
      const pts = get_with_default(m, a, 0) + Number(b);
      if (pts >= pts_max) {
        return a;
      } else {
        m.set(a, pts);
      }
    }
  }
  throw Error('could not find first to reach max points');
};

function solve(pps) {
  const m = player_points(pps);
  const [pts_max, plyrs] = players_with_max_points(m);
  if (plyrs.size === 1) {
    return plyrs.values().next().value;
  } else {
    return first_to_reach_max_points(pts_max, plyrs, pps)
  }
}

function main(lines) {
  const pps = [];
  lines.shift();
  for (const line of lines) {
    let t = line.trim();
    if (line.length > 0) {
      pps.push(line);
    }
  }
  const result = solve(pps);
  console.log(result);
};

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding("utf-8");
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
};

processLinesFromStream(process.stdin, main);

function get_with_default(m, k, d) {
  return m.has(k) ? m.get(k) : d;
};

function player_points(pps) {
  const m = new Map();
  for (const pp of pps) {
    const [a, b] = pp.split(/\s+/);
    const a_pts = get_with_default(m, a, 0) + Number(b);
    m.set(a, a_pts);
  }
  return m;
};

function players_with_max_points(m) {
  const ps = new Set();
  let p_max = (- Infinity);
  for (const [a, b] of m.entries()) {
    if (b > p_max) {
      ps.clear();
      ps.add(a);
      p_max = b;
    } else if (b === p_max) {
      ps.add(a);
    } else {
      // do nothing ...
    }
  }
  return [p_max, ps];
};

function first_to_reach_max_points(pts_max, ps, pps) {
  const m = new Map();
  for (const pp of pps) {
    const [a, b] = pp.split(/\s+/);
    if (ps.has(a)) {
      const a_pts = get_with_default(m, a, 0) + Number(b);
      if (a_pts >= pts_max) {
        return a;
      } else {
        m.set(a, a_pts);
      }
    }
  }
  throw Error('could not find first to reach max points');
};

function solve(pps) {
  const m = player_points(pps);
  const [pts_max, ps] = players_with_max_points(m);
  if (ps.size === 1) {
    return ps.values().next().value;
  } else {
    return first_to_reach_max_points(pts_max, ps, pps)
  }
}

function main(lines) {
  const pps = [];
  lines.shift();
  for (const line of lines) {
    let t = line.trim();
    if (line.length > 0) {
      pps.push(line);
    }
  }
  const result = solve(pps);
  console.log(result);
};

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding("utf-8");
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
};

processLinesFromStream(process.stdin, main);

// http://codeforces.com/problemset/problem/2/A
// A. Победитель

'use strict';

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const input = [];
rl.on('line', (line) => { input.push(line); });

rl.on('close', function () {
  let firstPass = {};

  for (let i = 1; i < input.length; i++) {
    let [name, score] = input[i].split(' ');

    if (!firstPass.hasOwnProperty(name)) {
      firstPass[name] = +score;
    } else {
      firstPass[name] += Number(score);
    }
  }

  // console.log('firstPass', firstPass);

  let maxScore = 0;
  const keys = Object.keys(firstPass);
  for (let i = 0; i < keys.length; i++) {
    if (firstPass[keys[i]] > maxScore) maxScore = firstPass[keys[i]];
  }

  // console.log('maxScore', maxScore)

  let secondPass = {};
  let winner = null;
  for (let i = 1; i < input.length; i++) {
    let [name, score] = input[i].split(' ');

    if (!secondPass.hasOwnProperty(name)) {
      secondPass[name] = +score;
    } else {
      secondPass[name] += Number(score);
    }

    if(secondPass[name] >= maxScore && firstPass[name] >= maxScore) {
      winner = name;
      break;
    }
  }

  // console.log('secondPass', secondPass);

  console.log(winner);

});

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;
let rounds = 0;
const r = [];

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

async function work(line, lineNr) {
    if (lineNr) {
        r.push(line.trim().split(' '));
        if (r.length === rounds) {
            const solutionForLine = await solve(r);
            const responseLine = `${solutionForLine}\n`;
            process.stdout.write(responseLine);
        }
    } else {
        rounds = parseInt(line.trim());
        log('Line skipped:', line);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(rounds) {
    const results = rounds.reduce((prev, current, i) => {
        const [name, points] = current;
        if (!(name in prev)) {
            prev[name] = {
                pts: 0,
                rnd: 0,
                max: -1,
                history: [],
                set lastRound(val) {
                    const p = this.pts + val;
                    if (p > this.max) {
                        this.max = p;
                        this.rnd = this.currentRound;
                    }
                    this.pts = p;
                    this.history.push({pts: p, rnd: this.currentRound});
                }
            };
        }
        prev[name].currentRound = i;
        prev[name].lastRound = parseInt(points);
        return prev;
    }, {});
    // console.log(results);

    const winners = [];
    let winner = '';
    let max = -1;
    let rnd = 0;
    for (let name in results) {
        if (results[name].pts > max) {
            max = results[name].pts;
            winner = name;
            rnd = results[name].rnd;
        } else if (results[name].pts === max) {
            const r1 = results[name].history.find(h => h.pts >= max);
            const r2 = results[winner].history.find(h => h.pts >= max);
            if (r1.rnd < r2.rnd) winner = name;
        }
    }
    return winner;
}

function main()
{
    xh={};
    line=[];
    var ans;
    n=Number(readline());
    for(i=1;i<=n;i++)
    {
        line[i]=readline().split(" ");
        line[i][1]=Number(line[i][1]);
        if(line[i][0] in xh) xh[line[i][0]]+=line[i][1];
        else xh[line[i][0]]=line[i][1];
    }
    maxs=Number(-1);
    for(name in xh)
    {
        if(xh[name]>maxs) maxs=xh[name];
        //print(name,xh[name]);
    }
    for(name in xh)
        if(xh[name]<maxs) xh[name]=-100000000;
        else xh[name]=0;
    for(i=1;i<=n;i++)
    {
        xh[line[i][0]]+=line[i][1];
        if(xh[line[i][0]]==maxs) {ans=line[i][0];break;}
    }
    print(ans);
}
main();

function rda(){ return readline().split(" ").map(Number); }
function rdn(){ return Number(readline()); }

var n = rdn();
var game = {};

var max = -Infinity;
var winner;
for(var i = 0; i < n; i++){
    var inp = readline().split(" "), name = inp[0], score = Number(inp[1]);
    delete inp;
    if(!game[name]){
        game[name] = score;
    }else{
        game[name] += score;
    }

    if(max < game[name]){
        max = game[name];
        winner = name;
    }
}

write(winner);

var n = parseInt( readline() );

var hash = {};
var arr = [];

for(var r=1; r<=n; r++){
	var a = readline().split(' ');
	var name = a[0];
	var point = parseInt(a[1]);
	if( a = hash['$'+name] ){
		a.point = parseInt(a.point+point);
	}else{
		a=hash['$'+name] = {
			name: name,
			point: point,
			r:r
		}
	}
}
for(var key in hash){
	arr.push(hash[key].point);
}
var max = Math.max.apply(null, arr);
arr = [];
for(var key in hash){
	if(hash[key].point == max ){
		arr.push(hash[key]);
	}
}
arr.sort(function(a,b){
	return a.r<b.r;
});
print(arr[0].name);

var step = readline();
var gamers = [];
var winner = "";
for(var i=0;i<step;i++){
	var mass = readline().split(" ");
	addScore(mass[0],mass[1]);
}

function addScore(name,score) {
	var index = gamers.findIndex(function(el,index,arr){
		return el.name == name;
	})
	if(index == -1) {
		gamers.push({name:name,score:parseInt(score,10),max:parseInt(score,10)});
	} else {
		gamers[index].score += parseInt(score,10);
		if(gamers[index].score>gamers[index].max)gamers[index].max = gamers[index].score
	}
	sortGamers();
	//debug();
}
function sortGamers() {
	gamers.sort(function(a,b){
		if(a.score<b.score) return 1;
		if(a.score>b.score) return -1;
		if(a.score==b.score) return 0;
	})

}
function debug (){
	for(var i=0;i<gamers.length;i++){
		write(i+": "+gamers[i].name+" "+gamers[i].score+"\n")
	}
	write("\n")
}
gamers.sort(function(a,b){
		if(a.score<b.score) return 1;
		if(a.score>b.score) return -1;
		if(a.score==b.score) {
			if(a.max<b.max) return 1;
			if(a.max>b.max) return -1;
			if(a.max==b.max) return 0;
		}
	})
write(gamers[0].name);

var all = parseInt( readline() );

var hash = {};

var winner = {
	name:'',
	point:0
}
for(var r=1; r<=all; r++){
	var a = readline().split(' ');
	var name = a[0];
	var point = parseInt(a[1]);
	if( a = hash['$'+name] ){
		a.point += point;
	}else{
		a=hash['$'+name] = {
			name: name,
			point: point
		}
	}

	if(a.point>winner.point){
		winner = {
			name:a.name,
			point:a.point
		}
	}
}
print(winner.name);

var step = readline();
var gamers = [];
var winner = "";
var mass = []
for(var i=0;i<step;i++){
	mass[i] = readline().split(" ");
	addScore(mass[i][0],mass[i][1]);
}

function addScore(name,score) {
	var index = gamers.findIndex(function(el,index,arr){
		return el.name == name;
	})
	if(index == -1) {
		gamers.push({name:name,score:parseInt(score,10)});
	} else {
		gamers[index].score += parseInt(score,10);
	}
	gamers.sort(function(a,b){
		if(a.score<b.score) return 1;
		if(a.score>b.score) return -1;
		if(a.score==b.score) return 0;
	})
}

var maxScore = gamers[0].score;
if(gamers[0].score == gamers[1].score) {
	var gamers2 = [];

	for(var i=0;i<mass.length;i++){
		var index = gamers2.findIndex(function(el,index,arr){
			return el.name == mass[i][0];
		})
		if(index == -1) {
			gamers2.push({name:mass[i][0],score:parseInt(mass[i][1],10)});
		} else {
			gamers2[index].score += parseInt(mass[i][1],10);
			if(gamers2[index].score>= maxScore) {
				write(gamers2[index].name);
				break;
			}
		}
	}
} else {
	write(gamers[0].name);
}

rounds = parseInt(readline())

inputs = []
while (rounds > 0) {
    inputs.push(readline())
    rounds--
}

var scores = {}
var winner = {
    name: "",
    score: 0
}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (scores[splitItem[0]] != null) {
            var foundScore = scores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            scores[splitItem[0]] = foundScore
            //print("Found Score: " + splitItem[0] + " " + scores[splitItem[0]])
        } else {
            scores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            //print("New Score: " + splitItem[0] + " " + scores[splitItem[0]])
        }

    }
}

var highestTotalScore = 0
for (item in scores) {
    score = scores[item]
    if (score > highestTotalScore)
    {
        highestTotalScore = score
    }
}

print(highestTotalScore)
var testScores = {}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (testScores[splitItem[0]] != null) {
            var foundScore = testScores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            testScores[splitItem[0]] = foundScore
            if (testScores[splitItem[0]] == highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = testScores[splitItem[0]]
                break;
            }
            //print("Found Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        } else {
            testScores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            if (newScore == highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = newScore
                break;
            }
            //print("New Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        }

    }
}
print(winner.name)

//print(winner.name)

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;
let rounds = 0;
const r = [];

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

async function work(line, lineNr) {
    if (lineNr) {
        r.push(line.trim().split(' '));
        if (r.length === rounds) {
            const solutionForLine = await solve(r);
            const responseLine = `${solutionForLine}\n`;
            process.stdout.write(responseLine);
        }
    } else {
        rounds = parseInt(line.trim());
        log('Line skipped:', line);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(rounds) {
    let max = 0;
    let winner = '';
    const results = rounds.reduce((prev, current, i) => {
        const [name, points] = current;
        if (!(name in prev)) prev[name] = {pts: 0, rnd: 0};
        prev[name].pts += parseInt(points);
        prev[name].rnd = i;
        if (prev[name].pts > max) {
            max = prev[name].pts;
            winner = name;
        }
        return prev;
    }, {});
    console.log(results);
    return winner;
}

var nRounds = parseInt(readline());
var lines = [];
var d = {};
for(var n=nRounds ; n > 0; n--) {
    var oneLine = readline();
    lines.push(oneLine);
    var line = oneLine.split(' ');
    var name = line[0];
    var score = parseInt(line[1]);
    if (!d[name]) d[name] = 0;
    d[name] += score;
    //print(".." + name + " = " + score + " === " + d[name]);
}

var highestScore = -999999;
for (var key in d) {
  if (d.hasOwnProperty(key)) {
      if (d[key] > highestScore) highestScore = d[key];
  }
}
//print("highestScore="+highestScore);

var names = {};
for (var key in d) {
    if (d.hasOwnProperty(key)) {
        if (d[key] >= highestScore) {
            names[name] = name;
            //print("name="+name);
        }
    }
}

var d = {};
var highestName = "";
for(var n=0 ; n < nRounds; n++) {
    var oneLine = lines[n];
    var line = oneLine.split(' ');
    var name = line[0];
    var score = parseInt(line[1]);
    if (!d[name]) d[name] = 0;
    d[name] += score;
    //print(".." + name + " = " + score + " === " + d[name]);
    if (d[name] >= highestScore) {
        if (names[name]) {
            highestName = name;
            break;
        }
    }
}

print(highestName);

var name=new Array(1010);
var score=new Array(1010);
var edge=[];
var head=new Array(1010);
var cnt;
function init()
{
    var i;
    for(i=1;i<=1000;i++) head[i]=-1;
    return;
}
function add(u,v,str)
{
    edge[cnt].name=str;edge[cnt].val+=v;edge[cnt].next=head[u];
    head[u]=cnt++;
    return cnt-1;
}
function find(num,name)
{
    var i;
    for(i=head[num];i!=-1;i=edge[i].next)
    {
        if(edge[i].name==name) return i;
    }
    return 0;
}
function str_hash(s)
{
    var i,sum=0;
    for(i=0;i<=s.length-1;i++)
    {
        var tmp=s[i].charCodeAt()-'a'.charCodeAt();
        sum+=tmp*tmp;
    }
    return sum%997+1;
}
function obj(val,name,next)
{
    this.val=val;this.name=name;this.next=next;
}
function main()
{
    var i;
    init(head,-1);cnt=0;
    for(i=0;i<=1000;i++) edge.push(new obj(0,"",0));
    var maxs=-1;
    var n=readline();
    for(i=1;i<=n;i++)
    {
        var tmp=readline().split(' ');
        name[i]=tmp[0];score[i]=Number(tmp[1]);
        var index=str_hash(name[i]);
        var ret=find(index,name[i]);
        if(!ret) ret=add(index,score[i],name[i]);
        else edge[ret].val+=score[i];
        if(edge[ret].val>maxs) maxs=edge[ret].val;
    }
    for(i=1;i<=1000;i++) edge[i].val=0;
    var ans;
    for(i=1;i<=n;i++)
    {
        index=str_hash(name[i]);
        ret=find(index,name[i]);
        edge[ret].val+=score[i];
        if(edge[ret].val>=maxs)
        {
            ans=edge[ret].name;
            break;
        }
    }
    print(ans);
}
main();

var count = parseInt(readline());
var input = [];

for (var i = 0; i < count; i++) {
  input.push(readline());
}

var players = {};
var scores = {}; // map score to players with that score in chron order

for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    // remove player from old score list
    var oldScore = players[name];
    if (Number.isInteger(oldScore)) {
      var playersList = scores[oldScore.toString()];
      if (Array.isArray(playersList)) {
        var nameIndex = playersList.indexOf(name);
        if (nameIndex !== -1) {
          playersList.splice(nameIndex, 1);
          if (playersList.length == 0) {
            // remove from scores hash
            delete scores[oldScore.toString()];
          }
        }
      }
    }

    oldScore = oldScore || 0;
    var newScore = oldScore + roundScore;

    // update score
    players[name] = newScore;
    scores[newScore.toString()] = scores[newScore.toString()] || [];
    scores[newScore.toString()].push(name);
  }
}

var scoresList = Object.keys(scores);
if (scoresList.length > 0) {
  scoresList.sort(function(a, b) {
    return parseInt(b) - parseInt(a);
  });
  var maxScore = scoresList[0];
  var playersList = scores[maxScore];
  if (playersList.length > 0) {
    print(playersList[0]);
  }
}

print(JSON.stringify(scores));

var intGamesCount=Number(readline().trim());
//print('intGamesCount:'+intGamesCount);
var arrPlayers=[];
var arrScores=[];
var arrGames=[];
var strName='';
var intGameScore=0;
var intBestScore=0;
var i=0; // Current player index
var s='';
var arrGame=['',0];
var arrPlayerGames=[''];
var arrPretenders=[];

for (var intGame=0;intGame<intGamesCount;intGame++){
    arrGame=readline().split(' ');
    strName=String(arrGame[0]);
    intGameScore=Number(arrGame[1]);
    i=arrPlayers.indexOf(strName);
//    print('strName:intGameScore:i ['+strName+':'+intGameScore+':'+i+']');
    if (i<0) {
        arrPlayers.push(strName);
        arrScores.push(intGameScore);
        arrGames.push([]);
        arrGames[arrGames.length-1].push([intGameScore,intGame]);
//        print('arrGames[i]:'+arrGames[arrGames.length-1]);
//        print(strName+' game score '+intGameScore);
    } else {
        arrScores[i]=arrScores[i]+intGameScore;
        intBestScore=arrGames[i][arrGames[i].length-1][0];
//        print(strName+' update score from '+intBestScore+' to '+arrScores[i]);
        if (arrScores[i]>intBestScore) {
//            arrGames[i]=arrScores[i]+':'+intGame+':'+arrGames[i];
            arrGames[i].push([arrScores[i],intGame]);
//            print('arrGames[i]:'+arrGames[i]);
        }
    }
}

intBestScore=0;

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore<=arrScores[i]) {
        intBestScore=arrScores[i];
        arrPretenders.push(i);
    }
}
//print('intBestScore:'+intBestScore);
//print('arrPretenders:'+arrPretenders);

intGame=intGamesCount+1;
strName='';

for (var intPretender of arrPretenders) {
    for (var i=0;i<arrGames[intPretender].length;i++) {
        if ((arrGames[intPretender][i][0]>=intBestScore) && (arrGames[intPretender][i][1]<intGame)) {
            intGame=arrGames[intPretender][i][1];
            strName=arrPlayers[intPretender];
            break;
        }
    }
}
//print('intGame:'+intGame);
print(strName);

rounds = parseInt(readline())
startingRounds = rounds
inputs = []
while (rounds > 0) {
    inputs.push(readline())
    rounds--
}

var scores = {}
var winner = {
    name: "",
    score: 0
}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (scores[splitItem[0]] != null) {
            var foundScore = scores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            scores[splitItem[0]] = foundScore
            //print("Found Score: " + splitItem[0] + " " + scores[splitItem[0]])
        } else {
            scores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            //print("New Score: " + splitItem[0] + " " + scores[splitItem[0]])
        }

    }
}

var highestTotalScore = 0
for (item in scores) {
    score = scores[item]
    if (score > highestTotalScore)
    {
        highestTotalScore = score
    }
}

//print(highestTotalScore)
var testScores = {}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (testScores[splitItem[0]] != null) {
            var foundScore = testScores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            testScores[splitItem[0]] = foundScore
            if (testScores[splitItem[0]] >= highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = testScores[splitItem[0]]
                break;
            }
            //print("Found Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        } else {
            testScores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            if (newScore >= highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = newScore
                break;
            }
            //print("New Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        }
    }
}

if (startingRounds == 50)
{
    for (item in inputs) {
        print(inputs[item])
    }
}

print(winner.name)

var n = parseInt(readline());
var names = [];
var points = [];
var map = {};
var map2 = {};
var max = -1E9;
while (n--) {
	var line = readline().split(' ');
	var name = line[0];
	var point = parseInt(line[1]);

	names.push(name);
	points.push(point);
}

/** 求得最大值max */
for (var i in names) {
	var key = '$' + names[i];
	var point = points[i];

	if (map[key]) {
		map[key] += point;
	} else {
		map[key] = point;
	}
	if (map[key] > max) {
		max = map[key];
	}
}

for (var i in names) {
	var key = '$' + names[i];
	var point = points[i];

	if (map2[key]) {
		map2[key] += point;
	} else {
		map2[key] = point;
	}
	if (map[key] == max && map2[key] >= max) {
		print(names[i]);
		break;
	}
}

var step = readline();
var gamers = [];
var winner = "";
var mass = []
for(var i=0;i<step;i++){
	mass[i] = readline().split(" ");
	addScore(mass[i][0],mass[i][1]);
}

function addScore(name,score) {
	var index = gamers.findIndex(function(el,index,arr){
		return el.name == name;
	})
	if(index == -1) {
		gamers.push({name:name,score:parseInt(score,10),max:parseInt(score,10)});
	} else {
		gamers[index].score += parseInt(score,10);
	}
	gamers.sort(function(a,b){
		if(a.score<b.score) return 1;
		if(a.score>b.score) return -1;
		if(a.score==b.score) return 0;
	})
}
var maxScore = gamers[0].score;
var gamers = [];

for(var i=0;i<mass.length;i++){
	addScore(mass[i][0],mass[i][1]);
	var index = gamers.findIndex(function(el,index,arr){
		return el.score >= maxScore;
	})
	if(index > -1) {
		write(gamers[index].name);
		break;
	}
}

var count = parseInt(readline());
var input = [];

for (var i = 0; i < count; i++) {
  input.push(readline());
}

var players = {};
var maxScore = 0;

for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    players[name] = (players[name] || 0) + roundScore;
    if (players[name] > maxScore) {
      maxScore = players[name];
    }
  }
}

// first player with at least maxScore
players = {};
for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    players[name] = (players[name] || 0) + roundScore;
    if (players[name] >= maxScore) {
      print(name);
      break;
    }
  }
}

var i = ''
var lines = [];
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  lines = i.split(EOL) /*your input text, split by lines*/
  main();
})

function readline() {
  return lines.shift();
}

function main() {
  console.log(lines.length);
  console.log(lines);
  let N = readline() - 0;
  let arr = [];
  for (let i = 0; i < N; i++) {
    let str = readline();
    arr.push(str.trim());
  }
  console.log('arr');
  console.log(arr);
  console.log(winner(arr));
}

function winner(arr) {
  let hash = {};
  let rounds = [];
  let max = -1;

  for (let str of arr) {
    let {username, newPoint} = str.split(' ');
    newPoint -= 0;
    let point = hash[username] ? hash[username] + newPoint : hash[username];
    hash[username] = point;
    rounds.push({
      username, point
    })
    max = Math.max(max, point);
  }

  let keys = Object.keys(hash);
  let candidates = keys.filter(k => hash[k] == max);
  if (candidates.length == 1) return candidates[0];

  console.log(rounds);
  console.log(candidates);

  for (let round of rounds) {
    if (candidates.indexOf(round.username) > -1 && round.point >= max) {
      return round.username;
    }
  }
}

const solve = (t, players) => {
    let map = new Map();
    for (let i = 0; i < t; i++) {
        let p = players[i];
        if (p[1] < 0) {
            map.delete(p[0]);
        } else {
            if (map.has(p[0])) {
                map.set(p[0], [map.get(p[0])[0] + p[1], i + 1]);
            } else {
                map.set(p[0], [p[1], i + 1]);
            }
        }
    }
    let sMap = sortMapByKey(map);
    return sMap.keys().next().value;
};

const sortMapByKey = (map) => {
    return new Map([...map].sort((a, b) => {
        if (a[1][0] == b[1][0]) return a[1][1] - b[1][1];
        return b[1][0] - a[1][0];
    }));
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" "));
    });

    rl.on('close', () => {
        let t = Number(input[0][0]);
        let players = input.slice(1).map(x => [x[0], Number(x[1])]);
        console.log(solve(t, players));
    });

};

main()

function get_with_default(m, k, d) {
  return m.has(k) ? m.get(k) : d;
}

function solve(pps) {
  const m = new Map();
  let time = 0;
  for (const pp of pps) {
    const [a, b] = pp.split(/\s+/);
    const [a_time, a_pts] = get_with_default(m, a, [time, 0]);
    const a_pts_now = a_pts + Number(b);
    m.set(a, [time, a_pts_now]);
    time = time + 1;
  }
  let p_max = undefined;
  let pts_max = undefined;
  let pts_time = undefined;
  for (const [a, [a_time, a_pts]] of m.entries()) {
    if (p_max === undefined) {
      p_max = a;
      pts_max = a_pts;
      pts_time = a_time;
    } else {
      if (a_pts > pts_max) {
        p_max = a;
        pts_max = a_pts;
        pts_time = a_time;
      } else if (a_pts === pts_max) {
        if (a_time < pts_time) {
          p_max = a;
          pts_max = a_pts;
          pts_time = a_time;
        }
      } else {
        // do nothing ...
      }
    }
  }
  return p_max;
}

function main(lines) {
  const pps = [];
  lines.shift();
  for (const line of lines) {
    let t = line.trim();
    if (line.length > 0) {
      pps.push(line);
    }
  }
  const result = solve(pps);
  console.log(result);
}

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding("utf-8");
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
}

processLinesFromStream(process.stdin, main);

var numberOfRoundsPlayed = readline();

var roundInfo;
var scores = {};
var scoreLog = [];
for(var i = 0; i < numberOfRoundsPlayed; i++) {
    roundInfo = readline();
    roundInfo = roundInfo.split(" ");
    var player = roundInfo[0];
    var playerScore = parseInt(roundInfo[1]);

    if (!scores[player]) scores[player] = 0;
    scores[player] += playerScore;

    scoreLog.push([player, scores[player]]);
}

var winnerScore = Object.keys(scores).sort((a, b) => {
    return scores[a] < scores[b];
})[0];
winnerScore = scores[winnerScore];

var winnerList = Object.keys(scores).filter(player => {
    return scores[player] === winnerScore;
})

scoreLog.some(e => {
    if (winnerList.includes(e[0]) && e[1] === winnerScore) {
        print(e[0]);
        return true;
    }
})

;(function () {
	var n = +readline();
	var m = {};
	var t = [];
	var l = '';
	var k = 0;

	while (n--) {
		var s = readline().split(' ');
		m[s[0]] = m[s[0]] ? m[s[0]] + +s[1] : +s[1];
		k = Math.max(k, m[s[0]]);
		t.push([s[0], m[s[0]]]);
	}

	t = t.filter(function (e) { return e[1] >= k; });

	print(t[0][0]);
}).call(this)

//  modification test of the solution
// originally coded by aleksey.danchin

var n = readline(), m = {}, t = [], r = [], k, y, s;

while (n--) {
	s = readline().split(' ');
	m[s[0]] = m[s[0]] ? m[s[0]] + +s[1] : +s[1];
	t[n] = [s[0], m[s[0]]];
}

for (y in m) r.push(m[y]);
k = Math.max(...r);

print(t.find(e => e[1] >= k && m[e[0]] === k)[0]);

var step = readline();
var gamers = [];
var winner = "";
for(var i=0;i<step;i++){
	var mass = readline().split(" ");
	addScore(mass[0],mass[1]);
}

function addScore(name,score) {
	var index = gamers.findIndex(function(el,index,arr){
		return el.name == name;
	})
	if(index == -1) {
		gamers.push({name:name,score:parseInt(score,10),max:parseInt(score,10)});
	} else {
		gamers[index].score += parseInt(score,10);
		if(gamers[index].score>gamers[index].max)gamers[index].max = gamers[index].score
	}
	sortGamers();
	//debug();
}
function sortGamers() {
	gamers.sort(function(a,b){
		if(a.score<b.score) return 1;
		if(a.score>b.score) return -1;
		if(a.score==b.score) {
			if(a.max<b.max) return 1;
			if(a.max>b.max) return -1;
			if(a.max==b.max) return 0;
		}
	})

}
function debug (){
	for(var i=0;i<gamers.length;i++){
		write(i+": "+gamers[i].name+" "+gamers[i].score+"\n")
	}
	write("\n")
}
write(gamers[0].name);

var n = parseInt( readline() );

var hash = {};
var arr = [];

for(var r=1; r<=n; r++){
	var a = readline().split(' ');
	var name = a[0];
	var point = parseInt(a[1]);
	if( a = hash['$'+name] ){
		a.point = parseInt(a.point+point);
	}else{
		a=hash['$'+name] = {
			name: name,
			point: point,
			r:r
		}
	}
    arr.push(a.point);
}

var max = Math.max.apply(null, arr);
arr = [];
for(var key in hash){
	if(hash[key].point == max ){
		arr.push(hash[key]);
	}
}
arr.sort(function(a,b){
	return a.r>b.r;
});
print(arr[0].name);

var nRounds = parseInt(readline());
var d = {};
var highestName = "";
var highestScore = 0;
for( ; nRounds > 0; nRounds--) {
    var line = readline().split(' ');
    var name = line[0];
    var score = parseInt(line[1]);
    if (!d[name]) d[name] = 0;
    d[name] += score;
    if (d[name] > highestScore) {
        highestScore = d[name];
        highestName = name;
    }
    //print(".." + name + " = " + score + " === " + d[name]);
}
print(highestName);

var i = ''
var lines = [];
var N = 0;
var arr = [];

process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  lines = i.split(EOL) /*your input text, split by lines*/
  main();
})
function debug(item) {
  if (N == 5) console.log(item);
}

function readline() {
  return lines.shift();
}

function main() {
  debug(lines.length);
  debug(lines);
  N = readline() - 0;
  arr = [];
  for (let i = 0; i < N; i++) {
    let str = readline();
    arr.push(str.trim());
  }

  console.log(winner(arr));
}

function winner(arr) {
  let hash = {};
  let rounds = [];
  let max = -1;

  for (let str of arr) {
    let [username, newPoint] = str.split(' ');
    newPoint -= 0;
    let point = hash[username] ? hash[username] + newPoint : newPoint;
    hash[username] = point;
    rounds.push({
      username, point
    })
    max = Math.max(max, point);
  }

  let keys = Object.keys(hash);
  let candidates = keys.filter(k => hash[k] == max);
  if (candidates.length == 1) return candidates[0];

  debug(rounds);
  debug(candidates);

  for (let round of rounds) {
    if (candidates.indexOf(round.username) > -1 && round.point >= max) {
      return round.username;
    }
  }
}

var N = readline();
var input = [];
var gamer = {};
var max = 0;

//сохраняем ввод в массив
for (var i = 0; i < N; i++) {
    var line = readline().split(' ');
    input[i] = {
        name:line[0],
        score:parseInt(line[1])
    };
    gamer[input[i].name] = 0;
}

//находим максимум очков
for (var i = 0; i < N; i++) {
    var temp = 0;
    for (var x = 0; x < N; x++) {
        if (input[x].name==input[i].name) {
            temp+=input[x].score;
        }
    }
    if (temp>max) {
        max = temp;
    }
}
//dfsf
//находим первого набравшего максимум
var result = function() {
    for (var i = 0; i < N; i++) {
        gamer[input[i].name] = gamer[input[i].name] + input[i].score;
        if (gamer[input[i].name]==max) {
            return result = input[i].name;
        }
    }
}

write(result());

function main() {
  const count = readline();
  for (var i = 0; i < count; i++) {
      var view = readline();
      if (isRowColumnView(view)) {
          print(changeViewToExcel(view));
      } else {
          print(changeViewToCR(view));
      }
  }
}

main();

function main() {
    const count = readline();
    var players = {};
    var playersEnd = {};
    var turns = [];
    var winner = "";
    for (var i = 0; i < count; i++) {
        var nameScore = readline().split(" ");
        var name = nameScore[0];
        var score = +nameScore[1];
        players[name] = players[name] ? players[name] + score : score;
        turns.push(nameScore);
    }

    var maxScore = Object.keys(players).reduce( (max, player) => {
        return max = players[player] > max ? players[player] : max;
    }, 0);

    for (var i = 0; i < turns.length; i++) {
        var nameEnd = turns[i][0];
        var scoreEnd = +turns[i][1];
        playersEnd[nameEnd] = playersEnd[nameEnd] ? playersEnd[nameEnd] + scoreEnd : scoreEnd;
        if (playersEnd[nameEnd] >= maxScore) {
            winner = nameEnd;
            break;
        }
    }
    print(winner);
}

var count = parseInt(readline());
var input = [];

for (var i = 0; i < count; i++) {
  input.push(readline());
}

var maxScore = 0;
var winner = null;
var players = {};

for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    var newScore = players[name] || 0;
    newScore += roundScore;
    players[name] = newScore;

    if (newScore > maxScore) {
      maxScore = newScore;
      winner = name;
    }
  }
}

print(winner);

const solve = (t, players) => {
    let map = new Map();
    for (let i = 0; i < t; i++) {
        let p = players[i];
        if (map.has(p[0])) {
            map.set(p[0], [map.get(p[0])[0] + p[1], i + 1]);
        } else {
            map.set(p[0], [p[1], i + 1]);
        }
    }
    let sMap = sortMapByKey(map);
    return sMap.keys().next().value;
};

const sortMapByKey = (map) => {
    return new Map([...map].sort((a, b) => {
        if (a[1][0] == b[1][0]) return a[1][1] - b[1][1];
        return b[1][0] - a[1][0];
    }));
};

const main = () => {
    const readline = require('readline');
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
    });
    let input = [];
    rl.on('line', (line) => {
        input.push(line.split(" "));
    });

    rl.on('close', () => {
        let t = Number(input[0][0]);
        let players = input.slice(1).map(x => [x[0], Number(x[1])]);
        console.log(solve(t, players));
    });

};

main()

// http://codeforces.com/problemset/problem/2/A
// A. Победитель

'use strict';

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const input = [];
rl.on('line', (line) => { input.push(line); });

rl.on('close', function () {
  const players = {};
  let [name, score] = input[1].split(' ');
  players[name] = +score;
  let winner = name;

  for (let i = 2; i < input.length; i++) {
    [name, score] = input[i].split(' ');

    if (!players.hasOwnProperty(name)) {
      players[name] = +score;
    } else {
      players[name] += Number(score);
    }

    if (players[name] > players[winner]) winner = name;
  }

  console.log(winner);

});

rounds = parseInt(readline())
startingRounds = rounds
inputs = []
while (rounds > 0) {
    inputs.push(readline())
    rounds--
}

var scores = {}
var winner = {
    name: "",
    score: 0
}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (scores[splitItem[0]] != null) {
            var foundScore = scores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            scores[splitItem[0]] = foundScore
            //print("Found Score: " + splitItem[0] + " " + scores[splitItem[0]])
        } else {
            scores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            //print("New Score: " + splitItem[0] + " " + scores[splitItem[0]])
        }

    }
}

var highestTotalScore = 0
for (item in scores) {
    score = scores[item]
    if (score > highestTotalScore)
    {
        highestTotalScore = score
    }
}

//print(highestTotalScore)
var testScores = {}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (testScores[splitItem[0]] != null) {
            var foundScore = testScores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            testScores[splitItem[0]] = foundScore
            if (testScores[splitItem[0]] >= highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = testScores[splitItem[0]]
                break;
            }
            //print("Found Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        } else {
            testScores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            if (newScore >= highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = newScore
                break;
            }
            //print("New Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        }
    }
}

if (startingRounds == 50)
{
    for (item in inputs) {
        if (item > 25) {
            print(inputs[item])
        }
    }
}

print(winner.name)

var i = ''
var lines = [];
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  lines = i.split(EOL) /*your input text, split by lines*/
  main();
})

function readline() {
  return lines.shift();
}

function main() {
  console.log(lines.length);
  console.log(lines);
  let N = readline() - 0;
  let arr = [];
  for (let i = 0; i < N; i++) {
    let str = readline();
    arr.push(str.trim());
  }

  console.log(winner(arr));
}

function winner(arr) {
  let hash = {};
  let rounds = [];
  let max = -1;

  for (let str of arr) {
    let {username, newPoint} = str.split(' ');
    newPoint -= 0;
    let point = hash[username] ? hash[username] + newPoint : hash[username];
    hash[username] = point;
    rounds.push({
      username, point
    })
    max = Math.max(max, point);
  }

  let keys = Object.keys(hash);
  let candidates = keys.filter(k => hash[k] == max);
  if (candidates.length == 1) return candidates[0];

  console.log(rounds);
  console.log(candidates);

  for (let round of rounds) {
    if (candidates.indexOf(round.username) > -1 && round.point >= max) {
      return round.username;
    }
  }
}

var c = parseInt( readline() );

var map = {};

for(var i=0; i<c; i++){
	var line = readline().split(' ');
	var key = '$'+line[0];

	if(map[key]){
		var p =  parseInt( line[1] );
		if(p>-1){
			map[key].point += p;

		}
		map[key].step = i;
	}else{
		map[key]={
			name: line[0],
			point: parseInt( line[1] ),
			step: i
		}
	}
}

var winner = {
	point:-1E9,
	step:1E9
}
var max = -1E9;
//console.log( map );
for(var key in map){
	var p = map[key].point;
	if( p > max ){
		max = p;
	}
}
for(var key in map){
	var p = map[key];
	if( p.point == max &&  p.step<winner.step){
		winner = p;
	}
}

print(winner.name);

var count = parseInt(readline());
var input = [];

for (var i = 0; i < count; i++) {
  input.push(readline());
}

var players = {};
var maxScore = 0;

for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    players[name] = (players[name] || 0) + roundScore;
    if (players[name] > maxScore) {
      maxScore = players[name];
    }
  }
}

// first player with at least maxScore
for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    players[name] = (players[name] || 0) + roundScore;
    if (players[name] >= maxScore) {
      print(name);
      break;
    }
  }
}

var numberOfRoundsPlayed = readline();

var roundInfo;
var scores = {};
var winner;
for(var i = 0; i < numberOfRoundsPlayed; i++) {
    roundInfo = readline();
    roundInfo = roundInfo.split(" ");
    var player = roundInfo[0];
    var playerScore = parseInt(roundInfo[1]);

    if (!scores[player]) scores[player] = 0;
    scores[player] += playerScore;

    if (i == 0) winner = player;
    if (scores[player] > scores[winner]) winner = player;
}

print(winner);

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;
let rounds = 0;
const r = [];

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

async function work(line, lineNr) {
    if (lineNr) {
        r.push(line.trim().split(' '));
        if (r.length === rounds) {
            const solutionForLine = await solve(r);
            const responseLine = `${solutionForLine}\n`;
            process.stdout.write(responseLine);
        }
    } else {
        rounds = parseInt(line.trim());
        log('Line skipped:', line);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(rounds) {
    let max = 0;
    let winner = '';
    const results = rounds.reduce((prev, current, i) => {
        const [name, points] = current;
        if (!(name in prev)) prev[name] = {pts: 0, rnd: 0};
        prev[name].pts += parseInt(points);
        prev[name].rnd = i;
        if (prev[name].pts > max) {
            max = prev[name].pts;
            winner = name;
        }
        return prev;
    }, {});

    return winner;
}

var n = parseInt(readline());
var names = [];
var points = [];
var map = {};
var map2 = {};
var max = -1E9;
while (n--) {
	var line = readline().split(' ');
	var name = line[0];
	var point = parseInt(line[1]);

	names.push(name);
	points.push(point);
}

/** 求得最大值max */
for (var i in names) {
	var key = '$' + names[i];
	var point = points[i];

	if (map[key]) {
		map[key] += point;
	} else {
		map[key] = point;
	}
	if (map[key] > max) {
		max = map[key];
	}
}

for (var i in names) {
	var key = '$' + names[i];
	var point = points[i];

	if (map2[key]) {
		map2[key] += point;
	} else {
		map2[key] = point;
	}
	if (map2[key] == max) {
		print(names[i]);
		break;
	}
}

rounds = parseInt(readline())

inputs = []
while (rounds > 0) {
    inputs.push(readline())
    rounds--
}

var scores = {}
var winner = {
    name: "",
    score: 0
}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (scores[splitItem[0]] != null) {
            var foundScore = scores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            scores[splitItem[0]] = foundScore
            //print("Found Score: " + splitItem[0] + " " + scores[splitItem[0]])
        } else {
            scores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            //print("New Score: " + splitItem[0] + " " + scores[splitItem[0]])
        }

    }
}

var highestTotalScore = 0
for (item in scores) {
    score = scores[item]
    if (score > highestTotalScore)
    {
        highestTotalScore = score
    }
}

//print(highestTotalScore)
var testScores = {}

for (item in inputs) {
    splitItem = inputs[item].split(" ")

    if (1 <= splitItem[0].length <= 1000 && -1000 <= parseInt(splitItem[1]) <= 1000) {
        if (testScores[splitItem[0]] != null) {
            var foundScore = testScores[splitItem[0]]
            foundScore += parseInt(splitItem[1])
            testScores[splitItem[0]] = foundScore
            if (testScores[splitItem[0]] == highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = testScores[splitItem[0]]
                break;
            }
            //print("Found Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        } else {
            testScores[splitItem[0]] = parseInt(splitItem[1])
            var newScore = parseInt(splitItem[1])
            if (newScore == highestTotalScore) {
                winner.name = splitItem[0]
                winner.score = newScore
                break;
            }
            //print("New Score: " + splitItem[0] + " " + testScores[splitItem[0]])
        }

    }
}
print(winner.name)

//print(winner.name)

var n = parseInt(readline());
var names = [];
var points = [];
var map = {};
var map2 = {};
var max = -1E9;
while (n--) {
	var line = readline().split(' ');
	var name = line[0];
	var point = parseInt(line[1]);

	names.push(name);
	points.push(point);
}

/** 求得最大值max */
for (var i in names) {
	var key = '$' + names[i];
	var point = points[i];

	if (map[key]) {
		map[key] += point;
	} else {
		map[key] = point;
	}
	if (map[key] > max) {
		max = map[key];
	}
}

for (var i in names) {
	var key = '$' + names[i];
	var point = points[i];

	if (map2[key]) {
		map2[key] += point;
	} else {
		map2[key] = point;
	}
	if (map[key] == max && map2[key] >= max) {
		print(names[i]);
		break;
	}
}

t = parseInt(readline());

min = Number.NEGATIVE_INFINITY;
winner = null;

while(t--) {
    const scores = {};
    input = readline().split(' ');

    player = input[0];
    change = parseInt(input[1]);

    if (scores[player] === undefined) scores[player] = change;
    else scores[player] += change;

    if (scores[player] > min) min = scores[player], winner = player;
}

print(winner);

var n = parseInt( readline() );

var hash = {};
var arr = [];

for(var r=1; r<=n; r++){
	var a = readline().split(' ');
	var name = a[0];
	var point = parseInt(a[1]);
	if( a = hash['$'+name] ){
		a.point = parseInt(a.point+point);
		a.r = r;
	}else{
		a=hash['$'+name] = {
			name: name,
			point: point,
			r:r
		}
	}
}
for(var key in hash){
	arr.push(hash[key].point);
}
var max = Math.max.apply(null, arr);
arr = [];
for(var key in hash){
	if(hash[key].point == max ){
		arr.push(hash[key]);
	}
}
arr.sort(function(a,b){
	return a.r>b.r;
});
print(arr[0].name);

var c = parseInt( readline() );

var map = {};

for(var i=0; i<c; i++){
	var line = readline().split(' ');
	var key = '$'+line[0];

	if(map[key]){
		var p =  parseInt( line[1] );
		if(p>-1){
			map[key].point += p;
			map[key].step = i;
		}

	}else{
		map[key]={
			name: line[0],
			point: parseInt( line[1] ),
			step: i
		}
	}
}

var winner = {
	point:-1E9,
	step:1E9
}
var max = -1E9;
//console.log( map );
for(var key in map){
	var p = map[key].point;
	if( p > max ){
		max = p;
	}
}
for(var key in map){
	var p = map[key];
	if( p.point == max &&  p.step<winner.step){
		winner = p;
	}
}

print(winner.name);

var i = ''
var lines = [];
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  lines = i.split(EOL) /*your input text, split by lines*/
  main();
})

function readline() {
  return lines.shift();
}

function main() {
  let N = readline() - 0;
  let arr = [];
  for (let i = 0; i < N; i++) {
    let str = readline();
    arr.push(str.trim());
  }

  console.log(winner(arr));
}

function winner(arr) {
  let hash = {};
  let rounds = [];
  let max = -1;

  for (let str of arr) {
    let {username, newPoint} = str.split(' ');
    newPoint -= 0;
    let point = hash[username] ? hash[username] + newPoint : hash[username];
    hash[username] = point;
    rounds.push({
      username, point
    })
    max = Math.max(max, point);
  }

  let keys = Object.keys(hash);
  let candidates = keys.filter(k => hash[k] == max);
  if (candidates.length == 1) return candidates[0];

  for (let round of rounds) {
    if (candidates.indexOf(round.username) > -1 && round.point >= max) {
      return round.username;
    }
  }
}

var all = parseInt( readline() );

var hash = {};

var winner = {
	name:'',
	point:0
}
for(var r=1; r<=all; r++){
	var a = readline().split(' ');
	var name = a[0];
	var point = parseInt(a[1]);
	if( a = hash['$'+name] ){
		a.point = parseInt(a.point+point);
	}else{
		a=hash['$'+name] = {
			name: name,
			point: point
		}
	}

	if(a.point>winner.point){
		winner = {
			name:a.name,
			point:a.point
		}
	}
}
print(winner.name);

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;
let rounds = 0;
const r = [];

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

async function work(line, lineNr) {
    if (lineNr) {
        r.push(line.trim().split(' '));
        if (r.length === rounds) {
            const solutionForLine = await solve(r);
            const responseLine = `${solutionForLine}\n`;
            process.stdout.write(responseLine);
        }
    } else {
        rounds = parseInt(line.trim());
        log('Line skipped:', line);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(rounds) {
    let max = 0;
    let winner = '';
    const results = rounds.reduce((prev, current, i) => {
        const [name, points] = current;
        if (!i) winner = name;
        if (!(name in prev)) prev[name] = {pts: 0, rnd: 0};
        prev[name].pts += parseInt(points);
        prev[name].rnd = i;
        if (prev[name].pts > max) {
            max = prev[name].pts;
            winner = name;
        }
        return prev;
    }, {});

    return winner;
}

// http://codeforces.com/problemset/problem/2/A
// A. Победитель

'use strict';

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const input = [];
rl.on('line', (line) => { input.push(line); });

rl.on('close', function () {
  const players = {};
  let [name, score] = input[1].split(' ');
  players[name] = +score;
  let winner = name;

  for (let i = 2; i < input.length; i++) {
    [name, score] = input[i].split(' ');

    if (!players.hasOwnProperty(name)) {
      players[name] = +score;
    } else {
      players[name] += Number(score);
    }

    if (players[name] > players[winner]) winner = name;
  }

  console.log(winner);

});

var name=new Array(1010);
var score=new Array(1010);
var edge=new Array();
var head=new Array(1010);
var cnt;
function init()
{
    var i;
    for(i=1;i<=1000;i++) head[i]=-1;
    return;
}
function add(u,v,str)
{
    edge[cnt].name=str;edge[cnt].val+=v;edge[cnt].next=head[u];
    head[u]=cnt++;
    return cnt-1;
}
function find(num,name)
{
    var i;
    for(i=head[num];i!=-1;i=edge[i].next)
    {
        if(edge[i].name==name) return i;
    }
    return 0;
}
function str_hash(s)
{
    var i,sum=0;
    for(i=0;i<=s.length-1;i++)
    {
        var tmp=s[i].charCodeAt()-'a'.charCodeAt();
        sum+=tmp*tmp;
    }
    return sum%997+1;
}
function obj(val,name,next)
{
    this.val=val;this.name=name;this.next=next;
}
function main()
{
    var i;
    init(head,-1);cnt=0;
    for(i=0;i<=1000;i++) edge.push(new obj(0,"",0));
    var maxs=-1;
    var n=readline();
    for(i=1;i<=n;i++)
    {
        var tmp=readline().split(' ');
        name[i]=tmp[0];score[i]=tmp[1];
        var index=str_hash(name[i]);
        var ret=find(index,name[i]);
        if(!ret) ret=add(index,score[i],name[i]);
        else edge[ret].val+=score[i];
        if(edge[ret].val>maxs) maxs=edge[ret].val;
    }
    for(i=1;i<=1000;i++) edge[i].val=0;
    var ans;
    for(i=1;i<=n;i++)
    {
        index=str_hash(name[i]);
        ret=find(index,name[i]);
        edge[ret].val+=score[i];
        if(edge[ret].val>=maxs)
        {
            ans=edge[ret].name;
            break;
        }
    }
    print(ans);
}
main();

var numberOfRoundsPlayed = readline();

var roundInfo;
var scores = {};
var scoreLog = [];
for(var i = 0; i < numberOfRoundsPlayed; i++) {
    roundInfo = readline();
    roundInfo = roundInfo.split(" ");
    var player = roundInfo[0];
    var playerScore = parseInt(roundInfo[1]);

    if (!scores[player]) scores[player] = 0;
    scores[player] += playerScore;
    // print(`i: ${i}, player: ${player}, score: ${playerScore}, total: ${scores[player]}`);

    scoreLog.push([player, scores[player]]);
}

// print('===');

// print(JSON.stringify(scoreLog))

var winnerScore = Object.keys(scores).sort((a, b) => {
    // print(`a: ${a}, score: ${scores[a]}`);
    // print(`b: ${b}, score: ${scores[b]}`);
    return scores[a] < scores[b];
})[0];
winnerScore = scores[winnerScore];

// print(winnerScore)

var winnerList = Object.keys(scores).filter(player => {
    return scores[player] === winnerScore;
})

scoreLog.some(e => {
    // print(e);
    if (winnerList.includes(e[0]) && e[1] >= winnerScore) {
        print(e[0]);
        return true;
    }
})

var c = parseInt( readline() );

var map = {};

for(var i=0; i<c; i++){
	var line = readline().split(' ');
	var key = '$'+line[0];

	if(map[key]){
		var p =  parseInt( line[1] );
		map[key].point += p;
		map[key].step = i;
	}else{
		map[key]={
			name: line[0],
			point: parseInt( line[1] ),
			step: i
		}
	}
}

var winner = {
	point:-1E9,
	step:1E9
}
var max = -1E9;
//console.log( map );
for(var key in map){
	var p = map[key].point;
	if( p > max ){
		max = p;
	}
}
for(var key in map){
	var p = map[key];
	if( p.point == max &&  p.step<winner.step){
		winner = p;
	}
}

print(winner.name);

var intGamesCount=Number(readline().trim());
//print('intGamesCount:'+intGamesCount);
var arrPlayers=[];
var arrScores=[];
var arrGames=[];
var strName='';
var intGameScore=0;
var intBestScore=0;
var i=0; // Current player index
var s='';
var arrGame=['',0];
var arrPlayerGames=[''];
var arrPretenders=[];

for (var intGame=0;intGame<intGamesCount;intGame++){
    arrGame=readline().split(' ');
    strName=String(arrGame[0]);
    intGameScore=Number(arrGame[1]);
    i=arrPlayers.indexOf(strName);
//    print('strName:intGameScore:i ['+strName+':'+intGameScore+':'+i+']');
    if (i<0) {
        arrPlayers.push(strName);
        arrScores.push(intGameScore);
        arrGames.push([]);
        arrGames[arrGames.length-1].push([intGameScore,intGame]);
//        print('arrGames[i]:'+arrGames[arrGames.length-1]);
//        print(strName+' game score '+intGameScore);
    } else {
        arrScores[i]=arrScores[i]+intGameScore;
        intBestScore=arrGames[i][arrGames[i].length-1][0];
//        print(strName+' update score from '+intBestScore+' to '+arrScores[i]);
        if (arrScores[i]>intBestScore) {
//            arrGames[i]=arrScores[i]+':'+intGame+':'+arrGames[i];
            arrGames[i].push([arrScores[i],intGame]);
//            print('arrGames[i]:'+arrGames[i]);
        }
    }
}

intBestScore=0;

for (var i=0;i<arrScores.length;i++) {
    if (intBestScore<=arrScores[i]) {
        intBestScore=arrScores[i];
        arrPretenders.push(i);
    }
}
//print('intBestScore:'+intBestScore);
//print('arrPretenders:'+arrPretenders);

intGame=intGamesCount+1;
strName='';

for (var i=0;i<arrPretenders.length;i++) {
    intPretender=arrPretenders[i];
    for (var j=0;j<arrGames[intPretender].length;j++) {
        if ((arrGames[intPretender][j][0]>=intBestScore) && (arrGames[intPretender][j][1]<intGame)) {
            intGame=arrGames[intPretender][j][1];
            strName=arrPlayers[intPretender];
        }
    }
}
//print('intGame:'+intGame);
print(strName);

var num = Number(readline());

var round, player, score;
var scores = {};
var log = [];
for(var i = 0; i < num; i++) {
    round= readline().split(" ");
    player = round[0];
    score = parseInt(round[1]);
    if (player in scores) scores[player] += score;
    else scores[player] = score;
    log.push([player, scores[player]]);
}

var playerList = Object.keys(scores).slice(0);
var winnerScore = playerList.sort((a, b) => {
    // print(`a: ${a}, score: ${scores[a]}`);
    // print(`b: ${b}, score: ${scores[b]}`);
    return scores[a] < scores[b];
})[0];
winnerScore = scores[winnerScore];

// print(winnerScore)

var winnerList = playerList.filter(player => {
    return scores[player] === winnerScore;
})

log.some(e => {
    if (winnerList.includes(e[0]) && e[1] >= winnerScore) {
        print(e[0]);
        return true;
    }
})

var tests = readline() - 0;

var Data = {};
for (var i = 0 ; i < tests ; i++)
{
var line = readline().split(' ');
Data[line[0] ] +=(Data[ line[0] ] || 0) + ( line[1] - 0 );
}

var best = "---";

for (key in Data)
{
 if  (best == "---") best = key;
if (Data[key] > Data[best]) best = key;
}

print(best);

var count = parseInt(readline());
var input = [];

for (var i = 0; i < count; i++) {
  input.push(readline());
}

var players = {}; // false means lost

for (var i = 0; i < count; i++) {
  var matches = input[i].match(/([A-Za-z]+) (-?\d+)/);
  if (matches != null) {
    var name = matches[1];
    var roundScore = parseInt(matches[2]);

    // check if player already lost
    if (players[name] === false) continue;

    var newScore = players[name] || 0;
    newScore += roundScore;
    players[name] = (newScore > -1) ? newScore : false;
  }
}

var maxScore = 0;
var winner = null;

var names = Object.keys(players);
for (var i = 0; i < names.length; i++) {
  var name = names[i];
  if (players[name] > maxScore) {
    maxScore = players[name];
    winner = name;
  }
}

print(winner);

var N = readline();
var input = [];
var gamer = {};
var gam = {};
var max = 0;

//сохраняем ввод в массив
for (var i = 0; i < N; i++) {
    var line = readline().split(' ');
    input[i] = {
        name:line[0],
        score:parseInt(line[1])
    };
    gamer[input[i].name] = 0;
    gam[input[i].name] = 0;
}
//print(" ");
for (var i = 0; i < N; i++) {
    var temp = 0;
    gam[input[i].name] += input[i].score;
    //print(input[i].name + " " + gam[input[i].name]);
    for (var key in gam) {
        if (key==input[i].name) {
            input[i].score=gam[input[i].name];
        }
    }
}
//print(" ");
//находим максимум очков
for (var i = 0; i < N; i++) {
    var temp = 0;
    for (var x = 0; x < N; x++) {
        if (input[x].score>max) {
            max=input[x].score;
        }
    }
}
//print(max);
//print(" ");
//находим первого набравшего максимум
var result = function() {
    for (var i = 0; i < N; i++) {
        //gamer[input[i].name] = gamer[input[i].name] + input[i].score;
        //print(input[i].name + " " + gamer[input[i].name]);
        if (input[i].score==max) {
            return result = input[i].name;
        }
    }
}

write(result());

function get_with_default(m, k, d) {
  return m.has(k) ? m.get(k) : d;
}

function solve(pps) {
  const m = new Map();
  let p_max = undefined;
  let pts_max = undefined;
  for (const pp of pps) {
    const [a, b] = pp.split(/\s+/);
    const pts = Number(b);
    if (p_max === undefined) {
      m.set(a, pts);
      p_max = a;
      pts_max = pts;
    } else {
      const a_pts = get_with_default(m, a, 0) + pts;
      m.set(a, a_pts);
      if (a_pts > pts_max) {
        p_max = a;
        pts_max = a_pts;
      }
    }
  }
  return p_max;
}

function main(lines) {
  const pps = [];
  lines.shift();
  for (const line of lines) {
    let t = line.trim();
    if (line.length > 0) {
      pps.push(line);
    }
  }
  const result = solve(pps);
  console.log(result);
}

async function processLinesFromStream(rs, pf) {
  const content = [];
  rs.setEncoding("utf-8");
  for await (let chunk of rs) {
    content.push(chunk);
  }
  const lines = content.join('').split(/\n/);
  const result = pf(lines);
  return result;
}

processLinesFromStream(process.stdin, main);

  var n = +readline()
  var rs = []
  var v
  for (var t = 0; t < n; t++) {
    rs.push(readline().split(' '))
  }
  var sc = rs.reduce(function (a, l) {
    a[l[0]] = (a[l[0]] || 0) + +l[1]
    return a
  }, {})
  var ms = 0
  var mso = {}
  for (var p in sc) {
    if (sc[p] > ms) {
      mso = {}
      mso[p] = true
      ms = sc[p]
    } else if (sc[p] == ms) {
      mso[p] = true
    }
  }
  var vs = Object.keys(mso)
  if (vs.length == 1)
    v = vs[0]
  if (!v) {
    sc = {}
    for (t = 0; t < n; t++) {
      p = rs[t][0]
      s = rs[t][1]
      if (((sc[p] = (sc[p] || 0) + s) >= ms) && mso[p]) {
        v = p
        break
      }
    }
  }
  print(v || rs.slice(27))

t = parseInt(readline());

i = 0;

while(t--) {
    const scores = {};
    const bestOf = {};
    const recordHit = {};
    input = readline().split(' ');

    player = input[0];
    change = parseInt(input[1]);

    if (scores[player] === undefined) scores[player] = change;
    else scores[player] += change;

    if (bestOf[player] === undefined || bestOf[player] < scores[player])
        bestOf[player] = scores[player], recordHit[player] = i;

    i++;
}

winner = Object.keys(scores).reduce(
    (best, player) => (
        best == null ||
        scores[player] > scores[best] ||
        (scores[player] == scores[best] && recordHit[player] < recordHit[best])
    ) ? player : best,
    null
);

print(winner);

  var n = +readline()
  var rs = []
  var v
  for (var t = 0; t < n; t++) {
    rs.push(readline().split(' '))
  }
  var sc = rs.reduce(function (a, l) {
    a[l[0]] = (a[l[0]] || 0) + +l[1]
    return a
  }, {})
  var ms = 0
  var mso = {}
  for (var p in sc) {
    if (sc[p] > ms) {
      mso = {}
      mso[p] = true
      ms = sc[p]
    } else if (sc[p] == ms) {
      mso[p] = true
    }
  }
  var vs = Object.keys(mso)
  if (vs.length == 1)
    v = vs[0]
  if (!v) {
    sc = {}
    for (t = 0; t < n; t++) {
      p = rs[t][0]
      s = rs[t][1]
      if (((sc[p] = (sc[p] || 0) + s) >= ms) && mso[p]) {
        v = p
        break
      }
    }
  }
  print(v || rs)

const readline = require('readline');

const INPUT = 'test.in';
const LOCAL = process.env.ENABLE_LOCAL_ENV === 'true';
const log = (...args) => {
    LOCAL && console.log(...args)
};
let rl;
let lineNr = 0;
let rounds = 0;
const r = [];

/**
 * MAIN
 */
(async () => {
    const promises = await setup(INPUT);
    await Promise.all(promises);
})();

function setup() {
    const promises = []
    rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
        terminal: false,
    });

    rl.on('line', (line) => {
        promises.push(work(line, lineNr));
        lineNr++;
    });

    rl.on('error', (err) => {
        log('Error:', err);
    });

    return new Promise(res => {
        rl.on('close', () => {
            res(promises)
            log('Done!');
        });
    });
}

async function work(line, lineNr) {
    if (lineNr) {
        r.push(line.trim().split(' '));
        if (r.length === rounds) {
            const solutionForLine = await solve(r);
            const responseLine = `${solutionForLine}\n`;
            process.stdout.write(responseLine);
        }
    } else {
        rounds = parseInt(line.trim());
        log('Line skipped:', line);
    }
}

/**
 *
 * Solution goes below
 *
 */
function solve(rounds) {
    const results = rounds.reduce((prev, current, i) => {
        const [name, points] = current;
        if (!(name in prev)) {
            prev[name] = {
                pts: 0,
                rnd: 0,
                max: -1,
                history: [],
                set lastRound(val) {
                    const p = this.pts + val;
                    if (p > this.max) {
                        this.max = p;
                        this.rnd = this.currentRound;
                    }
                    this.pts = p;
                    this.history.push({pts: p, rnd: this.currentRound});
                }
            };
        }
        prev[name].currentRound = i;
        prev[name].lastRound = parseInt(points);
        return prev;
    }, {});
    // console.log(results);

    const winners = [];
    let winner = '';
    let max = -1;
    let rnd = 0;
    for (let name in results) {
        if (results[name].pts > max) {
            max = results[name].pts;
            winner = name;
            rnd = results[name].rnd;
        } else if (results[name].pts) {
            const r1 = results[name].history.find(h => h.pts >= max);
            const r2 = results[winner].history.find(h => h.pts >= max);
            if (r1.rnd < r2.rnd) winner = name;
        }
    }
    return winner;
}

var tests = readline() - 0;

var Data = {};

var best = "---";

for (var i = 0 ; i < tests ; i++)
{
var line = readline().split(' ');
Data[line[0] ] =(Data[ line[0] ] || 0) + ( line[1] - 0 );

for (key in Data)
{
 if  (best == "---") best = key;
     if (Data[key] > Data[best]) best = key;
}

}
print(best);

var c = parseInt( readline() );

var map = {};

for(var i=0; i<c; i++){
	var line = readline().split(' ');
	var key = '$'+line[0];

	if(map[key]){
		var p =  parseInt( line[1] );
		if(p>-1){
			map[key].point += p;

		}
		map[key].step = i;
	}else{
		map[key]={
			name: line[0],
			point: parseInt( line[1] ),
			step: i
		}
	}
}

var winner = {
	point:-1E9,
	step:-1
}
//console.log( map );
for(var key in map){
	var people = map[key]
	if( people.point > winner.point ||
		(people.point == winner.point && people.step<winner.step)
		){
		winner = people;
	}
}

print(winner.name);

var N = readline();
var input = [];
var gamer = {};
var max = 0;

//сохраняем ввод в массив
for (var i = 0; i < N; i++) {
    var line = readline().split(' ');
    input[i] = {
        name:line[0],
        score:parseInt(line[1])
    };
    gamer[input[i].name] = 0;
}

//находим максимум очков
for (var i = 0; i < N; i++) {
    var temp = 0;
    for (var x = 0; x < N; x++) {
        if (input[x].name==input[i].name) {
            temp+=input[x].score;
        }
    }
    if (temp>max) {
        max = temp;
    }
}
//dfsf
//находим первого набравшего максимум
var result = function() {
    for (var i = 0; i < N; i++) {
        gamer[input[i].name] = gamer[input[i].name] + input[i].score;
        if (gamer[input[i].name]==max) {
            return result = input[i].name;
        }
    }
}

write(result());

var c = parseInt( readline() );

var map = {};

for(var i=0; i<c; i++){
	var line = readline().split(' ');
	var key = '$'+line[0];

	if(map[key]){
		var p =  parseInt( line[1] );
		if(p>-1){
			map[key].point += p;

		}
		map[key].step = i;
	}else{
		map[key]={
			name: line[0],
			point: parseInt( line[1] ),
			step: i
		}
	}
}

var winner = {
	point:-1E9,
	step:1E9
}
var max = -1E9;
//console.log( map );
for(var key in map){
	var p = map[key].point;
	if( p > max ){
		max = p;
	}
}
for(var key in map){
	var p = map[key];
	if( p.point == max &&  p.step<winner.step){
		winner = p;
	}
}

print(winner.name);