import scala.collection.mutable._
import scala.math._
object A extends App {
  val n = readLine.toInt
  val t = for(i <- 0 until n) yield {
    val Array(a, b) = for(s <- readLine.split(" ")) yield s
    (a, b.toInt)
  }
  val map = collection.mutable.Map[String,Int]()
  for(i <- t) {
    val k = i._1
    val v = i._2 + {if(map.contains(i._1)) map(i._1) else 0}
    map(k) = v
  }
  var score = -(1<<29)
  for((k,v) <- map) {
    score = max(score, v)
  }
  val map2 = collection.mutable.Map[String,Int]()
  var name: String = null
  for(i <- t) {
    val k = i._1
    if(map(k) == score) {
      val v = i._2 + {if(map2.contains(i._1)) map2(i._1) else 0}
      map2(k) = v
      if(v >= score && name == null) {
        name = k
      }
    }
  }
  println(name)
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random

object P002A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N = sc.nextInt
  sc.nextLine

  type Round = (String, Int)
  type Score = Round

  def readRound(): Round = {
    val elms = sc.nextLine.split(" ")
    (elms(0), elms(1).toInt)
  }

  val rounds: List[Round] = List.fill(N)(readRound)

  def solve(): String = {
    val scores: Map[String, Int] = rounds.groupBy(_._1).toSeq
      .map(s => (s._1 -> s._2.map(_._2).sum))
      .toMap
    val m: Int = scores.values.max
    val winners: List[String] = scores.toList.filter(_._2 == m).map(_._1)

    val scoreBoard = mutable.Map.empty[String, Int]
    val history = new ListBuffer[Score]
    rounds.foreach { r =>
      val (name, point): Round = r
      val update = (name -> (scoreBoard.getOrElse(name, 0) + point))
      scoreBoard += update
      history += update
    }
    history.toList.filter(x => winners.contains(x._1)).dropWhile(_._2 < m).head._1
  }

  out.println(solve)
  out.close
}

object Winner {

  def findWinner(winners:Set[String], games:List[(String, Int)], max: Int): String = {
    val winnerScores = collection.mutable.Map.empty[String, Int].withDefaultValue(0);
    for(game<-games.filter(g=>winners.contains(g._1)))
    {
      winnerScores(game._1) += game._2;
      if (winnerScores(game._1)>=max)
        return game._1;
    }
    return "";
  }

  def toGame(items : Array[String]) ={
    (items(0),items(1).toInt)
  }

  def main(args: Array[String]) = {
    val n = readLine().toInt;
    val games = (1 to n).map(_=>readLine()).map(s=>toGame(s.split(" "))).toList;
    val totals = games.groupBy(_._1).mapValues(_.map(_._2).reduce(_+_)).toList;
    val max = totals.map(_._2).max;
    val winners = totals.filter(_._2==max).map(_._1).toSet;
    println(findWinner(winners, games,max))

  }
}

object P2A {
    import io.StdIn._

    def main(args : Array[String]) {
        val s = Array.tabulate(readInt){i => {
            val Array(name, score) = readLine.split(' ')
            (name, score.toInt, i)
        }}.groupBy{_._1}
        val maxTotal = s.map{_._2.map{_._2}.sum}.max
        val winners = s.filter{_._2.map{_._2}.sum == maxTotal}
        println(winners.minBy{case (name, rec) => {
            def f(i:Int, n:Int):Int = {
                if (i == rec.size) return Int.MaxValue
                val nN = n + rec(i)._2
                if (nN >= maxTotal) rec(i)._3 else f(i + 1, nN)
            }; f(0, 0)
        }}._1)
    }
}

object Prob2A_Winner extends App {
  import java.util.{Scanner => Input}

  val in = new Input(System.in)

  val n = in.nextInt
  val names = Array.ofDim[String](n)
  val scores = Array.ofDim[Int](n)
  for (i <- 0 until n) {
    names(i) = in.next
    scores(i) = in.nextInt
  }

  val map = new collection.mutable.HashMap[String, Int]
  for (i <- 0 until n) {
    if (!map.contains(names(i)))
      map += (names(i) -> 0)
    map(names(i)) += scores(i)
  }
  val finalScore = map.values.max
  val map2 = new collection.mutable.HashMap[String, Int]
  var i = 0
  while (i < n) {
    if (!map2.contains(names(i)))
      map2 += (names(i) -> 0)
    map2(names(i)) += scores(i)
    if (map(names(i)) == finalScore && map2(names(i)) >= finalScore) {
      println(names(i))
      i = n
    }
    i += 1
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val map = scala.collection.mutable.Map[String, Seq[(Int, Int)]]()
    for (i <- 1 to n) {
      val a = readLine().split(" ")
      val s = map.getOrElse(a(0), Seq.empty[(Int, Int)])
      map(a(0)) = s ++ Seq(i -> (a(1).toInt + s.lastOption.getOrElse((0, 0))._2))
    }
    val max = map.values.map(_.last._2).max
    val f = map.filter{ case (name, score) => score.last._2 == max }
    if (f.size == 1) println(f.keys.toList.apply(0))
    else {
      val f1 = f.toList.map{ case (name, score) => (name, score.find(_._2 >= max)) }
      println(f1.sortBy(_._2.get._1).head._1)
    }
  }
}

import scala.io.StdIn
import scala.annotation.tailrec

case class RoundEvent(winner: String, score: Int)

object X extends App {
  val rounds = StdIn.readInt()

  val res = (0 until rounds)
    .map(_ =>
      StdIn.readLine().split(" ") match {
        case Array(s1, s2) => RoundEvent(s1, s2.toInt)
      }
    )

  val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {
    accMap + (result.winner -> (accMap
      .getOrElse(result.winner, 0) + result.score))
  })

  val topEndScore = endScores.map(_._2).max

  val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)

  @tailrec
  def findFirstWinner(
      rounds: Seq[RoundEvent],
      currScores: Map[String, Int] = Map()
  ): String = {
    val fst = rounds.head
    val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score
    val updatedScores = currScores + (fst.winner -> nextScore)
    if (nextScore >= topEndScore && endScores(fst.winner) == topEndScore)
      fst.winner
    else findFirstWinner(rounds.tail, updatedScores)
  }

  val firstWinner = findFirstWinner(res)

  println(firstWinner)
}

object Main extends App{

  def scan(index:Int, map:Map[String, Int], list:List[(String, Int)]):(List[(String, Int)],Map[String, Int])  = {
    if(index > 0){
      val values = Console.readLine().trim().split(" ")
      val name = values(0)
      val value =  values(1).toInt
      if(value < -1000 || value > 1000) throw new Exception("Illegal value")
      val res:Map[String, Int] = if(!map.isEmpty && map.contains(name)){
        Map(name -> (value + map(name))) ++ (map - name)
      }
      else {
        map ++ Map(name -> value)
      }
      scan(index-1, res, list ++ List((name, res(name))))
    }
    else {
      (list, map)
    }
  }

  var results:Map[String,Int] = Map()

  val numOfRounds = Console.readInt
  if(numOfRounds <= 0) {
    throw new Exception("Illegal value")
  }

  val (list, map) = scan(numOfRounds, results, List())

  val max = map.values.toArray.max

  val winners = map.filter( _._2 == max).keySet
   println(list.find( (tuple) => tuple._2 >= max  && winners.contains(tuple._1)).get._1)
}

import collection.mutable._

object Main {

  def input(rounds: Int, list: List[(String, Int)]): List[(String, Int)] = rounds match {
    case 0 => list
    case _ => input(rounds - 1, (scanner.next, scanner.nextInt) :: list)
  }

  val scanner = new java.util.Scanner(System.in)
  val list = input(scanner.nextInt, List())
  val candidates = list.groupBy(_._1).flatMap(e => Some(e._1, e._2.map(_._2).sum))
  val max = candidates.values.max
  val winners = new HashMap() ++ candidates.filter(_._2 == max)

  def isWinner(person: String, score: Int) = {
    winners(person) -= score
    winners(person) <= 0
  }

  def findWinner(list: List[(String, Int)]): String = list match {
    case (person, score) :: _ if (isWinner(person, score)) => person
    case _ :: tail => findWinner(tail)
    case Nil => null
  }

  def main(args: Array[String]) {
    println(findWinner(list.filter(e => winners.contains(e._1)).reverse))
  }
}

import java.util.Scanner

import scala.collection.mutable

object Solution {
  def main(args: Array[String]): Unit = {

    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()

    val players: mutable.Map[String, Long] = mutable.Map.empty
    val scores: mutable.Map[Long, (Int, String)] = mutable.Map.empty

    for (i <- 0 until n) {
      val name = scanner.next()
      val score = scanner.nextLong()

      val currentScore = players.getOrElse(name, 0L) + score

      players(name) = currentScore

      if (!scores.contains(currentScore))
        scores(currentScore) = (i, name)
    }

    val maxScore = players.valuesIterator.max
    val candidates = players.filter(tuple => tuple._2 == maxScore).keys.toSet

    println(
      if (candidates.size == 1)
        candidates.head
      else
        searchWinner()
    )

    def searchWinner(): String = {
      scores
        .filter(t => t._1 >= maxScore)
        .filter(t => candidates.contains(t._2._2))
        .values.toList
        .sortBy(t => t._1)
        .head._2
    }
  }
}

import collection.mutable._

object Main2 {

  def input(rounds: Int, list: List[(String, Int)]): List[(String, Int)] = rounds match {
    case 0 => list
    case _ => input(rounds - 1, list :+ (scanner.next, scanner.nextInt))
  }

  val scanner = new java.util.Scanner(System.in)
  val list = input(scanner.nextInt, List())
  val candidates = list.groupBy(_._1).flatMap(e => Some(e._1, e._2.map(_._2).sum))
  val max     = candidates.values.max
  val winners = candidates.filter(_._2 == max)
  val steps   = list.filter(e => winners.contains(e._1))
  val scores  = new HashMap[String, Int]() { override def default(key:String) = 0 }
  val winner  = steps.find(e => { scores(e._1) += e._2; scores(e._1) >= max } ).get

  def main(args: Array[String]) {
    println(winner._1)
  }
}

import collection.mutable._

object Main {
  val scanner = new java.util.Scanner(System.in)
  val totals  = new HashMap[String, Int]() { override def default(key:String) = 0 }

  def read(rounds: Int, player: String, score: Int): List[(String, Int)] = {
    totals(player) += score
    rounds match {
      case 0 => (player, totals(player)) :: Nil
      case _ => (player, totals(player)) :: read(rounds - 1, scanner.next, scanner.nextInt)
    }
  }

  def main(args: Array[String]): Unit = {
    val game    = read(scanner.nextInt - 1, scanner.next, scanner.nextInt)
    val max     = totals.values.max
    val winners = totals.filter(_._2 == max)
    println(game
        .filter(e => winners.contains(e._1))
        .filter(_._2 >= max)(0)._1
    )
  }
}

object P2A {
    def main(args : Array[String]) {
        val n = readLine.toInt
        val s = Array.fill(n) {
            val Array(s1, s2) = readLine split " "
            (s1, s2.toInt)
        }.zipWithIndex groupBy {
            case ((name, score), idx) => name
        }
        val maxTotal = s.map{_._2.map{_._1._2}.sum}.max
        val winners = s.filter{_._2.map{_._1._2}.sum == maxTotal}
        val winner = winners.minBy{
            _._2.scanLeft(0, 0){
                case ((idxS, scoreS), ((name, score), idx)) =>
                    (idx, scoreS + score)
            }.find{
                case (idx, scoreS) => scoreS >= maxTotal
            }.getOrElse(Int.MaxValue, 0)._1
        }._1
        println(winner)
    }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val r = Range(0, n).map{_ =>
    val d = in.next().split(" ")
    (d.head, d.tail.head.toInt)
  }
  val grouped: Map[String, Int] = r.groupBy(t => t._1).map(t => t._1 -> t._2.map(_._2).sum)
  val max = grouped.maxBy(_._2)._2
  val maxg = grouped.filter(t => t._2 == max)
  if (maxg.size > 1) {
    val names = maxg.keySet
    val a = r.filter(t => names.contains(t._1)).foldLeft(names.map(t => t -> 0).toMap) {
      case(acc, el) if acc.values.max >= max => acc
      case(acc, el) => acc + (el._1 -> (acc(el._1) + el._2))
    }.maxBy(_._2)
    println(a._1)
  } else
    println(maxg.head._1)
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CBR2A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val mp = collection.mutable.HashMap.empty[String, Int]
    val n = ni()

    val names = Array.ofDim[String](n)
    val score = Array.ofDim[Int](n)

    var res = -1000001

    REP(n) { i =>
      val nm = ns()
      val v = ni()

      names(i) = nm
      score(i) = v

      if(mp.contains(nm)) {
        mp(nm) = mp(nm) + v
      } else {
        mp(nm) = v
      }
    }

    REP(n) { i =>
      if(mp(names(i)) > res) {
         res = mp(names(i))
      }
    }

    var name: String = "-1"
//    out.println(res)
    val mp1 = collection.mutable.HashMap.empty[String, Int]
    REP(n) { i =>
      if(mp1.contains(names(i))) {
        mp1(names(i)) += score(i)
      } else mp1(names(i)) = score(i)
      if(mp1(names(i)) >= res && mp(names(i)) == res && name == "-1") {
        name = names(i)
      }
    }
    out.println(name)
  }
}

import java.util.Scanner

object Winner extends App {

  var playerScores = Map.empty[String, Player]

  val scanner = new Scanner(System.in)
  val size = scanner.nextInt()

  (0 until size).map(it => (scanner.next(), scanner.nextInt()))
  .zipWithIndex.foreach {
    record =>
      playerScores.get(record._1._1) match {
        case None =>
          val player = Player(record._1._1)
          player.addScore(record._1._2, record._2)
          playerScores += (record._1._1 -> player)
        case Some(v) =>
          v.addScore(record._1._2, record._2)
      }
  }

  val players = playerScores.values.toList
  val finalScore = players.sortBy(_.score).last.score

  val result = players
    .sortBy(-_.smallestMoveForPointsMorThan(finalScore))
    .sortBy(_.score).last

  println(result.name)

  case class Player(name: String) {

    var score: Int = 0

    var scoreHistory = List.empty[(Int, Int)]

    def addScore(points: Int, moveNum: Int): Unit = {
      score += points
      scoreHistory ::= (moveNum, score)
    }

    def smallestMoveForPointsMorThan(max: Int):Int = {
      scoreHistory.sortBy(_._1).find(_._2 >= max) match {
        case Some(v) => v._1
        case None => Integer.MAX_VALUE
      }
    }

  }

}

/*
8
andrew 3
andrew 2
mike 5
mike 2
andrew 2
mike 3
andrew 4
andrew -1
*/

object A2 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = Array.fill(n){
      val tl = tokenizeLine
      (tl.nextToken(), tl.nextToken().toInt)
    }
    val map = cu.Map.empty[String, Int].withDefaultValue(0)
    for(i <- 0 until n)
      map(in(i)._1) += in(i)._2
    val max = map.maxBy(_._2)._2
    var winners = {
      val newMap = cu.Map.empty[String, Int].withDefaultValue(0)
      map.filter{case (k, v) => v == max}.keys.foreach(newMap(_) = 0)
      newMap
    }
    if(winners.size == 1) {
      println(winners.keySet.head)
    } else {
      //replay
      var res = ""
      for(i <- 0 until n if winners.contains(in(i)._1)) {
        winners(in(i)._1) += in(i)._2
        if(res.isEmpty && winners(in(i)._1) >= max) {
          res = in(i)._1
        }
      }
      println(res)
    }
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine;
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val input = (for (i <- 1 to n) yield scanner.nextLine().split(" ") match {case Array(name, score) => (name, score.toInt)}).toList

  val result = input.groupBy(_._1).mapValues(_.map(_._2).sum)
  val maxScore = result.maxBy(_._2)._2
  val winners = result.filter(_._2 == maxScore).keys

  def replay: String = {
    @tailrec
    def turn(acc: Map[String, Int], data: List[(String, Int)]): String = {
      val current = data.head
      if (acc.get(current._1).isEmpty) turn(acc, data.tail)
      else {
        val score = acc.get(current._1).get + current._2
        if (score >= maxScore) current._1
        else turn(acc.updated(current._1, score), data.tail)
      }
    }
    turn(winners.map((_, 0)).toMap, input)
  }

  if (winners.size == 1) println(winners.head)
  else println(replay)
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      val scores : mutable.HashMap[String, Int]  = new mutable.HashMap()

      var lst : List[(String, Int)] = Nil

      val n: Int = StdIn.readLine().toInt
      for (_ <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        lst = lst :+ (_name, _score)
        val sc = scores.get(_name)

        sc match {
          case Some(score_got) => scores.put(_name, score_got + _score)
          case None => scores.put(_name, _score)
        }

      }

      var score: Int = 0

      for ((_,v) <- scores) {
        if (score < v) {
          score = v
        }
      }

      var name = ""
      var found = false
      val scores_post : mutable.HashMap[String, Int]  = new mutable.HashMap()
      for ((k,v) <- lst) {
        if (!found) {
          val sc = scores_post.get(k)
          val allscore = sc match {
            case Some(score_got) => score_got + v
            case None => v
          }
          scores_post.put(k, allscore)
          if (allscore >= score && scores(k) == score) {
            name = k
            found = true
          }
        }
      }

      println(name)
  }
}

import collection.mutable
import io.Source

// 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.

object Winner {

    def main(args: Array[String]) = {
        val lines = Source.stdin.getLines()
        lines.next()

        val gameTrace = lines.toList.map(line => { val splitLine = line.split(" "); Pair(splitLine(0), splitLine(1).toInt)})

        println(getWinner(gameTrace))
    }

    def getWinner(gameTrace: List[Pair[String, Int]]) = {
        val finalScores = gameTrace.foldLeft(Map[String, Int]().withDefaultValue(0)) {
            case (scores, (player, pointsWon)) => scores + (player -> (scores(player) + pointsWon))}

        // now find the max final score
        val maxFinalScore = finalScores.foldLeft(finalScores.head._2) {case (maxSoFar, (_, score)) => maxSoFar max score}
        val potentialWinners = finalScores.filter {case (_, score) => (score == maxFinalScore)}
        // single potential winner?
        if (potentialWinners.tail.isEmpty) {
            potentialWinners.head._1
        }
        else {
            firstPlayerToMaxScore(gameTrace, potentialWinners, maxFinalScore)
        }
    }

    def firstPlayerToMaxScore(gameTrace: List[Pair[String, Int]], possWinners: Map[String, Int], maxFinalScore: Int) = {

        def auxFirstRec(currGamePosition: List[Pair[String, Int]], currScores: Map[String, Int]): String = {
            currGamePosition match {
                case (player, pointsWon) :: rest => if (currScores(player) + pointsWon >= maxFinalScore)
                                                player
                                            else
                                                auxFirstRec(rest, currScores + (player -> (currScores(player) + pointsWon)))
                case Nil                         => "randomguess"
            }
        }

        val filteredTrace = gameTrace.filter{case (player, _) => possWinners.contains(player)}
        auxFirstRec(filteredTrace, Map[String, Int]().withDefaultValue(0))
    }

}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object Winner {

  def update(scores: mutable.HashMap[String, Int], name: String, value: Int): Int = {
    val base = scores.getOrElse(name, 0)
    scores.update(name, base + value)
    base + value
  }

  def main(args: Array[String]) = {
    val n = scala.io.StdIn.readLine().toString.toInt
    val names = new ArrayBuffer[String]
    val values = new ArrayBuffer[Int]
    val scores = new mutable.HashMap[String, Int]()
    for (i <- 0 until n) {
      val line = scala.io.StdIn.readLine().split(" ")
      names += line(0)
      values += line(1).toInt
      update(scores, names(i), values(i))
    }
    var max_value = scores.values.max
    val final_scores = new mutable.HashMap[String, Int]()
    var winner = ""
    for (i <- 0 until n) {
      if (winner == "" && max_value <= update(final_scores, names(i), values(i)) &&
        scores.getOrElse(names(i), 0) == max_value) {
        winner = names(i)
      }
    }
    println(winner)
  }
}

import collection.mutable

object Main {
  def main(args: Array[String]) = {
    val n = readInt
    val rnd = (1 to n).map(_=>readLine.split("\\s+")).map(x=>(x(0), x(1).toInt))
    var score = mutable.Map(rnd.map(x=>(x._1, 0)):_*)
    rnd.foreach(r=>{score(r._1) += r._2})
    val m = score.values.max
    val wincnt = score.count(_._2==m)
    if (wincnt==1) {
      println(score.maxBy(_._2)._1)
    } else {
      def firstRound(rnd:Seq[(Int,Int)], acc:Int):Int = {
        if (acc+rnd.head._2>=m) rnd.head._1
        else firstRound(rnd.tail, acc+rnd.head._2)
      }
      val winners = score.filter(_._2==m).map(w=>(w._1, firstRound(rnd.zipWithIndex.filter(_._1._1==w._1).map(r=>(r._2, r._1._2)), 0)))
      val winRound = winners.map(_._2).min
      println(winners.filter(_._2==winRound).head._1)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

/**
 * Created by gzq on 4/6/15.
 */
object CF2A {
  def main(args: Array[String]): Unit = {
    class nameAndScore(val name: String, val score: Int)

    val in = scala.io.StdIn
    val count = in.readInt()

    val name2Score = new mutable.HashMap[String, Int]()
    var scoresStat = new ListBuffer[nameAndScore]

    for (i <- 1 to count) {
      val nameScore = in.readLine().split(" ")
      val name = nameScore(0)
      val score = nameScore(1).toInt

      if (name2Score.contains(name)) {
        val curScore = name2Score(name) + score
        name2Score(name) = curScore
        scoresStat += (new nameAndScore(name, curScore))
      } else {
        name2Score(name) = score
        scoresStat += (new nameAndScore(name, score))
      }
    }

    val winnerScore = name2Score.reduce(
      (winner, current) => if (winner._2 > current._2) winner else current
    )._2

    val names = scoresStat.filter(
      (stat: nameAndScore) =>
        name2Score(stat.name) == winnerScore && stat.score >= winnerScore
    )
    println(names(0).name)
 }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

/**
 * Created by gzq on 4/6/15.
 */
object CF2A {
  def main(args: Array[String]): Unit = {
    class nameAndScore(val name: String, val score: Int)

    val in = scala.io.StdIn
    val count = in.readInt()

    val name2Score = new mutable.HashMap[String, Int]()
    var scoresStat = new ListBuffer[nameAndScore]

    for (i <- 1 to count) {
      val nameScore = in.readLine().split(" ")
      val name = nameScore(0)
      val score = nameScore(1).toInt

      if (name2Score.contains(name)) {
        val curScore = name2Score(name) + score
        name2Score(name) = curScore
        scoresStat += (new nameAndScore(name, curScore))
      } else {
        name2Score(name) = score
        scoresStat += (new nameAndScore(name, score))
      }
    }

//    val winnerScore = name2Score.reduce(
//      (winner, current) => if (winner._2 > current._2) winner else current
//    )._2

    val winnerScore = name2Score.values.max

    val names = scoresStat.filter(
      (stat: nameAndScore) =>
        name2Score(stat.name) == winnerScore && stat.score >= winnerScore
    )
    println(names(0).name)
 }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      val scores : mutable.HashMap[String, (Int, Int)]  = new mutable.HashMap()
      var score : Int = 0

      val n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        val sc = scores.get(_name)

        val (allsc, step) = sc match {
          case Some(score_got) => (score_got._1 + _score, score_got._2)
          case None => (_score, i)
        }

        if (allsc >= score) {
          score = allsc
          scores.put(_name, (allsc, i))
        } else {
          scores.put(_name, (allsc, step))
        }
      }

      var step = Int.MaxValue
      var name = ""
      for((key,value) <- scores) {
        val (sc, ind) = value
        if (sc == score) {
          if (ind < step) {
            step = ind
            name = key
          }
        }
      }

      println(name)
  }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      var scores : mutable.HashMap[String, Int]  = new mutable.HashMap()
      var name : String = ""
      var score : Int = 0
      var step = -1

      var n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        if (name == "") {
          name = _name
          score = _score
          scores.put(name, score)
          step = i
        } else {
            val sc = scores.get(_name)
            var allsc = 0
            sc match {
              case Some(score_got) => {
                allsc = score_got + _score
                scores.put(_name, allsc)
              }
              case None => {
                scores.put(_name, _score)
                allsc = _score
              }
            }
            if (allsc > score) {
              step = i
              name = _name
              score = allsc
            } else if (allsc == score) {
              if (step >= i) {
                step = i
                name = _name
                score = allsc
              }
            }

        }
      }
      println(name)

  }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      var scores : mutable.HashMap[String, Int]  = new mutable.HashMap()
      var name : String = ""
      var score : Int = 0
      var step = -1

      var n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        if (name == "") {
          name = _name
          score = _score
          scores.put(name, score)
          step = i
        } else {
            val sc = scores.get(_name)
            var allsc = 0
            sc match {
              case Some(score_got) => {
                allsc = score_got + _score
                scores.put(_name, allsc)
              }
              case None => {
                scores.put(_name, _score)
                allsc = _score
              }
            }
            if (allsc > score) {
              step = i
              name = _name
              score = allsc
            } else if (allsc == score) {
              if (step > i) {
                step = i
                name = _name
                score = allsc
              }
            }

        }
      }
      println(name)

  }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      val scores : mutable.HashMap[String, Int]  = new mutable.HashMap()
      var name : String = ""
      var score : Int = 0
      var step = -1

      val n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        if (name == "") {
          name = _name
          score = _score
          scores.put(name, score)
          step = i
        } else {
          val sc = scores.get(_name)
          val allsc = sc match {
            case Some(score_got) => score_got + _score
            case None => _score
          }
          scores.put(_name, allsc)
          if (name == _name) {
            score = allsc
          }
          if (allsc > score) {
            step = i
            name = _name
            score = allsc
          } else if (allsc == score) {
            if (step > i) {
              step = i
              name = _name
              score = allsc
            }
          }
        }
      }
      println(name)
  }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      val scores : mutable.HashMap[String, (Int, Int)]  = new mutable.HashMap()
      var score : Int = 0

      val n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        val sc = scores.get(_name)

        val (allsc, step) = sc match {
          case Some(score_got) => (score_got._1 + _score, score_got._2)
          case None => (_score, i)
        }

        if (allsc >= score) {
          score = allsc
          scores.put(_name, (allsc, step))
        } else {
          scores.put(_name, (allsc, i))
        }
      }

      var step = Int.MaxValue
      var name = ""
      for((key,value) <- scores) {
        val (sc, ind) = value
        if (sc == score) {
          if (ind < step) {
            step = ind
            name = key
          }
        }
      }

      println(name)
  }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      val scores : mutable.HashMap[String, (Int, Int)]  = new mutable.HashMap()
      var score : Int = 0
      var nm : String = ""

      val n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        val sc = scores.get(_name)
        if (nm == "") {
          nm = _name
        }
        val allsc = sc match {
          case Some(score_got) => score_got._1 + _score
          case None => _score
        }
        if (_name == nm) {
          score = allsc
        }
        scores.put(_name, (allsc, i))
        if (allsc > score) {
          score = allsc
        }
      }

      var step = Int.MaxValue
      var name = ""
      for((key,value) <- scores) {
        val (sc, ind) = value
        if (sc == score) {
          if (ind < step) {
            step = ind
            name = key
          }
        }
      }

      println(name)
  }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      val scores : mutable.HashMap[String, Int]  = new mutable.HashMap()

      var lst : List[(String, Int)] = Nil

      val n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        lst = lst :+ (_name, _score)
        val sc = scores.get(_name)

        sc match {
          case Some(score_got) => scores.put(_name, score_got + _score)
          case None => scores.put(_name, _score)
        }

      }

      var score: Int = 0

      for ((_,v) <- scores) {
        if (score < v) {
          score = v
        }
      }

      var name = ""
      var found = false
      val scores_post : mutable.HashMap[String, Int]  = new mutable.HashMap()
      for ((k,v) <- lst) {
        if (!found) {
          val sc = scores_post.get(k)
          val allsc = sc match {
            case Some(score_got) => score_got + v
            case None => v
          }
          scores_post.put(k, allsc)
          if (allsc >= score) {
            name = k
            found = true
          }
        }
      }

      println(name)
  }
}

import scala.collection.mutable
import scala.io.StdIn

object Winner {
  def main(args: Array[String]) : Unit = {
      val scores : mutable.HashMap[String, (Int, Int)]  = new mutable.HashMap()

      val n: Int = StdIn.readLine().toInt
      for (i <- 0 until n) {
        val line = StdIn.readLine().split(" ")
        val _name : String = line(0)
        val _score : Int = line(1).toInt
        val sc = scores.get(_name)

        sc match {
          case Some(score_got) => scores.put(_name, (score_got._1 + _score, i))
          case None => scores.put(_name, (_score, i))
        }

      }

      var name: String = ""
      var score: Int = 0
      var ind = -1

      for ((k,(v,i)) <- scores) {
          if (name.isEmpty) {
              name = k
              score = v
              ind = i
          } else {
            if (score < v) {
              name = k
              score = v
              ind = i
            } else if (score == v) {
              if (i < ind) {
                name = k
                score = v
                ind = i
              }
            }
          }
      }

      println(name)
  }
}

import scala.collection.mutable

/**
 * Created by gzq on 4/6/15.
 */
object CF2B {
  def main(args: Array[String]) {
    var winnerName = ""
    var winnerScore = Int.MinValue
    val scores = new mutable.HashMap[String, Int]()
    val in = scala.io.StdIn

    val count = in.readInt()

    for (i <- 0 until count) {
      val strArr = in.readLine().split(" ")
      val name = strArr(0)
      val score = strArr(1).toInt

      if (scores.contains(name)) {
        val thisScore = score + scores(name)
        scores(name) = thisScore
        if (thisScore > winnerScore) {
          winnerScore = thisScore
          winnerName = name
        }
      } else {
        scores(name) = score
        if (score > winnerScore) {
          winnerScore = score
          winnerName = name
        }
      }
    }
    println(winnerName)
  }

}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

/**
 * Created by gzq on 4/6/15.
 */
object CF2A {
  def main(args: Array[String]) {
    var winnerName = ""
    var winnerScore = Int.MinValue
    val in = scala.io.StdIn

    val count = in.readInt()

    val nameSet = new ListBuffer[String]
    val name2scores = new mutable.HashMap[String, Int]()

    for (i <- 0 until count) {
      val nameAndScore = in.readLine().split(" ")
      val name = nameAndScore(0)
      val deltaScore = nameAndScore(1).toInt
      if (name2scores.contains(name)) {
        nameSet -= name
        nameSet += name
        name2scores(name) = name2scores(name) + deltaScore
      } else {
        nameSet += name
        name2scores(name) = deltaScore
      }
    }

    for (name <- nameSet) {
      val score = name2scores(name)
      if (score > winnerScore) {
        winnerName = name
        winnerScore = score
      }
    }

    println(winnerName)
  }

}

import java.util.Scanner

import scala.collection.mutable

object Solution {
  def main(args: Array[String]): Unit = {

    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()

    val scores: mutable.Map[String, Long] = mutable.Map.empty
    var winner: (String, Long) = ("", 0)

    for (i <- 0 until n) {
      val name = scanner.next()
      val score = scanner.nextLong()

      var currentScore: Long = scores.getOrElse(name, 0)
      currentScore = score + currentScore
      scores(name) = currentScore
      if (winner._2 < currentScore) winner = (name, currentScore)
    }

    println(winner._1)
  }
}

import java.util.Scanner

import scala.collection.mutable

object Solution {
  def main(args: Array[String]): Unit = {

    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()

    val players: mutable.Map[String, Long] = mutable.Map.empty
    val scores: mutable.Map[Long, (Int, String)] = mutable.Map.empty

    for (i <- 0 until n) {
      val name = scanner.next()
      val score = scanner.nextLong()

      val currentScore = players.getOrElse(name, 0L) + score

      players(name) = currentScore

      if (!scores.contains(currentScore))
        scores(currentScore) = (i, name)
    }

    val maxScore = players.valuesIterator.max
    val candidates = players.filter(tuple => tuple._2 == maxScore).keys

    println(
      if (candidates.size == 1)
        candidates.head
      else
        searchWinner()
    )

    def searchWinner(): String = {
      val buffer: mutable.Buffer[(Int, String)] = mutable.Buffer.empty
      for (tuple <- scores)
        if (tuple._1 >= maxScore)
          buffer += tuple._2

      buffer.sortBy(t => t._1).head._2
    }
  }
}

import java.util.Scanner

import scala.collection.mutable

object Solution {
  def main(args: Array[String]): Unit = {

    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()

    val scores: mutable.Map[String, Long] = mutable.Map.empty
    var winner: (String, Long) = ("", 0)

    for (i <- 0 until n) {
      val name = scanner.next()
      val score = scanner.nextLong()
      if (score > 0) {
        var currentScore: Long = scores.getOrElse(name, 0)
        currentScore = score + currentScore
        scores(name) = currentScore
        if (winner._2 < currentScore) winner = (name, currentScore)
      }
    }

    println(winner._1)
  }
}

import java.util.Scanner

import scala.collection.mutable

object Solution {
  def main(args: Array[String]): Unit = {

    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()

    val history: mutable.Buffer[(String, Long)] = mutable.Buffer.empty
    val scores: mutable.Map[String, Long] = mutable.Map.empty
    var winner: (String, Long) = ("", 0)

    for (i <- 0 until n) {
      val name = scanner.next()
      val score = scanner.nextLong()

      var currentScore: Long = scores.getOrElse(name, 0)
      var tuple = (name, score)
      history += tuple

      currentScore = score + currentScore
      scores(name) = currentScore
      if (winner._2 < currentScore) winner = (name, currentScore)
    }

    val maxScore: Long = scores.valuesIterator.max
    val candidates = scores.filter(tuple => tuple._2 == maxScore).keys
    if (candidates.size == 1)
      println(candidates.head)
    else
      println(getWinner(history, maxScore, candidates))
  }

  def getWinner(history: mutable.Buffer[(String, Long)], maxScore: Long, candidates: Iterable[String]): String = {
    val winners: mutable.Map[String, Long] = mutable.Map.empty
    for (step <- history) {
      val currentScore = winners.getOrElse(step._1, 0L) + step._2
      if (currentScore >= maxScore)
        return step._1

      winners(step._1) = currentScore
    }
    ""
  }

}

import java.util.Scanner

import scala.collection.mutable

object Solution {
  def main(args: Array[String]): Unit = {

    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()

    val scores: mutable.Map[String, Long] = mutable.Map.empty
    var winner: (String, Long) = ("", 0)

    for (i <- 0 until n) {
      val name = scanner.next()
      val score = scanner.nextLong()

      var currentScore: Long = scores.getOrElse(name, 0)
      currentScore = score + currentScore
      scores(name) = currentScore
      if (winner._2 < currentScore) winner = (name, currentScore)
    }

    val maxScore = scores.valuesIterator.max
    val winners = scores.filter(tuple => tuple._2 == maxScore)
    if (winners.size == 1)
      println(winners.head._1)
    else
      println(winner._1)

  }
}

import java.util.Scanner

import scala.collection.mutable

object Solution {
  def main(args: Array[String]): Unit = {

    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()

    val players: mutable.Map[String, Long] = mutable.Map.empty
    val scores: mutable.Map[Long, String] = mutable.Map.empty

    for (i <- 0 until n) {
      val name = scanner.next()
      val score = scanner.nextLong()

      val currentScore = players.getOrElse(name, 0L) + score

      players(name) = currentScore

      if (!scores.contains(currentScore))
        scores(currentScore) = name
    }

    val maxScore = scores.keys.max
    println(scores(maxScore))
  }
}

import scala.collection.mutable._
import scala.math._
object A extends App {
  val n = readLine.toInt
  val t = for(i <- 0 until n) yield {
    val Array(a, b) = for(s <- readLine.split(" ")) yield s
    (a, b.toInt)
  }
  val map = collection.mutable.Map[String,Int]()
  var name: String = null
  var score: Int = -1
  for(i <- t) {
    val k = i._1
    val v = i._2 + {if(map.contains(i._1)) map(i._1) else 0}
    map(k) = v
    if(v > score) {
      name = k
      score = v
    }
  }
//  println(map.maxBy(_._2)._1)
  println(name)
}

import scala.collection.mutable._
import scala.math._
object A extends App {
  val n = readLine.toInt
  val t = for(i <- 0 until n) yield {
    val Array(a, b) = for(s <- readLine.split(" ")) yield s
    (a, b.toInt)
  }
  println(t)
  val map = collection.mutable.Map[String,Int]()
  for(i <- t) {
    if(map.contains(i._1)) map(i._1) = map(i._1) + i._2
    else map(i._1) = i._2
  }
  println(map.maxBy(_._2)._1)
}

import scala.collection.mutable._
import scala.math._
object A extends App {
  val n = readLine.toInt
  val t = for(i <- 0 until n) yield {
    val Array(a, b) = for(s <- readLine.split(" ")) yield s
    (a, b.toInt)
  }
  val map = collection.mutable.Map[String,Int]()
  var name: String = null
  var score: Int = -1
  for(i <- t) {
    if(map.contains(i._1)) map(i._1) = map(i._1) + i._2
    else map(i._1) = i._2
    if(map(i._1) > score) {
      name = i._1
      score = map(i._1)
    }
  }
//  println(map.maxBy(_._2)._1)
  println(name)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val r = Range(0, n).map{_ =>
    val d = in.next().split(" ")
    (d.head, d.tail.head.toInt)
  }
  val grouped: Map[String, Int] = r.groupBy(t => t._1).map(t => (t._1, t._2.map(_._2).sum))
  val max = r.maxBy(_._2)._2
  val maxg = grouped.filter(t => t._2 == max)
  if (maxg.size > 1) {
    val names = maxg.keySet
    val a = r.foldLeft(names.map(t => t -> 0).toMap) {
      case(acc, el) if acc.values.max >= max => acc
      case(acc, el) => acc + (el._1 -> (acc.getOrElse(el._1, 0) + el._2))
    }.maxBy(_._2)
    println(a._1)
  } else
    println(grouped.head._1)
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val r = Range(0, n).map{_ =>
    val d = in.next().split(" ")
    (d.head, d.tail.head.toInt)
  }
  val grouped: Map[String, Int] = r.groupBy(t => t._1).map(t => (t._1, t._2.map(_._2).sum))
  val max = grouped.maxBy(_._2)._2
  val maxg = grouped.filter(t => t._2 == max)
  if (maxg.size > 1) {
    val names = maxg.keySet
    val a = r.foldLeft(names.map(t => t -> 0).toMap) {
      case(acc, el) if acc.values.max >= max => acc
      case(acc, el) => acc + (el._1 -> (acc.getOrElse(el._1, 0) + el._2))
    }.maxBy(_._2)
    println(a._1)
  } else
    println(maxg.head._1)
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CBR2A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val mp = collection.mutable.HashMap.empty[String, Int]
    val n = ni()

    val names = Array.ofDim[String](n)
    val score = Array.ofDim[Int](n)

    var res = -1001

    REP(n) { i =>
      val nm = ns()
      val v = ni()

      names(i) = nm
      score(i) = v

      if(mp.contains(nm)) {
        mp(nm) = mp(nm) + v
      } else {
        mp(nm) = v
      }
      if(res < mp(nm)) {
        res = mp(nm)
      }
    }

    mp.clear()
    var name: String = "-1"
    REP(n) { i =>
      if(mp.contains(names(i))) {
        mp(names(i)) += score(i)
      } else mp(names(i)) = score(i)
      if(mp(names(i)) >= res && name == "-1") {
        name = names(i)
      }
    }
    out.println(name)
  }
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CBR2A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val mp = collection.mutable.HashMap.empty[String, Int]
    val n = ni()

    var res = -1001
    var name: String = "rm"

    REP(n) { _ =>
      val nm = ns()
      val v = ni()

      if(mp.contains(nm)) {
        mp(nm) = mp(nm) + v
      } else {
        mp(nm) = v
      }
      if(res < mp(nm)) {
        res = mp(nm)
        name = nm
      }
    }
    out.println(name)
  }
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CBR2A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val mp = collection.mutable.HashMap.empty[String, Int]
    val n = ni()

    val names = Array.ofDim[String](n)
    val score = Array.ofDim[Int](n)

    var res = -1001

    REP(n) { i =>
      val nm = ns()
      val v = ni()

      names(i) = nm
      score(i) = v

      if(mp.contains(nm)) {
        mp(nm) = mp(nm) + v
      } else {
        mp(nm) = v
      }
      if(res < mp(nm)) {
        res = mp(nm)
      }
    }

    var name: String = "-1"
    val mp1 = collection.mutable.HashMap.empty[String, Int]
    REP(n) { i =>
      if(mp1.contains(names(i))) {
        mp1(names(i)) += score(i)
      } else mp1(names(i)) = score(i)
      if(mp1(names(i)) >= res && mp(names(i)) == res && name == "-1") {
        name = names(i)
      }
    }
    out.println(name)
  }
}

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CBR2A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class CBR2A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val mp = collection.mutable.HashMap.empty[String, Int]
    val n = ni()

    val names = Array.ofDim[String](n)
    val score = Array.ofDim[Int](n)

    var res = -1001

    REP(n) { i =>
      val nm = ns()
      val v = ni()

      names(i) = nm
      score(i) = v

      if(mp.contains(nm)) {
        mp(nm) = mp(nm) + v
      } else {
        mp(nm) = v
      }
      if(res < mp(nm)) {
        res = mp(nm)
      }
    }

    mp.clear()
    var name: String = "-1"
    REP(n) { i =>
      if(mp.contains(names(i))) {
        mp(names(i)) += score(i)
      } else mp(names(i)) = score(i)
      if(mp(names(i)) == res && name == "-1") {
        name = names(i)
      }
    }
    out.println(name)
  }
}

import java.util.Scanner

object Winner extends App {

  var playerScores = Map.empty[String, (Int, Int, Int)]

  val scanner = new Scanner(System.in)
  val size = scanner.nextInt()

  (0 until size).map(it => (scanner.next(), scanner.nextInt()))
  .zipWithIndex.foreach {
    record =>
      playerScores.get(record._1._1) match {
        case None => playerScores += (record._1._1 -> (record._1._2, record._1._2, record._2))
        case Some(v) => updateScore(record._1, record._2, v)
      }
  }

  def updateScore(record: (String, Int), order: Int, prevScore: (Int, Int, Int)): Unit = {
    val curScore = prevScore._1 + record._2
    if (curScore > prevScore._2) {
      playerScores += (record._1 ->(curScore, curScore, order))
    } else {
      playerScores += (record._1 ->(curScore, prevScore._2, prevScore._3))
    }
  }

  val result = playerScores.toList
    .sortBy(-_._2._3)
    .sortBy(_._2._2)
    .sortBy(_._2._1).last

  println(result._1)

}

import java.util.Scanner

object Winner extends App {

  var playerScores = Map.empty[String, (Int, Int, Int)]

  val scanner = new Scanner(System.in)
  val size = scanner.nextInt()

  (0 until size).map(it => (scanner.next(), scanner.nextInt()))
  .zipWithIndex.foreach {
    record =>
      playerScores.get(record._1._1) match {
        case None => playerScores += (record._1._1 -> (record._1._2, record._1._2, record._2))
        case Some(v) => updateScore(record._1, record._2, v)
      }
  }

  def updateScore(record: (String, Int), order: Int, prevScore: (Int, Int, Int)): Unit = {
    val curScore = prevScore._1 + record._2
    if (curScore > prevScore._2) {
      playerScores += (record._1 ->(curScore, curScore, order))
    } else {
      playerScores += (record._1 ->(curScore, prevScore._2, prevScore._3))
    }
  }

  val result = playerScores.toList
    .sortBy(-_._2._3)
    .sortBy(_._2._2)
    .sortBy(_._2._1).last

  println(result)

}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

  if (n == 850){
    val l = (for (d <- inData; if d contains "vikdriyzvgnpitwkkcu") yield d).toList
    val l1 = (for (d <- inData; if d contains "cpygmrkcsbrrnksp") yield d).toList
    println(l)
    println(l1)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      val score = acc.get(cur._1).get + cur._2
      if (score >= winnerScore) cur._1
      else iter(acc.updated(cur._1, score), d.tail)
    }
    iter(map, data)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(res.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

if (n == 850) println(res)

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }
  if (n == 850) println(res.get("cpygmrkcsbrrnksp"))
  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score == winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }
println(winners)
  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }
  if (n == 850) println(winners)
  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = if (cur._2 < 0) acc.get(cur._1).get else acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }
//  if (n == 850) println(res.get("cpygmrkcsbrrnksp"))
  if (n == 850) {
    val l = (for (d <- data; if d._1 == "cpygmrkcsbrrnksp") yield d._2).toList
    println(l.sum)
    println(l)
  }
  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = if (acc.get(cur._1).get < 0) cur._2 else acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val input = (for (i <- 1 until n) yield scanner.nextLine().split(" ") match {case Array(name, score) => (name, score.toInt)}).toList

  val result = input.groupBy(_._1).mapValues(_.map(_._2).sum)
  val maxScore = result.maxBy(_._2)._2
  val winners = result.filter(_._2 == maxScore).keys

  def replay: String = {
    @tailrec
    def turn(acc: Map[String, Int], data: List[(String, Int)]): String = {
      val current = data.head
      if (acc.get(current._1).isEmpty) turn(acc, data.tail)
      else {
        val score = acc.get(current._1).get + current._2
        if (score >= maxScore) current._1
        else turn(acc.updated(current._1, score), data.tail)
      }
    }
    turn(winners.map((_, 0)).toMap, input)
  }

  if (winners.size == 1) println(winners.head)
  else println(replay)
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2)).mapValues(_.sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }
  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }
//  if (n == 850) println(res.get("cpygmrkcsbrrnksp"))
  if (n == 850) {
//    val l = (for (d <- data; if d._1 == "cpygmrkcsbrrnksp") yield d._2).toList
//    println(l.sum)
//    println(l)
    println(data)
  }
  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
//  val l = List(747, 723, 450, -191, 696, -393, -853, 113, -536, -724, -887, 22, 317, -194, 839, -53, -844, 729, -419, -110, 661, -149, 408)
//  println (l sum)
//  println (l.foldLeft(0)(_+_))
}

import java.util.Scanner
import scala.annotation.tailrec

object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  def replay(map: Map[String, Int]) = {
    @tailrec
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

  if (n == 850){
    val l = (for (d <- data; if d._1 == "vikdriyzvgnpitwkkcu") yield d._2).toList
    val l1 = (for (d <- data; if d._1 == "cpygmrkcsbrrnksp") yield d._2).toList
    println(l)
    println(l1)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
object Winner extends App {
  val scanner = new Scanner(System.in)
  val n = scanner.nextLine().toInt
  val inData = (for (i <- 1 until n) yield scanner.nextLine).toList
  val data = inData.map(d => (d.substring(0, d.indexOf(" ")), d.substring(d.indexOf(" ")+1).toInt))
  val res = data.groupBy(_._1).mapValues(_.map(_._2).sum)
  val winnerScore = res.maxBy(_._2)._2
  val winners = res.filter(_._2 == winnerScore)

  println (winners)

  def replay(map: Map[String, Int]) = {
    def iter(acc: Map[String, Int], d: List[(String, Int)]): String = {
      val cur = d.head
      if (acc.get(cur._1).isEmpty) iter(acc, d.tail)
      else {
        val score = acc.get(cur._1).get + cur._2
        if (score >= winnerScore) cur._1
        else iter(acc.updated(cur._1, score), d.tail)
      }
    }
    iter(map, data)
  }

  if (winners.size == 1) println (winners.keys.head)
  else println(replay(winners.keys.map(_ -> 0).toMap))
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random

object P002A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N = sc.nextInt
  sc.nextLine

  type Round = (String, Int)
  type Score = Round

  def readRound(): Round = {
    val elms = sc.nextLine.split(" ")
    (elms(0), elms(1).toInt)
  }

  val rounds: List[Round] = List.fill(N)(readRound)

  def solve(): String = {
    val highScore: Int = rounds.groupBy(_._1).toSeq.map(_._2.map(_._2).sum).max
    val scoreBoard = mutable.Map.empty[String, Int]
    val history = new ListBuffer[Score]
    rounds.foreach { r =>
      val (name, point): Round = r
      val update = (name -> (scoreBoard.getOrElse(name, 0) + point))
      scoreBoard += update
      history += update
    }
    history.toList.dropWhile(_._2 < highScore).head._1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random

object P002A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N = sc.nextInt
  sc.nextLine

  type Round = (String, Int)
  type Score = Round

  def readRound(): Round = {
    val elms = sc.nextLine.split(" ")
    (elms(0), elms(1).toInt)
  }

  val rounds: List[Round] = List.fill(N)(readRound)

  def solve(): String = {
    val highScore = rounds.groupBy(_._1).toSeq.map(_._2.map(_._2).sum).max
    val scoreBoard = mutable.Map.empty[String, Int]
    val history = new ListBuffer[Score]
    rounds.foreach { r =>
      val (name, point): Round = r
      val update = (name -> (scoreBoard.getOrElse(name, 0) + point))
      scoreBoard += update
      history += update
    }
    history.dropWhile(_._2 < highScore).head._1
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.util.Random

object P002A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  val N = sc.nextInt
  sc.nextLine

  type Round = (String, Int)
  type Score = Round

  def readRound(): Round = {
    val elms = sc.nextLine.split(" ")
    (elms(0), elms(1).toInt)
  }

  val rounds: List[Round] = List.fill(N)(readRound)

  def solve(): String = {
    val highScore = rounds.groupBy(_._1).toSeq.map(_._2.map(_._2).sum).max
    val scoreBoard = mutable.Map.empty[String, Int]
    val history = new ListBuffer[Score]
    rounds.foreach { r =>
      val (name, point): Round = r
      val update = (name -> (scoreBoard.getOrElse(name, 0) + point))
      scoreBoard += update
      history += update
    }
    history.dropWhile(_._2 != highScore).head._1
  }

  out.println(solve)
  out.close
}

object Winner {

  def toGame(items : Array[String]) ={
    (items(0),items(1).toInt)
  }

  def main(args: Array[String]) = {
    val n = readLine().toInt;
    val games = (1 to n).map(_=>readLine()).map(s=>toGame(s.split(" "))).toList;
    val max = games.map(_._2).max;
    val winners = games.filter(_._2==max).map(_._1).toSet;
    print(games.find(game=>game._2>=max && winners.contains(game._1)).get._1);
  }
}

import scala.io.StdIn
import scala.annotation.tailrec

case class RoundEvent(winner: String, score: Int)

object X extends App {
  val rounds = StdIn.readInt()

  val res = (0 until rounds)
    .map(_ =>
      StdIn.readLine().split(" ") match {
        case Array(s1, s2) => RoundEvent(s1, s2.toInt)
      }
    )

  val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {
    accMap + (result.winner -> (accMap
      .getOrElse(result.winner, 0) + result.score))
  })

  val topEndScore = endScores.map(_._2).max

  val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)

  if (rounds == 50) {
    println(achievers)
  }
  @tailrec
  def findFirstWinner(
      rounds: Seq[RoundEvent],
      currScores: Map[String, Int] = Map()
  ): String = {
    val fst = rounds.head
    val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score
    val updatedScores = currScores + (fst.winner -> nextScore)
    if (nextScore >= topEndScore) fst.winner
    else findFirstWinner(rounds.tail, updatedScores)
  }

  val firstWinner = findFirstWinner(res)

  println(firstWinner)
}

import scala.io.StdIn
import scala.annotation.tailrec

case class RoundEvent(winner: String, score: Int)

object X extends App {
  val rounds = StdIn.readInt()

  val res = (0 until rounds)
    .map(_ => {
      val winner = StdIn.readLine().split(" ") match {
        case Array(s1, s2) => RoundEvent(s1, s2.toInt)
      }
      winner
    })
    .toList

  val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {
    accMap + (result.winner -> (accMap
      .getOrElse(result.winner, 0) + result.score))
  })

  val topEndScore = endScores.map(_._2).max

  val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)

  @tailrec
  def findFirstWinner(
      rounds: List[RoundEvent],
      currScores: Map[String, Int] = Map()
  ): String = {
    val fst = rounds.head
    val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score
    val updatedScores = currScores + (fst.winner -> nextScore)
    if (nextScore >= topEndScore) fst.winner
    else findFirstWinner(rounds.tail, updatedScores)
  }

  val firstWinner = findFirstWinner(res)

  println(firstWinner)
}

import scala.io.StdIn
import scala.annotation.tailrec

case class RoundEvent(winner: String, score: Int)

object X extends App {
  val rounds = StdIn.readInt()

  val res = (0 until rounds)
    .map(_ =>
      StdIn.readLine().split(" ") match {
        case Array(s1, s2) => RoundEvent(s1, s2.toInt)
      }
    )

  val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {
    accMap + (result.winner -> (accMap
      .getOrElse(result.winner, 0) + result.score))
  })

  val topEndScore = endScores.map(_._2).max

  val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)

  if (rounds == 50) {
    println(res)
  }
  @tailrec
  def findFirstWinner(
      rounds: Seq[RoundEvent],
      currScores: Map[String, Int] = Map()
  ): String = {
    val fst = rounds.head
    val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score
    val updatedScores = currScores + (fst.winner -> nextScore)
    if (nextScore >= topEndScore) fst.winner
    else findFirstWinner(rounds.tail, updatedScores)
  }

  val firstWinner = findFirstWinner(res)

  println(firstWinner)
}

import scala.io.StdIn
import scala.annotation.tailrec

case class RoundEvent(winner: String, score: Int)

object X extends App {
  val rounds = StdIn.readInt()

  val res = (0 until rounds)
    .map(_ => {
      val winner = StdIn.readLine().split(" ") match {
        case Array(s1, s2) => RoundEvent(s1, s2.toInt)
      }
      winner
    })
    .toList

  val endScores = res.foldLeft(Map[String, Int]())((accMap, result) => {
    accMap + (result.winner -> (accMap
      .getOrElse(result.winner, 0) + result.score))
  })

  val topEndScore = endScores.map(_._2).max

  val achievers = endScores.filter { case (_, s) => s == topEndScore }.map(_._1)

  @tailrec
  def findFirstWinner(
      rounds: List[RoundEvent],
      currScores: Map[String, Int] = Map()
  ): String = {
    val fst = rounds.head
    val nextScore = currScores.getOrElse(fst.winner, 0) + fst.score
    val updatedScores = currScores + (fst.winner -> nextScore)
    if (nextScore == topEndScore) fst.winner
    else findFirstWinner(rounds.tail, updatedScores)
  }

  val firstWinner = findFirstWinner(res)

  println(firstWinner)
}

object Main extends App{

  def scan(index:Int, map:Map[String, Int], list:List[(String, Int)]):(List[(String, Int)],Map[String, Int])  = {
    if(index > 0){
      val values = Console.readLine().trim().split(" ")
      val name = values(0)
      val value =  values(1).toInt
      if(value < -1000 || value > 1000) throw new Exception("Illegal value")
      val res:Map[String, Int] = if(!map.isEmpty && map.contains(name)){
        Map(name -> (value + map(name))) ++ (map - name)
      }
      else {
        map ++ Map(name -> value)
      }
      scan(index-1, res, list ++ List((name, res(name))))
    }
    else {
      (list, map)
    }
  }

  var results:Map[String,Int] = Map()

  val numOfRounds = Console.readInt
  if(numOfRounds <= 0) {
    throw new Exception("Illegal value")
  }

  val (list, map) = scan(numOfRounds, results, List())

  val max = map.values.toArray.max
   println(list.find( (tuple) => tuple._2 >= max).get._1)
}

object Main extends App{

  def scan(index:Int, map:Map[String, Int], list:List[(String, Int)]):(List[(String, Int)],Map[String, Int])  = {
    if(index > 0){
      val values = Console.readLine().trim().split(" ")
      val name = values(0)
      val value =  values(1).toInt
      if(value < -1000 || value > 1000) throw new Exception("Illegal value")
      val res:Map[String, Int] = if(!map.isEmpty && map.contains(name)){
        Map(name -> (value + map(name))) ++ (map - name)
      }
      else {
        map ++ Map(name -> value)
      }
      scan(index-1, res, list ++ List((name, res(name))))
    }
    else {
      (list, map)
    }
  }

  var results:Map[String,Int] = Map()

  val numOfRounds = Console.readInt
  if(numOfRounds <= 0) {
    throw new Exception("Illegal value")
  }

  val (list, map) = scan(numOfRounds, results, List())

  val max = map.values.toArray.max

   println(list.find( (tuple) => tuple._2 == max).get._1)
}

import collection.mutable._

object Main {
  val scanner = new java.util.Scanner(System.in)
  val totals  = new HashMap[String, Int]() { override def default(key:String) = 0 }

  def solve(rounds: Int, player: String, count: Int): List[(String, Int)] = {
    totals(player) += count
    rounds match {
      case 0 => (player, totals(player)) :: Nil
      case _ => (player, totals(player)) :: solve(rounds - 1, scanner.next, scanner.nextInt)
    }
  }

  def main(args: Array[String]): Unit = {
    val game = solve(scanner.nextInt - 1, scanner.next, scanner.nextInt)
    val max  = totals.values.max
    println(game.filter(_._2 >= max)(0)._1)
  }
}

import collection.mutable._

object Main {
  val scanner = new java.util.Scanner(System.in)
  val totals  = new HashMap[String, Int]() { override def default(key:String) = 0 }

  def solve(rounds: Int, player: String, count: Int): List[(String, Int)] = {
    totals(player) += count
    rounds match {
      case 0 => (player, totals(player)) :: Nil
      case _ => (player, totals(player)) :: solve(rounds - 1, scanner.next, scanner.nextInt)
    }
  }

  def main(args: Array[String]): Unit = {
    val game = solve(scanner.nextInt - 1, scanner.next, scanner.nextInt)
    val max  = totals.values.max
    print(max)
    println(game.filter(_._2 >= max)(0)._1)
  }
}

import collection.mutable._

object Main extends App {

  val scanner = new java.util.Scanner(System.in)
  val rounds = scanner.nextInt
  val map: Map[String, Int] = new HashMap[String, Int]() { override def default(key: String) = 0 }
  var winner: String = null
  var max = 0

  while (scanner.hasNext) {
    val person = scanner.next
    map(person) += scanner.nextInt

    if (map(person) > max) {
        max = map(person)
        winner = person
    }
  }

  println(winner)
}

import collection.mutable._

object Main2 {

  def input(rounds: Int, list: List[(String, Int)]): List[(String, Int)] = rounds match {
    case 0 => list
    case _ => input(rounds - 1, list :+ (scanner.next, scanner.nextInt))
  }

  val scanner = new java.util.Scanner(System.in)
  val list = input(scanner.nextInt, List())
  val candidates = list.groupBy(_._1).flatMap(e => Some(e._1, e._2.map(_._2).sum))
  val max     = candidates.values.max
  val winners = candidates.filter(_._2 == max)
  val steps   = list.filter(e => winners.contains(e._1))
  val scores  = new HashMap[String, Int]() { override def default(key:String) = 0 }
  val winner  = steps.find(e => { scores(e._1) += e._2; scores(e._1) == max } ).get

  def main(args: Array[String]) {
    println(winner._1)
  }
}

import collection.mutable._

object Main {
  val scanner = new java.util.Scanner(System.in)
  val totals  = new HashMap[String, Int]() { override def default(key:String) = 0 }

  def solve(rounds: Int, player: String, count: Int): List[(String, Int)] = {
    totals(player) += count
    rounds match {
      case 0 => (player, totals(player)) :: Nil
      case _ => (player, totals(player)) :: solve(rounds - 1, scanner.next, scanner.nextInt)
    }
  }

  def main(args: Array[String]): Unit = {
    println(solve(scanner.nextInt - 1, scanner.next, scanner.nextInt).filter(_._2 >= totals.values.max)(0)._1)
  }
}

object P2A {
    def main(args : Array[String]) {
        val n = readLine.toInt
        val s = Array.fill(n) {
            val Array(s1, s2) = readLine split " "
            (s1, s2.toInt)
        }.zipWithIndex groupBy {
            case ((name, score), idx) => name
        }
        val maxTotal = s.map{_._2.map{_._1._2}.sum}.max
        val winner = s.minBy{
            _._2.scanLeft(0, 0){
                case ((idxS, scoreS), ((name, score), idx)) =>
                    (idx, scoreS + score)
            }.find{
                case (idx, scoreS) => scoreS >= maxTotal
            }.getOrElse(Int.MaxValue, 0)._1
        }._1
        println(winner)
    }
}