package main

import (
	"fmt"
)

type Round struct {
	name  string
	score int
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	var (
		name  string
		score int

		finalScore map[string]int = make(map[string]int)
		finalRound []Round        = make([]Round, 0, n)
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &name, &score)
		finalScore[name] += score
		finalRound = append(finalRound, Round{name, finalScore[name]})
	}

	var max int
	for _, score = range finalScore {
		if score > max {
			max = score
		}
	}

	for _, round := range finalRound {
		if (finalScore[round.name] == max) && (round.score >= max) {
			fmt.Println(round.name)
			break
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func I(i ...interface{}) error {
	_, err := fmt.Fscan(r, i...)
	return err
}

func O(o ...interface{}) {
	fmt.Fprint(w, o...)
}

var (
	r *bufio.Reader
	w *bufio.Writer
)

func init() {
	if f, err := os.Open("in.goC"); err == nil {
		r = bufio.NewReader(f)
	} else {
		r = bufio.NewReader(os.Stdin)
	}
	w = bufio.NewWriter(os.Stdout)
}

func main() {
	var n int
	for I(&n) == nil {
		solve(n)
	}
	w.Flush()
}

func solve(n int) {
	m := make(map[string]int)
	var oo []string
	var ooo []int
	for i := 0; i < n; i++ {
		var t string
		var tt int
		I(&t, &tt)
		m[t] = m[t] + tt
		oo = append(oo, t)
		ooo = append(ooo, m[t])
	}
	var winnerPoint int
	for _, i := range m {
		if i > winnerPoint {
			winnerPoint = i
		}
	}
	for i := range ooo {
		if m[oo[i]] == winnerPoint && ooo[i] >= winnerPoint {
			O(oo[i], "\n")
			return
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	finalScore := map[string]int{}
	score := map[string]int{}
	var n int
	s := bufio.NewScanner(os.Stdin)
	s.Scan()
	fmt.Sscanf(s.Text(), "%d", &n)
	in := make([]string, n)
	for i := 0; i < n; i++ {
		var name string
		var mark int
		s.Scan()
		fmt.Sscanf(s.Text(), "%s %d", &name, &mark)
		in[i] = s.Text()
		finalScore[name] = finalScore[name] + mark
	}
	max := -1000001

	for _, mark := range finalScore {
		if mark > max {
			max = mark
		}
	}

	for i := 0; i < n; i++ {
		var name string
		var mark int
		fmt.Sscanf(in[i], "%s %d", &name, &mark)
		in[i] = s.Text()
		score[name] = score[name] + mark
		if finalScore[name] == max && score[name] >= max {
			fmt.Printf("%s", name)
			return
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	var line string
	scanner := bufio.NewScanner(reader)
	scanner.Scan()
	var n int
	var count int
	fmt.Sscanf(scanner.Text(), "%d", &n)

	matchRounds := make(map[string]int)
	lines := make([]string, n)
	var winner string
	var max int
	var isFirst bool = true
	for scanner.Scan(){
		line = scanner.Text()
		if len(strings.TrimSpace(line)) == 0 {
			break
		}
		var name string
		var score int
		fmt.Sscanf(line, "%s %d", &name, &score)
		val, ok := matchRounds[name]
		if ok {
			matchRounds[name] = val + score
		}else {
			count++;
			matchRounds[name] = score
		}
		val = matchRounds[name]
		lines = append(lines, line)
	}
	for _, v := range matchRounds {
		if isFirst || max < v {
			max = v
			isFirst = false
		}
	}

	finalMatchRound := make(map[string]int, count+1)
	for i := 0; i < len(lines); i++ {
		line = lines[i]
		var name string
		var score int
		fmt.Sscanf(line, "%s %d", &name, &score)
		val, ok := finalMatchRound[name]
		if ok {
			finalMatchRound[name] = val + score
		}else {
			count++;
			finalMatchRound[name] = score
		}
		val = finalMatchRound[name]
		if (matchRounds[name] == max && finalMatchRound[name] >= max) {
			winner = name;
			break;
		}
	}

	fmt.Printf("%s", winner)

}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	reader := bufio.NewReader(os.Stdin)
	var line string
	scanner := bufio.NewScanner(reader)
	scanner.Scan()
	var n int
	var count int
	fmt.Sscanf(scanner.Text(), "%d", &n)

	matchRounds := make(map[string]int)
	lines := make([]string, n)
	var winner string
	var max int
	var isFirst bool = true
	for n > 0 {
		scanner.Scan()
		line = scanner.Text()
		var name string
		var score int
		fmt.Sscanf(line, "%s %d", &name, &score)
		matchRounds[name] = matchRounds[name] + score
		lines = append(lines, line)
		n--;
	}
	for _, v := range matchRounds {
		if isFirst || max < v {
			max = v
			isFirst = false
		}
	}

	finalMatchRound := make(map[string]int, count+1)
	for i := 0; i < len(lines); i++ {
		line = lines[i]
		var name string
		var score int
		fmt.Sscanf(line, "%s %d", &name, &score)
		if matchRounds[name] < max {
			continue
		}
		finalMatchRound[name] = finalMatchRound[name] + score
		if finalMatchRound[name] >= max {
			winner = name;
			break;
		}
	}

	fmt.Printf("%s", winner)

}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	n := readNum(reader)

	mem := make(map[string]int)

	records := make([]Pair, n)

	for i := 0; i < n; i++ {
		s, _ := reader.ReadBytes('\n')

		var j int
		for j < len(s) && s[j] != ' ' {
			j++
		}
		name := string(s[:j])
		var score int
		readInt(s, j + 1, &score)
		mem[name] += score
		records[i] = Pair{name, mem[name]}
	}
	var best int

	for _, score := range mem {
		best = max(best,score)
	}

	var winner string

	for i := 0; i < n; i++ {
		name := records[i].first
		if mem[name] == best && records[i].second >= best {
			winner = name
			break
		}
	}

	fmt.Println(winner)
}

func max(a, b int) int {
	if a >= b {
		return a
	}
	return b
}

type Pair struct {
	first string
	second int
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

package main
import (
	"fmt"
	//"sort"
	//"unicode/utf8"
)
func main() {
	var n int
	a:=make(map[string]int)
	b:=make(map[string]int)
	var c [1001]int
	var s [1001]string
	m:=0
	fmt.Scan(&n)
	for i:=0;i<n;i++ {
		fmt.Scan(&s[i],&c[i])
		a[s[i]]+=c[i]
	}
	for i:=0;i<n;i++ {
		if m<a[s[i]] {
			m=a[s[i]]
		}
	}
	counter:=0
	for j:=0;; {
		b[s[j]]+=c[j]
		if  a[s[j]]<m || b[s[j]]<m{
			j++
			counter++
		} else {
			break
		}

	}
	fmt.Println(s[counter])
}

package main

import "fmt"
import "log"

var high_per_player map[string]int

type rounddesc struct {
	name string;
	score int;
}

func main() {
	high_per_player = make(map[string]int)

	var n int
	nargs, err := fmt.Scan(&n);
	if err != nil {
		log.Fatal(err);
	}
	if nargs != 1 {
		log.Fatal("missing nargs", nargs);
	}

	game := make([]rounddesc, n);

	for round := 0; round < n; round++ {
		var name string;
		var score int;
		nargs, err = fmt.Scan(&name, &score);
		if err != nil {
			log.Fatal(err);
		}
		if nargs != 2 {
			log.Fatal("missing nargs", nargs);
		}

		game[round] = rounddesc{name, score}
		high_per_player[name] += score;
	}

	var first = true;
	var highlist []string;
	var high_score int;
	for k, v := range(high_per_player) {
		if first {
			high_score = v;
			highlist = make([]string, 1);
			highlist[0] = k;
			first = false;
			continue;
		}
		if v < high_score {
			continue;
		}

		if v > high_score {
			highlist = make([]string, 1);
			highlist[0] = k;
			high_score = v;
			continue;
		}
		highlist = append(highlist, k);
	}

	if len(highlist) == 1 {
		// Simple case, yea!
		fmt.Println(highlist[0]);
		return
	}

	// Ok, now we need to go back through the game and figure out
	// which of the winners got there first

	high_per_player = make(map[string]int)
	for _, k := range(highlist) {
		high_per_player[k] = 0
	}

	for _, round := range(game) {
		_, present := high_per_player[round.name];
		if !present {
			// Not one of the contenders, skip
			continue;
		}

		high_per_player[round.name] += round.score;
		if high_per_player[round.name] >= high_score {
			// First one to >= high_score wins!
			fmt.Println(round.name);
			return
		}
	}
}

package main

import (
  "os"
  "bufio"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

type Round struct {
  Player string
  Score int
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  rounds := make([]Round, n)
  finalScores := map[string]int{}
  for i := 0; i < n; i++ {
    player, score := getS(), getI()
    rounds[i] = Round{ player, score }
    finalScores[player] += score
  }
  topScore := 0
  for _, score := range finalScores {
    if score > topScore {
      topScore = score
    }
  }
  scores := map[string]int{}
  for i := 0; i < n; i++ {
    round := rounds[i]
    player, score := round.Player, round.Score
    if finalScores[player] != topScore {
      continue
    }
    scores[player] += score
    if scores[player] >= topScore {
      writer.WriteString(fmt.Sprintf("%s\n", player))
      return
    }
  }
}

package main

import "fmt"

type Round struct {
    name string
    score int
}

func main() {
    var n,a int
    var s string
    score := make(map[string]int)
    fmt.Scan(&n)
    r := make([]Round,0,n)
    for i := 0; i < n; i++ {
        fmt.Scan(&s,&a)
        score[s] += a
        r = append(r,Round{s,score[s]})
    }
    max := -1001
    for _, v := range score {
        if max < v { max = v }
    }
    for _, v := range r {
        if (score[v.name] == max) && (v.score >= max) {
            fmt.Println(v.name)
            break
        }
    }
}

package main

/*

ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Победитель популярной в Берляндии карточной игры «Берлоггинг» определяется
по следующим правилам. Если на момент окончания игры существует только
один игрок, набравший максимальное количество очков, то он и становится победителем.

Ситуация осложняется, если таких игроков несколько. Каждый кон игры
некоторый игрок выигрывает или проигрывает некоторое количество очков.
В записи о ходе игры это обозначается строкой «name score», где name это
имя игрока, а score целое число обозначающее количество заработанных очков
данным игроком. Если score — отрицательное число, это обозначает,
что игрок проиграл в этом коне. Так вот, если на конец игры несколько
игроков набрали максимум очков (пусть это число равно m), то выигрывает
тот из них, кто первым набрал как минимум m очков. Перед началом игры
у каждого игрока 0 очков. Гарантируется, что на момент окончания игры
хотя бы у одного игрока положительное число очков.

Входные данные
	В первой строке записано целое число n (1 ≤ n ≤ 1000), n — количество конов сыгранной игры.
	Далее в n строках идут описания конов, в формате «name score» в хронологическом порядке,
	где name это строка из строчных букв латинского алфавита длины от 1 до 32,
	а score это целое число от -1000 до 1000 включительно.

Выходные данные
	Выведите имя победителя игры «Берлоггинг».

*/

import "fmt"

type Round struct {
	score int
	name  string
}

func solve(ch <-chan Round) string {
	rounds := []Round{}
	scores := map[string]int{}
	for r := range ch {
		scores[r.name] += r.score
		rounds = append(rounds, r)
	}

	max := -1001
	for _, score := range scores {
		if score > max {
			max = score
		}
	}

	scores2 := map[string]int{}
	for _, r := range rounds {
		scores2[r.name] += r.score

		if scores2[r.name] >= max && scores[r.name] == max {
			return r.name
		}
	}

	return "" // to make compiler happy
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	ch := make(chan Round)
	go func() {
		for i := 0; i < n; i++ {
			r := Round{}
			fmt.Scanf("%s %d\n", &r.name, &r.score)
			ch <- r
		}
		close(ch)
	}()

	fmt.Printf("%s\n", solve(ch))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func getLine() string {
	s, _ := reader.ReadString('\n')
	if strings.HasSuffix(s, "\r\n") {
		s = s[:len(s)-2]
	} else if strings.HasSuffix(s, "\n") {
		s = s[:len(s)-1]
	}
	return s
}
func getLine2Int() (n int) {
	scanf("%d\n", &n)
	return
}
func getLine2Int2() (a, b int) {
	scanf("%d %d\n", &a, &b)
	return
}
func getLine2Ints(n int) []int {
	ans := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &ans[i])
	}
	scanf("%d\n", &ans[n-1])
	return ans
}

var debug = false

func see(a interface{}) {
	if debug {
		printf("DEBUG:%v\n", a)
	}
}

type cc struct {
	name  string
	score int
}

func main() {
	defer writer.Flush()

	n := getLine2Int()
	input := make([]cc, n)
	for i := 0; i < n; i++ {
		scanf("%s %d\n", &input[i].name, &input[i].score)
	}
	scoreCounter := make(map[string]int)
	for i := 0; i < n; i++ {
		scoreCounter[input[i].name] += input[i].score
	}
	maxScore := 0
	for _, finalScore := range scoreCounter {
		if finalScore > maxScore {
			maxScore = finalScore
		}
	}
	wins := make([]string, 0)
	for name, finalScore := range scoreCounter {
		if finalScore == maxScore {
			wins = append(wins, name)
		}
	}
	if len(wins) > 1 {
		scoreCounter := make(map[string]int)
		for i := 0; i < len(wins); i++ {
			scoreCounter[wins[i]] = 0
		}
		for i := 0; i < n; i++ {
			if _, ok := scoreCounter[input[i].name]; ok {
				scoreCounter[input[i].name] += input[i].score
				if scoreCounter[input[i].name] >= maxScore {
					printf("%s\n", input[i].name)
					return
				}
			}
		}
	}
	printf("%s\n", wins[0])
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

type History struct {
	Player string
	Score  int
}

func main() {
	var round int

	scanner := bufio.NewScanner(os.Stdin)

	if scanner.Scan() {
		line := scanner.Text()
		fmt.Sscanf(line, "%d", &round)
	}

	currentScoreMap := make(map[string]int)
	history := make([]History, round)

	for i := 0; i < round && scanner.Scan(); i++ {
		line := scanner.Text()
		var name string
		var score int

		fmt.Sscanf(line, "%s %d", &name, &score)

		currentScoreMap[name] += score

		history[i] = History{name, score}
	}

	topScore := 0
	topPlayers := make(map[string]int)
	for p, s := range currentScoreMap {
		if topScore <= s {
			topScore = s
			topPlayers[p] = s
		}
	}

	for _, event := range history {
		name, score := event.Player, event.Score
		_, isTopPlayer := topPlayers[name]
		if isTopPlayer {
			topPlayers[name] -= score
			if topPlayers[name] <= 0 {
				fmt.Println(name)
				return
			}
		}
	}
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"bufio"
	"fmt"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &n)
	total := make(map[string]int)
	histn := make([]string, n)
	hists := make([]int, n)
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanln(input, &name, &score)
		histn[i] = name
		hists[i] = score
		total[name] += score
	}
	max := 0
	wins := make(map[string]bool)
	for name, scores := range total {
		if scores >= max {
			if scores > max {
				max = scores
				wins = make(map[string]bool)
			}
			wins[name] = true
		}
	}

	result := make(map[string]int)
	for i := 0; i < len(histn); i++ {
		name := histn[i]
		if wins[name] {
			result[name] += hists[i]
			if result[name] >= max {
				fmt.Println(name)
				return
			}
		}
	}
}

package main

import (
	"fmt"
)

type pair struct {
	value int64
	cnt   int64
}

type input struct {
	key   string
	value int64
}

func (p *pair) String() string {
	return fmt.Sprintln("value n", p.value, p.cnt)
}

func less(a, b *pair) bool {
	return a.value < b.value || a.value == b.value && a.cnt > b.cnt
}

func main() {
	var n int64
	var key string
	var value int64
	r := make(map[string]int64)
	fmt.Scanf("%d\n", &n)
	data := make([]*input, 0, n)
	for i := n; i > 0; i-- {
		fmt.Scanf("%s %d\n", &key, &value)
		v := &input{key: key, value: value}
		data = append(data, v)
		r[key] += value
	}
	var max int64
	for _, v := range r {
		if v > max {
			max = v
		}
	}

	d := make(map[string]*pair)
	for i, v := range data {
		key := v.key
		value := v.value
		if _, ok := d[key]; ok {
			d[key].value += value
		} else {
			d[key] = &pair{value: value}
		}
		if d[key].value >= max && d[key].cnt == 0 {
			d[key].cnt = int64(i + 1)
		}
	}

	var choose string
	mmax := &pair{}
	for key, v := range d {
		if less(mmax, v) {
			mmax.value = v.value
			mmax.cnt = v.cnt
			choose = key
		}
	}
	// fmt.Println(r)
	fmt.Println(choose)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var rounds []map[string]int16
	for i := 0; i < n; i++ {
		var name string
		var score int16
		fmt.Scan(&name, &score)
		m := make(map[string]int16)
		if i != 0 {
			for k, v := range rounds[i-1] {
				m[k] = v
			}
		}
		m[name] = m[name] + score
		rounds = append(rounds, m)
	}
	var max int16
	for _, v := range rounds[n-1] {
		if v > max {
			max = v
		}
	}
	var ns []string
	for k, v := range rounds[n-1] {
		if v == max {
			ns = append(ns, k)
		}
	}
	for _, r := range rounds {
		for k, v := range r {
			if v >= max && contains(ns, k) {
				fmt.Print(k)
				return
			}
		}
	}
}

func contains(ns []string, k string) bool {
	for _, n := range ns {
		if n == k {
			return true
		}
	}
	return false
}

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"regexp"
	"strconv"
	"strings"
)

type Entry struct {
	name  string
	score int
}

func main() {
	var n int
	if _, err := fmt.Scanf("%d\n", &n); err != nil {
		return
	}

	history := make([]Entry, n)
	scoreboard := make(map[string]int)

	reader := bufio.NewReader(os.Stdin)
	re := regexp.MustCompile(`\r?\n`)
	for i := 0; i < n; i++ {
		if s, err := reader.ReadString('\n'); err != nil {
			if err == io.EOF {
				break
			} else {
				return
			}
		} else {
			s = re.ReplaceAllString(s, "")

			ss := strings.Split(s, " ")
			name := ss[0]
			score, err := strconv.Atoi(ss[1])
			if err != nil {
				return
			}

			history = append(history, Entry{name, score})
			scoreboard[name] = scoreboard[name] + score
		}
	}

	max := 0
	for _, score := range scoreboard {
		if score > max {
			max = score
		}
	}
	winners := make(map[string]int)
	for name, score := range scoreboard {
		if score == max {
			winners[name] = score
		}
	}

	scoreboard = make(map[string]int)
	for _, entry := range history {
		if winners[entry.name] > 0 {
			scoreboard[entry.name] = scoreboard[entry.name] + entry.score
			if scoreboard[entry.name] >= max {
				fmt.Println(entry.name)
				break
			}
		}
	}
}

package main

import "fmt"

type NameScore struct {
	name  string
	score int
}

func main() {
	var times int
	fmt.Scanln(&times)

	nameScoreMap := make(map[string]int)
	records := make([]NameScore, 1005)
	for i := 0; i < times; i++ {
		var name string
		var score int
		fmt.Scanln(&name, &score)
		records[i] = NameScore{name: name, score: score}
		nameScoreMap[name] += score
	}

	maxScore := -1001
	for _, v := range nameScoreMap {
		if v > maxScore {
			maxScore = v
		}
	}
	tmpNameScoreMap := make(map[string]int, len(nameScoreMap))
	for i := 0; i < times; i++ {
		tmpNameScoreMap[records[i].name] += records[i].score
		if nameScoreMap[records[i].name] == maxScore && tmpNameScoreMap[records[i].name] >= maxScore {
			fmt.Println(records[i].name)
			break
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n int
	a:=make(map[string]int)
	b:=make(map[string]int)
	var c [1001]int
	var s [1001]string
	m:=0
	fmt.Scan(&n)
	for i:=0;i<n;i++ {
		fmt.Scan(&s[i],&c[i])
		a[s[i]]+=c[i]
	}
	for i:=0;i<n;i++ {
		if m<a[s[i]] {
			m=a[s[i]]
		}
	}
	counter:=0
	for j:=0;; {
		b[s[j]]+=c[j]
		if  a[s[j]]<m || b[s[j]]<m{
			j++
			counter++
		} else {
			break
		}

	}
	fmt.Println(s[counter])
}

/*
func main() {
	var n int
	fmt.Scanf("%d", &n)
	scoreMap := make(map[string]int)
	var nameSet []string

	for ; n > 0; n-- {
		var name string
		var score int
		fmt.Scanf("%s %d", &name, &score)
		scoreMap[name] += score
		nameSet = append(nameSet, name)
	}

	nameMap := make(map[string]int)
	var nameSetDistinct []string

	for i := len(nameSet) - 1 ; i >= 0; i-- {
		if nameMap[nameSet[i]] == 0 {
			nameSetDistinct = append(nameSetDistinct, nameSet[i])
			nameMap[nameSet[i]] = 1
		}
	}

	resultNum := len(nameSetDistinct) - 1

	for i := resultNum - 2 ; i >= 0; i-- {
		if scoreMap[nameSetDistinct[i]] > scoreMap[nameSetDistinct[resultNum]] {
			resultNum = i
		}
	}

	fmt.Println(nameSetDistinct[resultNum])
}*/

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		scoreRecord = append(scoreRecord, scoreTable[token[0]])
		winnerRecord = append(winnerRecord, token[0])
	}

	l := len(scoreRecord)
	var winner string
	scorerCnt := map[int]int{}
	winningScore := -1
	for name, score := range scoreTable {
		if score > winningScore {
			winner = name
			winningScore = score
		}
		scorerCnt[score] += 1
	}

	if scorerCnt[winningScore] > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore && scoreTable[winnerRecord[i]] == winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winner)
	}
}

// codeforces_002A_winner
package main

import (
	"fmt"
)

func main() {
	var (
		num       int
		name      string
		number    int
		m, n      map[string]int
		names     []string
		numbers   []int
		maxNumber int
		maxName   string
	)

	fmt.Scanln(&num)
	m = make(map[string]int)
	maxNumber = -1000 * 1001

	for i := 0; i < num; i++ {
		fmt.Scanln(&name, &number)
		m[name] += number
		names = append(names, name)
		numbers = append(numbers, number)
	}

	for name, _ = range m {
		//		fmt.Printf("%s\t%d\n", name, m[name])
		if m[name] > maxNumber {
			maxNumber = m[name]
		}
	}

	//	fmt.Println(names)

	n = make(map[string]int)
	for i := 0; i < num; i++ {
		n[names[i]] += numbers[i]
		if maxNumber <= n[names[i]] && maxNumber <= m[names[i]] {
			maxName = names[i]
			break
		}
	}
	fmt.Printf("%s\n", maxName)
}

package main

import (
	"fmt"
)

func main() {
	var roundCount int
	fmt.Scanln(&roundCount)
	rounds := make([]map[string]int, roundCount+1)
	roundNames := make([]string, roundCount + 1)
	for i := 1; i <= roundCount; i++ {
		rounds[i] = make(map[string]int)
		for k, v := range rounds[i-1] {
			rounds[i][k] = v
		}
		var name string
		var score int
		fmt.Scan(&name, &score)
		rounds[i][name] += score
		roundNames[i] = name
	}
	var winners []string
	var m int
	for k, v := range rounds[roundCount] {
		switch {
		case v > m:
			winners = []string{k}
			m = v
		case v == m:
			winners = append(winners, k)
		}
	}
	var winner string
	if len(winners) > 1 {
		FIND_WINNER:
		for i := 1; i <= roundCount; i++ {
			for wi := range winners {
				if roundNames[i] == winners[wi] &&rounds[i][roundNames[i]] >= m {
					winner = roundNames[i]
					break FIND_WINNER
				}
			}
		}
	} else {
		winner = winners[0]
	}
	fmt.Println(winner)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	if err := run(os.Args[1:]); err != nil {
		fmt.Println(err)
	}
}

type Round struct {
	player string
	score  int
}

var CRLFReplacer = strings.NewReplacer("\n", "", "\r", "")

func run(args []string) error {
	reader := bufio.NewReader(os.Stdin)

	text, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	text = CRLFReplacer.Replace(text)

	lines, err := strconv.Atoi(text)
	if err != nil {
		return err
	}

	scores := make(map[string]int)
	max := 0
	var rounds []*Round

	for i := 0; i < lines; i++ {
		text, err := reader.ReadString('\n')
		if err != nil {
			return err
		}
		text = CRLFReplacer.Replace(text)

		parts := strings.Split(text, " ")
		name := parts[0]
		score, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}

		rounds = append(rounds, &Round{name, score})
	}

	for _, r := range rounds {
		scores[r.player] = scores[r.player] + r.score
	}

	winners := make(map[string]struct{})

	for _, v := range scores {
		if v >= max {
			max = v
		}
	}

	for k, v := range scores {
		if v == max {
			winners[k] = struct{}{}
		}
	}

	scores = make(map[string]int)

	for _, r := range rounds {
		scores[r.player] = scores[r.player] + r.score
		if _, ok := winners[r.player]; scores[r.player] >= max && ok {
			fmt.Println(r.player)
			return nil
		}
	}

	return nil
}

// 2A-mic
package main

import (
    "fmt"
)

func main() {
    a := make(map[string]int)
    aa := make(map[string]int)
    var n, na int
    fmt.Scan(&n)
    name := make([]string, n)
    score := make([]int, n)
    for i := 0; i < n; i++ {
        fmt.Scan(&name[i], &score[i])
        a[name[i]] += score[i]
    }
    for i := 0; i < n; i++ {
        if a[name[i]] > na {
            na = a[name[i]]
        }
    }
    for i := 0; i < n; i++ {
        if a[name[i]] == na {
            aa[name[i]] += score[i]
            if aa[name[i]] >= na {
                fmt.Println(name[i])
                break
            }
        }
    }
}

package main

import (
	"fmt"
)

type T struct {
	I int
	V int
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	var name string
	var score int

	M := make(map[string][]T)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &name, &score)

		if M[name] != nil {
			l := len(M[name])
			score += M[name][l-1].V
		}
		M[name] = append(M[name], T{i, score})
	}

	m := 0
	var N []string
	for name, v := range M {
		score = v[len(v)-1].V
		if m < score {
			m = score
			N = []string{name}
		} else if m == score {
			N = append(N, name)
		}
	}

	if len(N) == 1 {
		name = N[0]
	} else {
		i := 0
		for _, v := range N {
			for _, t := range M[v] {
				if t.V >= m {
					if i == 0 || t.I < i {
						name = v
						i = t.I
					}
					break
				}
			}
		}
	}

	fmt.Println(name)
}

// cf2a project main.go
package main

import (
	"fmt"
)

type pos struct {
	name  string
	score int
}

func main() {
	var n int
	fmt.Scan(&n)
	var p []pos
	nm := make(map[string]int)

	for i := 0; i < n; i++ {
		var a string
		var b int
		fmt.Scan(&a, &b)
		p = append(p, pos{a, b})
		nm[a] += b
	}
	m := 0
	for _, b := range nm {
		if m < b {
			m = b
		}
	}
	var s string
	mm := make(map[string]int)
	for _, b := range p {
		mm[b.name] += b.score
		if mm[b.name] >= m && nm[b.name] == m {
			s = b.name
			break
		}
	}
	fmt.Println(s)
}

package main

import "fmt"

func main(){

  m := make(map[string]int,1000)
  ln := make([]string,1000)
  ls := make([]int,1000)
  var n string
  var s int
  var t int
  fmt.Scanln(&t)

    ms := int(-2000*1000) //max score

  for i:=0 ; i<t ; i++ {

    fmt.Scanln(&n,&s)

    ln[i] = n
    ls[i] = s

    m[n] += s
  }

  for _,v := range m {
    if v>ms { ms = v }
  }

  k := make(map[string]int,1000)

  for i:=0;i<t;i++ {

    n = ln[i]
    s = ls[i]

    k[n] += s

    if k[n] >= ms && m[n] == ms {
      fmt.Println(n)
      return;
    }

  }

}

// Author: sighduck
// URL: https://codeforces.com/problemset/problem/2/A

package main

import (
	"bufio"
	"fmt"
	"os"
)

type Round struct {
	Player string
	Score  int
}

func Solve(n int, rounds []Round) string {
	scores := make(map[string]int)
	for i := 0; i < n; i++ {
		round := rounds[i]
		scores[round.Player] += round.Score
	}
	maxScore := 0
	for _, finalScore := range scores {
		if finalScore > maxScore {
			maxScore = finalScore
		}
	}
	winners := make(map[string]bool)
	for player, finalScore := range scores {
		if finalScore == maxScore {
			winners[player] = true
		}
	}
	runningScores := make(map[string]int)
	for i := 0; i < n; i++ {
		round := rounds[i]
		runningScores[round.Player] += round.Score
		if winners[round.Player] == true && runningScores[round.Player] >= maxScore {
			return round.Player
		}
	}
	panic("No winning players found.")
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	rounds := make([]Round, n)

	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%s %d\n", &rounds[i].Player, &rounds[i].Score)
	}
	fmt.Fprintf(writer, "%s\n", Solve(n, rounds))
}

package main

import (
	"fmt"
)

type s1 struct {
	name  string
	score int
}

func main() {
	var n int
	fmt.Scanln(&n)

	scores := make(map[string]int)
	logs := make([]s1, n)
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Scanf("%s %d\n", &name, &score)
		scores[name] += score
		logs[i] = s1{name, scores[name]}
	}

	maxScore := 0
	for _, score := range scores {
		if score > maxScore {
			maxScore = score
		}
	}

	winners := make(map[string]bool)
	for name, score := range scores {
		if score == maxScore {
			winners[name] = true
		}
	}

	var winner string
	for _, log := range logs {
		if winners[log.name] && log.score >= maxScore {
			winner = log.name
			break
		}
	}

	fmt.Println(winner)
}

package main

import (
	"fmt"
)

type Log struct {
	player string
	max    int
}

func main() {
	var t int
	fmt.Scan(&t)

	mp := make(map[string]int)

	var max int
	var logg []*Log

	for z := 0; z < t; z++ {
		var s string
		var n int
		fmt.Scan(&s, &n)
		mp[s] += n

		if mp[s] > 0 {
			logg = append(logg, &Log{s, mp[s]})
		}
	}

	// Find max.
	for _, v := range mp {
		if v > max {
			max = v
		}
	}

	// Find top players.
	var top []string
	for k, v := range mp {
		if v == max {
			top = append(top, k)
		}
	}

	// Base case when top player is only one.
	if len(top) == 1 {
		fmt.Print(top[0])
		return
	}

	// Special case when there are few players that reached top.
	var first string
	least := len(logg)
	for _, v := range top {
		for i := len(logg) - 1; i >= 0; i-- {
			if logg[i].player == v && logg[i].max >= max {
				if i < least {
					least = i
					first = v
				}
			}
		}
	}

	fmt.Print(first)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	type node struct {
		name  string
		score int
	}

	var (
		nodeList   []node         = make([]node, n)
		finalScore map[string]int = make(map[string]int, n)
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &nodeList[i].name, &nodeList[i].score)

		if currentScore, ok := finalScore[nodeList[i].name]; ok {
			finalScore[nodeList[i].name] = currentScore + nodeList[i].score
		} else {
			finalScore[nodeList[i].name] = nodeList[i].score
		}
	}

	var maximum int
	for _, score := range finalScore {
		if score > maximum {
			maximum = score
		}
	}

	var scoreHash map[string]int = make(map[string]int)
	for _, item := range nodeList {
		var (
			currentScore int
			ok           bool
		)
		if currentScore, ok = finalScore[item.name]; !ok || currentScore != maximum {
			continue
		}
		if currentScore, ok = scoreHash[item.name]; !ok {
			currentScore = 0
		}
		currentScore += item.score
		scoreHash[item.name] = currentScore

		if currentScore >= maximum {
			fmt.Println(item.name)
			return
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	type node struct {
		name  string
		score int
	}

	var (
		nodeList  []node         = make([]node, n)
		scoreHash map[string]int = make(map[string]int, n)
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &nodeList[i].name, &nodeList[i].score)

		if currentScore, ok := scoreHash[nodeList[i].name]; ok {
			scoreHash[nodeList[i].name] = currentScore + nodeList[i].score
		} else {
			scoreHash[nodeList[i].name] = nodeList[i].score
		}
	}

	var (
		maximum           int
		parallelScoreHash map[string]bool = make(map[string]bool)
	)
	for name, score := range scoreHash {
		if score > maximum {
			maximum = score
			parallelScoreHash = make(map[string]bool)
		}
		if score == maximum {
			parallelScoreHash[name] = true
		}
	}

	scoreHash = make(map[string]int, n)
	for _, item := range nodeList {
		var ok bool
		if _, ok = parallelScoreHash[item.name]; !ok {
			continue
		}

		var currentScore int
		if currentScore, ok = scoreHash[item.name]; !ok {
			currentScore = 0
		}
		currentScore += item.score
		scoreHash[item.name] = currentScore

		if currentScore >= maximum {
			fmt.Println(item.name)
			return
		}
	}
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	type node struct {
		name  string
		score int
	}

	var (
		nodeList  []node         = make([]node, n)
		scoreHash map[string]int = make(map[string]int, n)
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &nodeList[i].name, &nodeList[i].score)

		if currentScore, ok := scoreHash[nodeList[i].name]; ok {
			scoreHash[nodeList[i].name] = currentScore + nodeList[i].score
		} else {
			scoreHash[nodeList[i].name] = nodeList[i].score
		}
	}

	var maximum int
	for _, score := range scoreHash {
		if score > maximum {
			maximum = score
		}
	}

	scoreHash = make(map[string]int, n)
	for _, item := range nodeList {
		var (
			currentScore int
			ok           bool
		)
		if currentScore, ok = scoreHash[item.name]; !ok {
			currentScore = 0
		}
		currentScore += item.score
		scoreHash[item.name] = currentScore

		if currentScore >= maximum {
			fmt.Println(item.name)
			return
		}
	}
}

package main

/*

ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Победитель популярной в Берляндии карточной игры «Берлоггинг» определяется
по следующим правилам. Если на момент окончания игры существует только
один игрок, набравший максимальное количество очков, то он и становится победителем.

Ситуация осложняется, если таких игроков несколько. Каждый кон игры
некоторый игрок выигрывает или проигрывает некоторое количество очков.
В записи о ходе игры это обозначается строкой «name score», где name это
имя игрока, а score целое число обозначающее количество заработанных очков
данным игроком. Если score — отрицательное число, это обозначает,
что игрок проиграл в этом коне. Так вот, если на конец игры несколько
игроков набрали максимум очков (пусть это число равно m), то выигрывает
тот из них, кто первым набрал как минимум m очков. Перед началом игры
у каждого игрока 0 очков. Гарантируется, что на момент окончания игры
хотя бы у одного игрока положительное число очков.

Входные данные
	В первой строке записано целое число n (1 ≤ n ≤ 1000), n — количество конов сыгранной игры.
	Далее в n строках идут описания конов, в формате «name score» в хронологическом порядке,
	где name это строка из строчных букв латинского алфавита длины от 1 до 32,
	а score это целое число от -1000 до 1000 включительно.

Выходные данные
	Выведите имя победителя игры «Берлоггинг».

*/

import "fmt"

type Round struct {
	score int
	name string
}

func solve(ch <-chan Round) string {
	players := map[string]int{}

	var maxScore int
	var maxName string
	for r := range ch {
		players[r.name] += r.score
		if players[r.name] > maxScore {
			maxName = r.name
			maxScore = players[r.name]
		}
	}
	return maxName
}

func main() {
	var n int
	fmt.Scanf("%d", &n)

	ch := make(chan Round)
	go func () {
		for i := 0; i < n; i++ {
			r := Round{}
			fmt.Scanf("%s %d", &r.name, &r.score)
			ch <- r
		}
		close(ch)
	}()

	fmt.Printf("%s\n", solve(ch))
}

package main

import (
  "os"
  "bufio"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

type Round struct {
  Player string
  Score int
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  rounds := make([]Round, n)
  topScore := 0
  scores := map[string]int{}
  for i := 0; i < n; i++ {
    player, score := getS(), getI()
    rounds[i] = Round{ player, score }
    scores[player] += score
    if scores[player] > topScore {
      topScore = scores[player]
    }
  }
  scores = map[string]int{}
  for i := 0; i < n; i++ {
    round := rounds[i]
    player, score := round.Player, round.Score
    scores[player] += score
    if scores[player] == topScore {
      writer.WriteString(fmt.Sprintf("%s\n", player))
      return
    }
  }
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	var round int

	scanner := bufio.NewScanner(os.Stdin)

	if scanner.Scan() {
		line := scanner.Text()
		fmt.Sscanf(line, "%d", &round)
	}

	currentScoreMap := make(map[string]int)
	topScoreMap := make(map[string][]int)
	order := make([]string, round)

	for i := 0; i < round && scanner.Scan(); i++ {
		line := scanner.Text()
		var name string
		var score int

		fmt.Sscanf(line, "%s %d", &name, &score)

		currentScoreMap[name] += score

		topScoreMap[name] = append(topScoreMap[name], score)
		order = append(order, name)
	}

	topScore := 0
	topPlayers := make(map[string]int)
	for p, s := range currentScoreMap {
		if topScore < s {
			topScore = s
			topPlayers[p] = s
		}
	}

	i := 0
	for {
		for _, name := range order {
			_, inOrder := topPlayers[name]
			if inOrder {
				topPlayers[name] -= topScoreMap[name][i]
				if topPlayers[name] < 0 {
					fmt.Println(name)
					return
				}
			}
		}
		i++
	}
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"bufio"
	"fmt"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &n)
	sum := make(map[string]int)
	histn := make([]string, 0)
	hists := make([]int, 0)
	wins := make(map[int]map[string]bool)
	max := 0
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanf(input, "%s %d\n", &name, &score)
		histn = append(histn, name)
		hists = append(hists, score)
		sum[name] += score
		if sum[name] >= max {
			if sum[name] > max {
				max = sum[name]
				wins[max] = make(map[string]bool)
			}
			wins[max][name] = true
		}
	}

	result := make(map[string]int)

	if len(wins[max]) == 1 {
		for name := range wins[max] {
			fmt.Println(name)
			return
		}
	} else {
		winners := wins[max]
		for i := 0; i < len(histn); i++ {
			name := histn[i]
			if winners[name] {
				result[name] += hists[i]
				if result[name] >= max {
					fmt.Println(name)
					return
				}
			}
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	highestScore := -1
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	var debug bool

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")

		if !debug && token[0] == "ys" {
			debug = true
		}
		if debug {
			fmt.Println(line)
		}
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		if scoreTable[token[0]] > highestScore {
			highestScore = scoreTable[token[0]]
			scoreRecord = append(scoreRecord, highestScore)
			winnerRecord = append(winnerRecord, token[0])
		}
	}

	winnerCnt := 0
	l := len(scoreRecord)
	winningScore := scoreRecord[l-1]
	for _, score := range scoreTable {
		if score == winningScore {
			winnerCnt += 1
		}
	}

	if winnerCnt > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winnerRecord[l-1])
	}
}

package main

/*

ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Победитель популярной в Берляндии карточной игры «Берлоггинг» определяется
по следующим правилам. Если на момент окончания игры существует только
один игрок, набравший максимальное количество очков, то он и становится победителем.

Ситуация осложняется, если таких игроков несколько. Каждый кон игры
некоторый игрок выигрывает или проигрывает некоторое количество очков.
В записи о ходе игры это обозначается строкой «name score», где name это
имя игрока, а score целое число обозначающее количество заработанных очков
данным игроком. Если score — отрицательное число, это обозначает,
что игрок проиграл в этом коне. Так вот, если на конец игры несколько
игроков набрали максимум очков (пусть это число равно m), то выигрывает
тот из них, кто первым набрал как минимум m очков. Перед началом игры
у каждого игрока 0 очков. Гарантируется, что на момент окончания игры
хотя бы у одного игрока положительное число очков.

Входные данные
	В первой строке записано целое число n (1 ≤ n ≤ 1000), n — количество конов сыгранной игры.
	Далее в n строках идут описания конов, в формате «name score» в хронологическом порядке,
	где name это строка из строчных букв латинского алфавита длины от 1 до 32,
	а score это целое число от -1000 до 1000 включительно.

Выходные данные
	Выведите имя победителя игры «Берлоггинг».

*/

import "fmt"

type Round struct {
	score int
	name  string
}

type Score struct {
	name  string
	score int
}

func solve(ch <-chan Round) string {
	scores := map[string]int{}
	ranked := []Score{}

	max := -1001
	winners := map[string]bool{}
	for r := range ch {
		scores[r.name] += r.score
		cur := scores[r.name]
		if cur > 0 {
			ranked = append(ranked, Score{name: r.name, score: cur})
		}

		if cur > max {
			max = cur
			winners = map[string]bool{}
			winners[r.name] = true
		} else if cur == max {
			winners[r.name] = true
		}
	}

	if len(winners) == 1 {
		for name, _ := range winners {
			return name
		}
	}

	for _, s := range ranked {
		if !winners[s.name] {
			continue
		}

		if s.score >= max {
			return s.name
		}
	}

	// will happend only for zero rounds
	return ""
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	ch := make(chan Round)
	go func() {
		for i := 0; i < n; i++ {
			r := Round{}
			fmt.Scanf("%s %d\n", &r.name, &r.score)
			ch <- r
		}
		close(ch)
	}()

	fmt.Printf("%s\n", solve(ch))
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	var (
		name  string
		score int
	)
	var (
		hashScore    map[string]int = make(map[string]int)
		currentScore int
		ok           bool

		maximumName  string
		maximumScore int
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &name, &score)
		if score < 0 {
			continue
		}

		if currentScore, ok = hashScore[name]; !ok {
			currentScore = 0
		}

		currentScore += score
		hashScore[name] = currentScore

		if currentScore > maximumScore {
			maximumName = name
			maximumScore = currentScore
		}
	}
	fmt.Println(maximumName)
}

package main
import (
	"fmt"
	//"sort"
	//"unicode/utf8"
)
func main() {
	var n int
	a:=make(map[string]int)
	b:=make(map[string]int)

	var c [1000]int
	var s [1000]string
	m:=0
	fmt.Scan(&n)
	for i:=0;i<n;i++ {
		fmt.Scan(&s[i],&c[i])
		a[s[i]]+=c[i]
	}
	for i:=0;i<n;i++ {
		if m<a[s[i]] {
			m=a[s[i]]
		}
		fmt.Println(m)
	}
	j:=0
	b[s[0]]+=c[0]
	for ;a[s[j]]<m || b[s[j]]<m;j++ {
		b[s[j]]+=c[j]
	}
	fmt.Println(s[j])
}

package main

/*

ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Победитель популярной в Берляндии карточной игры «Берлоггинг» определяется
по следующим правилам. Если на момент окончания игры существует только
один игрок, набравший максимальное количество очков, то он и становится победителем.

Ситуация осложняется, если таких игроков несколько. Каждый кон игры
некоторый игрок выигрывает или проигрывает некоторое количество очков.
В записи о ходе игры это обозначается строкой «name score», где name это
имя игрока, а score целое число обозначающее количество заработанных очков
данным игроком. Если score — отрицательное число, это обозначает,
что игрок проиграл в этом коне. Так вот, если на конец игры несколько
игроков набрали максимум очков (пусть это число равно m), то выигрывает
тот из них, кто первым набрал как минимум m очков. Перед началом игры
у каждого игрока 0 очков. Гарантируется, что на момент окончания игры
хотя бы у одного игрока положительное число очков.

Входные данные
	В первой строке записано целое число n (1 ≤ n ≤ 1000), n — количество конов сыгранной игры.
	Далее в n строках идут описания конов, в формате «name score» в хронологическом порядке,
	где name это строка из строчных букв латинского алфавита длины от 1 до 32,
	а score это целое число от -1000 до 1000 включительно.

Выходные данные
	Выведите имя победителя игры «Берлоггинг».

*/

import "fmt"

type Round struct {
	score int
	name string
}

func solve(ch <-chan Round) string {
	players := map[string]int{}

	var maxScore int
	var maxName string
	for r := range ch {
		players[r.name] += r.score
		if players[r.name] > maxScore {
			maxName = r.name
			maxScore = players[r.name]
		}
	}
	return maxName
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	ch := make(chan Round)
	go func () {
		for i := 0; i < n; i++ {
			r := Round{}
			fmt.Scanf("%s %d\n", &r.name, &r.score)
			ch <- r
		}
		close(ch)
	}()

	fmt.Printf("%s\n", solve(ch))
}

package main

import (
	"bufio"
	"fmt"
  "os"
	"strconv"
	"strings"
)

func main() {
	if err := run(os.Args[1:]); err != nil {
	  fmt.Println(err)
	}
}

type Player struct {
	score int
	name string
}

var CRLFReplacer = strings.NewReplacer("\n", "", "\r", "")

func run(args []string) error {
	reader := bufio.NewReader(os.Stdin)

	text, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	text = CRLFReplacer.Replace(text)

	lines, err := strconv.Atoi(text)
	if err != nil {
		return err
	}

	scores := make(map[string]int)
	var winner *Player

	for i := 0; i < lines; i++ {
		text, err := reader.ReadString('\n')
		if err != nil {
			return err
		}
		text = CRLFReplacer.Replace(text)

		parts := strings.Split(text, " ")
		name := parts[0]
		score, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}

		newScore := scores[name] + score
		scores[name] = newScore

		if winner == nil || winner.score < newScore {
			winner = &Player{
				score: newScore,
				name:  name,
			}
		}
	}

	fmt.Println(winner.name)
	return nil
}

package main

/*

ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Победитель популярной в Берляндии карточной игры «Берлоггинг» определяется
по следующим правилам. Если на момент окончания игры существует только
один игрок, набравший максимальное количество очков, то он и становится победителем.

Ситуация осложняется, если таких игроков несколько. Каждый кон игры
некоторый игрок выигрывает или проигрывает некоторое количество очков.
В записи о ходе игры это обозначается строкой «name score», где name это
имя игрока, а score целое число обозначающее количество заработанных очков
данным игроком. Если score — отрицательное число, это обозначает,
что игрок проиграл в этом коне. Так вот, если на конец игры несколько
игроков набрали максимум очков (пусть это число равно m), то выигрывает
тот из них, кто первым набрал как минимум m очков. Перед началом игры
у каждого игрока 0 очков. Гарантируется, что на момент окончания игры
хотя бы у одного игрока положительное число очков.

Входные данные
	В первой строке записано целое число n (1 ≤ n ≤ 1000), n — количество конов сыгранной игры.
	Далее в n строках идут описания конов, в формате «name score» в хронологическом порядке,
	где name это строка из строчных букв латинского алфавита длины от 1 до 32,
	а score это целое число от -1000 до 1000 включительно.

Выходные данные
	Выведите имя победителя игры «Берлоггинг».

*/

import "fmt"

type Round struct {
	score int
	name  string
}

type Score struct {
	name  string
	score int
}

func solve(ch <-chan Round) string {

	max := -1001
	log := []Round{}
	scores := map[string]int{}
	winners := map[string]bool{}
	for r := range ch {
		scores[r.name] += r.score
		cur := scores[r.name]
		log = append(log, r)

		if cur > max {
			max = cur
			winners = map[string]bool{}
			winners[r.name] = true
		} else if cur == max {
			winners[r.name] = true
		}
	}

	if len(winners) == 1 {
		for name, _ := range winners {
			return name
		}
	}

	scores = map[string]int{}
	for _, r := range log {
		if !winners[r.name] {
			continue
		}

		scores[r.name] += r.score
		s := scores[r.name]

		if s >= max {
			return r.name
		}
	}

	return "" // to make compiler happy
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	ch := make(chan Round)
	go func() {
		for i := 0; i < n; i++ {
			r := Round{}
			fmt.Scanf("%s %d\n", &r.name, &r.score)
			ch <- r
		}
		close(ch)
	}()

	fmt.Printf("%s\n", solve(ch))
}

package main

import (
	"fmt"
)

func main() {
	var roundCount int
	fmt.Scanln(&roundCount)
	rounds := make([]map[string]int, roundCount+1)
	for i := 1; i <= roundCount; i++ {
		rounds[i] = make(map[string]int)
		for k, v := range rounds[i-1] {
			rounds[i][k] = v
		}
		var name string
		var score int
		fmt.Scan(&name, &score)
		rounds[i][name] += score
	}
	var winners []string
	var m int
	for k, v := range rounds[roundCount] {
		switch {
		case v > m:
			winners = []string{k}
			m = v
		case v == m:
			winners = append(winners, k)
		}
	}
	var winner string
	if len(winners) > 1 {
		FIND_WINNER:
		for i := 1; i <= roundCount; i++ {
			for k, v := range rounds[i] {
				for wi := range winners {
					if k == winners[wi] && v == m {
						winner = k
						break FIND_WINNER
					}
				}
			}
		}
	} else {
		winner = winners[0]
	}
	fmt.Println(winner)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	type node struct {
		name  string
		score int
	}

	var (
		nodeList  []node         = make([]node, n)
		scoreHash map[string]int = make(map[string]int, n)
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &nodeList[i].name, &nodeList[i].score)

		if currentScore, ok := scoreHash[nodeList[i].name]; ok {
			scoreHash[nodeList[i].name] = currentScore + nodeList[i].score
		} else {
			scoreHash[nodeList[i].name] = nodeList[i].score
		}
	}

	var maximum int
	for _, score := range scoreHash {
		if score > maximum {
			maximum = score
		}
	}

	scoreHash = make(map[string]int, n)
	for _, item := range nodeList {
		var (
			currentScore int
			ok           bool
		)
		if currentScore, ok = scoreHash[item.name]; !ok {
			currentScore = 0
		}
		currentScore += item.score
		scoreHash[item.name] = currentScore

		if currentScore == maximum {
			fmt.Println(item.name)
			return
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		scoreRecord = append(scoreRecord, roundScore)
		winnerRecord = append(winnerRecord, token[0])
	}

	winnerCnt := 0
	l := len(scoreRecord)
	var winner string
	winningScore := -1
	for name, score := range scoreTable {
		if score > winningScore {
			winner = name
			winningScore = score
		}
	}
	for _, score := range scoreTable {
		if score == winningScore {
			winnerCnt += 1
		}
	}

	if winnerCnt > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore && scoreTable[winnerRecord[i]] == winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winner)
	}
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"fmt"
	"bufio"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &n)
	sum := make(map[string]int)
	hist := make(map[string][]int)
	wins := make(map[int][]string)
	max := 0
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanf(input, "%s %d\n", &name, &score)
		sum[name] += score
		if len(hist[name]) == 0 {
			hist[name] = append(hist[name], 0)
		}
		hist[name] = append(hist[name], score)
		if max <= sum[name] {
			max = sum[name]
			wins[max] = append(wins[max], name)
		}
	}

	if len(wins[max]) == 1 {
		fmt.Println(wins[max][0])
	} else {
		i := 0
		winners := wins[max]
		for true {
			for _, name := range winners {
				if i >= len(hist[name]) {
					continue
				}

				if hist[name][i] >= max {
					fmt.Print(name)
					return
				}

				hist[name][i + 1] += hist[name][i]
			}
			i++
		}
	}
}

// 2A-mic
package main

import (
    "fmt"
)

type hmm struct {
    nama [1010]string
    skor [1010]int
    cou  [1010]int
}

func hmmm() *hmm {
    return &hmm{}
}

func main() {
    max := -1010
    count := 100
    s := hmmm()
    x := false
    y := 0
    var k string
    var n, sk, c int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&k, &sk)
        for z := 0; z < n; z++ {
            if s.nama[z] == k {
                s.skor[z] += sk
                s.cou[z]++
                x = true
            }
        }
        if !x {
            s.nama[y] = k
            s.skor[y] = sk
            s.cou[y] = 0
            x = false
            y++
        }
    }
    for l := 0; l < n; l++ {
        if s.skor[l] >= max && s.cou[l] < count {
            max = s.skor[l]
            c = l
            count = s.cou[l]
        }
    }
    fmt.Println(s.nama[c])
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanln(&n)

	scores := make(map[string]int)
	maxes := make(map[int]string)

	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Scanf("%s %d\n", &name, &score)
		scores[name] += score
		if _, exist := maxes[scores[name]]; !exist {
			maxes[scores[name]] = name
		}
	}

	var winner string
	maxScore := 0
	for _, v := range scores {
		if v > maxScore {
			winner = maxes[v]
			maxScore = v
		}
	}

	fmt.Println(winner)
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"fmt"
	"bufio"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &n)
	sum := make(map[string]int)
	hist := make(map[string][]int)
	wins := make(map[int][]string)
	max := 0
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanf(input, "%s %d\n", &name, &score)
		sum[name] += score
		hist[name] = append(hist[name], score)
		if max <= sum[name] {
			max = sum[name]
			wins[max] = append(wins[max], name)
		}
	}

	if len(wins[max]) == 1 {
		fmt.Println(wins[max][0])
	} else {
		i := 0
		for true {
			for _, name := range wins[max] {
				if hist[name][i] >= max {
					fmt.Println(name)
					return
				}
				hist[name][i + 1] += hist[name][i]
			}
		}
	}
}

// https://codeforces.com/contest/2/0
package main

import (
	"fmt"
	"bufio"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &n)
	sum := make(map[string]int)
	last := make(map[string][]int)
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanln(input, &name, &score)
		sum[name] += score
		last[name] = append(last[name], score)
	}

	var max_name string
	max_score := 0
	for k, v := range sum {
		if max_score < v {
			max_score = v
			max_name = k
		}
	}

	fmt.Println(max_name)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var rounds []map[string]uint16
	for i := 0; i < n; i++ {
		var name string
		var score uint16
		fmt.Scan(&name, &score)
		m := make(map[string]uint16)
		if i != 0 {
			for k, v := range rounds[i-1] {
				m[k] = v
			}
		}
		m[name] = m[name] + score
		rounds = append(rounds, m)
	}
	var max uint16
	for _, v := range rounds[n-1] {
		if v > max {
			max = v
		}
	}
	for _, r := range rounds {
		for k, v := range r {
			if v == max {
				fmt.Print(k)
				return
			}
		}
	}
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"bufio"
	"fmt"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main() {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &n)
	sum := make(map[string]int)
	histn := make([]string, 0)
	hists := make([]int, 0)
	wins := make(map[int]map[string]bool)
	max := 0
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanf(input, "%s %d\n", &name, &score)
		histn = append(histn, name)
		hists = append(hists, score)
		sum[name] += score
		if sum[name] >= max {
			if sum[name] > max {
				max = sum[name]
				wins[max] = make(map[string]bool)
			}
			wins[max][name] = true
		}
	}

	result := make(map[string]int)
	winners := wins[max]
	for i := 0; i < len(histn); i++ {
		name := histn[i]
		if winners[name] {
			result[name] += hists[i]
			if result[name] >= max {
				fmt.Println(name)
				return
			}
		}
	}
}

package main

/*

ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Победитель популярной в Берляндии карточной игры «Берлоггинг» определяется
по следующим правилам. Если на момент окончания игры существует только
один игрок, набравший максимальное количество очков, то он и становится победителем.

Ситуация осложняется, если таких игроков несколько. Каждый кон игры
некоторый игрок выигрывает или проигрывает некоторое количество очков.
В записи о ходе игры это обозначается строкой «name score», где name это
имя игрока, а score целое число обозначающее количество заработанных очков
данным игроком. Если score — отрицательное число, это обозначает,
что игрок проиграл в этом коне. Так вот, если на конец игры несколько
игроков набрали максимум очков (пусть это число равно m), то выигрывает
тот из них, кто первым набрал как минимум m очков. Перед началом игры
у каждого игрока 0 очков. Гарантируется, что на момент окончания игры
хотя бы у одного игрока положительное число очков.

Входные данные
	В первой строке записано целое число n (1 ≤ n ≤ 1000), n — количество конов сыгранной игры.
	Далее в n строках идут описания конов, в формате «name score» в хронологическом порядке,
	где name это строка из строчных букв латинского алфавита длины от 1 до 32,
	а score это целое число от -1000 до 1000 включительно.

Выходные данные
	Выведите имя победителя игры «Берлоггинг».

*/

import "fmt"

type Round struct {
	score int
	name string
}

func solve(ch <-chan Round) string {
	players := map[string]int{}

	//fmt.Println("---------------------------")

	var maxScore int
	var maxName string
	for r := range ch {
		if r.score > 0 {
			players[r.name] += r.score
		}

		if players[r.name] > maxScore {
			maxName = r.name
			maxScore = players[r.name]
		}
		//fmt.Printf("%v\n", players)
	}
	//fmt.Printf("%s: %d\n", maxName, maxScore)
	return maxName
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	ch := make(chan Round)
	go func () {
		for i := 0; i < n; i++ {
			r := Round{}
			fmt.Scanf("%s %d\n", &r.name, &r.score)
			ch <- r
		}
		close(ch)
	}()

	fmt.Printf("%s\n", solve(ch))
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	highestScore := -1
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	var debug bool

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")

		if !debug && token[0] == "ya" {
			debug = true
		}
		if debug {
			fmt.Println(line)
		}
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		if scoreTable[token[0]] > highestScore {
			highestScore = scoreTable[token[0]]
			scoreRecord = append(scoreRecord, highestScore)
			winnerRecord = append(winnerRecord, token[0])
		}
	}

	winnerCnt := 0
	l := len(scoreRecord)
	winningScore := scoreRecord[l-1]
	for _, score := range scoreTable {
		if score == winningScore {
			winnerCnt += 1
		}
	}

	if winnerCnt > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winnerRecord[l-1])
	}
}

package main

import (
	"fmt"
)

func main() {
	var roundCount int
	fmt.Scanln(&roundCount)
	rounds := make([]map[string]int, roundCount+1)
	roundNames := make([]string, roundCount + 1)
	for i := 1; i <= roundCount; i++ {
		rounds[i] = make(map[string]int)
		for k, v := range rounds[i-1] {
			rounds[i][k] = v
		}
		var name string
		var score int
		fmt.Scan(&name, &score)
		rounds[i][name] += score
		roundNames[i] = name
	}
	var winners []string
	var m int
	for k, v := range rounds[roundCount] {
		switch {
		case v > m:
			winners = []string{k}
			m = v
		case v == m:
			winners = append(winners, k)
		}
	}
	var winner string
	if len(winners) > 1 {
		FIND_WINNER:
		for i := 1; i <= roundCount; i++ {
			if (rounds[i][roundNames[i]] >= m) {
				winner = roundNames[i]
				break FIND_WINNER
			}
		}
	} else {
		winner = winners[0]
	}
	fmt.Println(winner)
}

package main

import (
	"fmt"
)

func main() {
	score := map[string]int{}
	turn := map[string]int{}
	var n int
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		var name string
		var mark int
		fmt.Scanf("%s %d", &name, &mark)
		score[name] = score[name] + mark
		turn[name] = i
	}
	max := -1000001
	minTurn := 99999
	var winner string

	for name, mark := range score {
		if mark == max && turn[name] < minTurn || mark > max {
			winner = name
			max = mark
			minTurn = turn[name]
		}
	}
	fmt.Printf("%s", winner)

}

package main

/*

ограничение по времени на тест
	1 second
ограничение по памяти на тест
	64 megabytes

Победитель популярной в Берляндии карточной игры «Берлоггинг» определяется
по следующим правилам. Если на момент окончания игры существует только
один игрок, набравший максимальное количество очков, то он и становится победителем.

Ситуация осложняется, если таких игроков несколько. Каждый кон игры
некоторый игрок выигрывает или проигрывает некоторое количество очков.
В записи о ходе игры это обозначается строкой «name score», где name это
имя игрока, а score целое число обозначающее количество заработанных очков
данным игроком. Если score — отрицательное число, это обозначает,
что игрок проиграл в этом коне. Так вот, если на конец игры несколько
игроков набрали максимум очков (пусть это число равно m), то выигрывает
тот из них, кто первым набрал как минимум m очков. Перед началом игры
у каждого игрока 0 очков. Гарантируется, что на момент окончания игры
хотя бы у одного игрока положительное число очков.

Входные данные
	В первой строке записано целое число n (1 ≤ n ≤ 1000), n — количество конов сыгранной игры.
	Далее в n строках идут описания конов, в формате «name score» в хронологическом порядке,
	где name это строка из строчных букв латинского алфавита длины от 1 до 32,
	а score это целое число от -1000 до 1000 включительно.

Выходные данные
	Выведите имя победителя игры «Берлоггинг».

*/

import "fmt"

type Round struct {
	score int
	name string
}

type Score struct {
	cur int
	max int
	turn int // number of turn when max was assigned
}

func solve(ch <-chan Round) string {
	players := map[string]Score{}

	turn := 0
	for r := range ch {
		score := players[r.name]
		score.cur = score.cur + r.score

		if score.cur > score.max {
			score.max = score.cur
			score.turn = turn
		}
		players[r.name] = score

		turn += 1
	}

	maxCur := 0 // гарантировано, что хотя бы у одного score > 0
	winners := []string{}
	for name, score := range players {
		if score.cur > maxCur {
			maxCur = score.cur
			winners = []string{name}
		} else if score.cur == maxCur {
			winners = append(winners, name)
		}
	}

	if len(winners) == 1 {
		return winners[0]
	}

	// смотрим прошлые максимумы у сравнявшихся победителей
	winner := winners[0]
	minTurn := 1001 // как +inf, максимум 1000
	for _, name := range winners {
		score := players[name]
		if score.max >= maxCur && score.turn < minTurn {
			minTurn = score.turn
			winner = name
		}
	}
	return winner
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	ch := make(chan Round)
	go func () {
		for i := 0; i < n; i++ {
			r := Round{}
			fmt.Scanf("%s %d\n", &r.name, &r.score)
			ch <- r
		}
		close(ch)
	}()

	fmt.Printf("%s\n", solve(ch))
}

// codeforces_002A_winner
package main

import (
	"fmt"
)

func main(){
	var num int
	fmt.Scanln(&num)
	var (
		name string
		number int
	)

	var (
	m map[string]int
	maxNumber int
	maxName string
	)
	m=make(map[string]int)
	maxNumber = -1000*1001

	for i:=0;i<num;i++{
		fmt.Scanln(&name, &number)
		m[name]+=number
		if m[name]>maxNumber{
			maxNumber=m[name]
			maxName=name
		}
	}
	fmt.Printf("%s", maxName)
}

package main

import (
	"container/heap"
	"fmt"
)

type Item struct {
	name  string
	score int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int           { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool { return pq[i].score > pq[j].score }
func (pq PriorityQueue) Swap(i, j int)      { pq[i], pq[j] = pq[j], pq[i] }

func (pq *PriorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.(*Item))
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n - 1]
	*pq = old[0 : n - 1]
	return item
}

func (pq *PriorityQueue) update(name string, score int) {
	n := -1

	for i, v := range *pq {
		if v.name == name {
			v.score += score
			n = i
			break
		}
	}

	item := Item{name, score}

	if n == -1 {
		heap.Push(pq, &item)
	} else {
		heap.Fix(pq, n)
	}
}

func main() {
	var n int
	fmt.Scanf("%d", &n)
	var pq PriorityQueue
	heap.Init(&pq)

	for ; n > 0; n-- {
		var name string
		var score int
		fmt.Scanf("%s %d", &name, &score)
		pq.update(name, score)
	}

	fmt.Println(heap.Pop(&pq).(*Item).name)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var rounds []map[string]int16
	for i := 0; i < n; i++ {
		var name string
		var score int16
		fmt.Scan(&name, &score)
		m := make(map[string]int16)
		if i != 0 {
			for k, v := range rounds[i-1] {
				m[k] = v
			}
		}
		m[name] = m[name] + score
		rounds = append(rounds, m)
	}
	var max int16
	for _, v := range rounds[n-1] {
		if v > max {
			max = v
		}
	}
	for _, r := range rounds {
		for k, v := range r {
			if v > max {
				fmt.Print(k)
				return
			}
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	highestScore := -1
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	var debug bool

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")

		if !debug && token[0] == "ys" {
			debug = true
		}
		if debug {
			if token[0] == "gczuitwphlv" {
				fmt.Printf("g: %d\n", token[1])
			} else if token[0] == "fzcgiyqdsddncqeccyegireaj" {
				fmt.Printf("f: %d\n", token[1])
			}
		}
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		if scoreTable[token[0]] > highestScore {
			highestScore = scoreTable[token[0]]
			scoreRecord = append(scoreRecord, highestScore)
			winnerRecord = append(winnerRecord, token[0])
		}
	}

	winnerCnt := 0
	l := len(scoreRecord)
	winningScore := scoreRecord[l-1]
	for _, score := range scoreTable {
		if score == winningScore {
			winnerCnt += 1
		}
	}

	if winnerCnt > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winnerRecord[l-1])
	}
}

// codeforces_002A_winner
package main

import (
	"fmt"
)

func main() {
	var (
		num       int
		name      string
		number    int
		m, n      map[string]int
		names     []string
		numbers   []int
		maxNumber int
		maxName   string
	)

	fmt.Scanln(&num)
	m = make(map[string]int)
	maxNumber = -1000 * 1001

	for i := 0; i < num; i++ {
		fmt.Scanln(&name, &number)
		m[name] += number
		names = append(names, name)
		numbers = append(numbers, number)
	}

	for _, name = range names {
		if m[name] >= maxNumber {
			maxNumber = m[name]
		}
	}

	n = make(map[string]int)
	for i := 0; i < num; i++ {
		n[names[i]] += numbers[i]
		if maxNumber == n[names[i]] {
			maxName = names[i]
			break
		}
	}
	fmt.Printf("%s\n", maxName)
}

package main

import (
	"fmt"
)

func main() {
	var t int
	fmt.Scan(&t)

	mp := make(map[string]int)
	var max int
	var first string

	for z := 0; z < t; z++ {
		var s string
		var n int
		fmt.Scan(&s, &n)

		mp[s] += n
		if mp[s] > max {
			first = s
			max = mp[s]
		}
	}

	fmt.Print(first)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	if err := run(os.Args[1:]); err != nil {
		fmt.Println(err)
	}
}

type Round struct {
	player string
	score  int
}

var CRLFReplacer = strings.NewReplacer("\n", "", "\r", "")

func run(args []string) error {
	reader := bufio.NewReader(os.Stdin)

	text, err := reader.ReadString('\n')
	if err != nil {
		return err
	}
	text = CRLFReplacer.Replace(text)

	lines, err := strconv.Atoi(text)
	if err != nil {
		return err
	}

	scores := make(map[string]int)
	max := 0
	var rounds []*Round

	for i := 0; i < lines; i++ {
		text, err := reader.ReadString('\n')
		if err != nil {
			return err
		}
		text = CRLFReplacer.Replace(text)

		parts := strings.Split(text, " ")
		name := parts[0]
		score, err := strconv.Atoi(parts[1])
		if err != nil {
			return err
		}

		rounds = append(rounds, &Round{name, score})
	}

	for _, r := range rounds {
		scores[r.player] = scores[r.player] + r.score
	}

	for _, v := range scores {
		if max < v {
			max = v
		}
	}

	scores = make(map[string]int)

	for _, r := range rounds {
		scores[r.player] = scores[r.player] + r.score
		if scores[r.player] >= max {
			fmt.Println(r.player)
			return nil
		}
	}

	return nil
}

package main

import (
	"fmt"
)

type pair struct {
	Value int64
	N     int64
}

func less(a, b *pair) bool {
	return a.Value < b.Value || a.Value == b.Value && a.N > b.N
}

func main() {
	var n int64
	var key string
	var value int64
	r := make(map[string]*pair)
	fmt.Scanf("%d\n", &n)
	for i := int64(1); i <= n; i++ {
		fmt.Scanf("%s %d\n", &key, &value)
		if _, ok := r[key]; ok {
			r[key].Value += value
			r[key].N = i
		} else {
			r[key] = &pair{Value: value, N: i}
		}
	}
	max := &pair{}
	var choose string
	for key, v := range r {
		if less(max, v) {
			max.Value = v.Value
			max.N = v.N
			choose = key
		}
	}
	fmt.Println(choose)
}

package main

import "fmt"

type ScoreRound struct {
	score int
	round int
}

func main() {
	var times int
	fmt.Scanln(&times)

	countMap := make(map[string]*ScoreRound)
	var maxScoreName string
	maxScoreRound := ScoreRound{score: -1, round: 0}
	for i := 1; i <= times; i++ {
		var name string
		var score int
		fmt.Scanln(&name, &score)
		scoreRound, ok := countMap[name]
		if !ok {
			scoreRound = &ScoreRound{score: 0, round: 0}
			countMap[name] = scoreRound
		}
		scoreRound.score += score
		scoreRound.round = i
	}

	for k, v := range countMap {
		if v.score > maxScoreRound.score || (v.score == maxScoreRound.score && v.round < maxScoreRound.round) {
			maxScoreName = k
			maxScoreRound = *v
		}
	}
	fmt.Println(maxScoreName)
}

package main

import (
	"fmt"
)

type pair struct {
	Value int64
	N     int64
}

func less(a, b *pair) bool {
	return a.Value < b.Value || a.Value == b.Value && a.N > b.N
}

func main() {
	var n int64
	var key string
	var value int64
	r := make(map[string]*pair)
	fmt.Scanf("%d\n", &n)
	for i := n; i > 0; i-- {
		fmt.Scanf("%s %d\n", &key, &value)
		if _, ok := r[key]; ok {
			r[key].Value += value
			r[key].N++
		} else {
			r[key] = &pair{Value: value, N: 1}
		}
	}
	max := &pair{}
	var choose string
	for key, v := range r {
		if less(max, v) {
			max.Value = v.Value
			max.N = v.N
			choose = key
		}
	}
	fmt.Println(choose)
}

package main

import (
  "os"
  "bufio"
  "strconv"
  "fmt"
)

var scanner *bufio.Scanner

func getI64() int64 {
  scanner.Scan()
  x, _ := strconv.ParseInt(scanner.Text(), 10, 64)
  return x
}
func getI() int {
  return int(getI64())
}
func getF() float64 {
  scanner.Scan()
  x, _ := strconv.ParseFloat(scanner.Text(), 64)
  return x
}
func getS() string {
  scanner.Scan()
  return scanner.Text()
}

type Round struct {
  Player string
  Score int
}

func main() {
  scanner = bufio.NewScanner(os.Stdin)
  scanner.Split(bufio.ScanWords)
  writer := bufio.NewWriter(os.Stdout)
  defer writer.Flush()

  n := getI()
  rounds := make([]Round, n)
  topScore := 0
  scores := map[string]int{}
  for i := 0; i < n; i++ {
    player, score := getS(), getI()
    rounds[i] = Round{ player, score }
    scores[player] += score
    if scores[player] > topScore {
      topScore = scores[player]
    }
  }
  scores = map[string]int{}
  for i := 0; i < n; i++ {
    round := rounds[i]
    player, score := round.Player, round.Score
    scores[player] += score
    if scores[player] >= topScore {
      writer.WriteString(fmt.Sprintf("%s\n", player))
      return
    }
  }
}

package main

import (
	"fmt"
)

func main() {
	var roundCount int
	fmt.Scanln(&roundCount)
	rounds := make([]map[string]int, roundCount+1)
	for i := 1; i <= roundCount; i++ {
		rounds[i] = make(map[string]int)
		for k, v := range rounds[i-1] {
			rounds[i][k] = v
		}
		var name string
		var score int
		fmt.Scanf("%s %d", &name, &score)
		rounds[i][name] += score
	}
	var winners []string
	var m int
	for k, v := range rounds[roundCount] {
		switch {
		case v > m:
			winners = []string{k}
			m = v
		case v == m:
			winners = append(winners, k)
		}
	}
	var winner string
	if len(winners) > 1 {
		for i := 1; i <= roundCount; i++ {
			for k, v := range rounds[i] {
				if v == m {
					winner = k
					break
				}
			}
			if winner != "" {
				break
			}
		}
	} else {
		winner = winners[0]
	}
	fmt.Println(winner)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	var round int

	scanner := bufio.NewScanner(os.Stdin)

	if scanner.Scan() {
		line := scanner.Text()
		fmt.Sscanf(line, "%d", &round)
	}

	scoreMap := make(map[string]int)
	topScore := 0
	topPlayer, secondPlayer := "", ""

	for i := 0; i < round && scanner.Scan(); i++ {
		line := scanner.Text()
		var name string
		var score int

		fmt.Sscanf(line, "%s %d", &name, &score)

		scoreMap[name] += score

		if topScore < scoreMap[name] {
			topPlayer, secondPlayer = name, topPlayer
			topScore = scoreMap[name]
		} else if topPlayer == name {
			topScore = scoreMap[name]
			secondScore := scoreMap[secondPlayer]
			if topScore < secondScore {
				topScore, secondScore = secondScore, topScore
				topPlayer, secondPlayer = secondPlayer, topPlayer
			}
		}
	}

	fmt.Println(topPlayer)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	var (
		name  string
		score int
	)
	var (
		hashScore    map[string]int = make(map[string]int)
		currentScore int
		ok           bool

		maximumName  string
		maximumScore int
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &name, &score)
		if score < 0 {
			continue
		}

		if currentScore, ok = hashScore[name]; !ok {
			currentScore = 0
		}

		currentScore += score
		hashScore[name] = currentScore

		if currentScore > maximumScore {
			maximumName = name
			maximumScore = currentScore
		}
	}
	fmt.Println(maximumName)
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"fmt"
	"bufio"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &n)
	sum := make(map[string]int)
	hist := make(map[string][]int)
	wins := make(map[int][]string)
	max := 0
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanf(input, "%s %d\n", &name, &score)
		if len(hist[name]) == 0 {
			hist[name] = append(hist[name], 0)
		}
		hist[name] = append(hist[name], score)
		sum[name] += score
		if max <= sum[name] {
			max = sum[name]
			wins[max] = append(wins[max], name)
		}
	}

	if len(wins[max]) == 1 {
		fmt.Println(wins[max][0])
	} else {
		i := 0
		winners := wins[max]
		for true {
			for _, name := range winners {
				if i >= len(hist[name]) {
					continue
				}

				if hist[name][i] >= max {
					fmt.Print(name)
					return
				}

				hist[name][i + 1] += hist[name][i]
			}
			i++
		}
	}
}

package main

import (
	"fmt"
)

type T struct {
	I int
	V int
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	var name string
	var score int

	M := make(map[string][]T)

	m := 0
	var N []string
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &name, &score)

		v := score
		if M[name] != nil {
			l := len(M[name])
			v = M[name][l-1].V + score
		}
		M[name] = append(M[name], T{i, v})

		if m < v {
			m = v
			N = []string{name}
		} else if m == v {
			N = append(N, name)
		}
	}

	if len(N) == 1 {
		name = N[0]
	} else {
		i := 0
		for _, v := range N {
			for _, t := range M[v] {
				if t.V >= m {
					if i == 0 || t.I < i {
						name = v
						i = t.I
					}
					break
				}
			}
		}
	}

	fmt.Println(name)

}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanln(&n)

	scores := make(map[string]int)
	maxes := make(map[int]string)

	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Scanf("%s %d\n", &name, &score)
		scores[name] += score
		if _, exist := maxes[scores[name]]; !exist {
			maxes[scores[name]] = name
		}
	}

	var winner string
	maxScore := 0
	for _, v := range scores {
		if v > maxScore {
			winner = maxes[v]
			maxScore = v
		}
	}

	fmt.Println(winner)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func getLine() string {
	s, _ := reader.ReadString('\n')
	if strings.HasSuffix(s, "\r\n") {
		s = s[:len(s)-2]
	} else if strings.HasSuffix(s, "\n") {
		s = s[:len(s)-1]
	}
	return s
}
func getLine2Int() (n int) {
	scanf("%d\n", &n)
	return
}
func getLine2Int2() (a, b int) {
	scanf("%d %d\n", &a, &b)
	return
}
func getLine2Ints(n int) []int {
	ans := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &ans[i])
	}
	scanf("%d\n", &ans[n-1])
	return ans
}

var debug = false

func see(a interface{}) {
	if debug {
		printf("DEBUG:%v\n", a)
	}
}

func main() {
	defer writer.Flush()

	n := getLine2Int()
	var name string
	var max int
	for i := 0; i < n; i++ {
		var str string
		var score int
		scanf("%s %d\n", &str, &score)
		if score > max {
			max, name = score, str
		}
	}
	printf("%s\n", name)
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"fmt"
	"bufio"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscanln(input, &n)
	sum := make(map[string]int)
	histn := make([]string, 0)
	hists := make([]int, 0)
	wins := make(map[int]map[string]bool)
	max := 0
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanf(input, "%s %d\n", &name, &score)
		histn = append(histn, name)
		hists = append(hists, score)
		sum[name] += score
		if  sum[name] > max {
			max = sum[name]
			wins[max] = make(map[string]bool)
			wins[max][name] = true
		}
	}

	result := make(map[string]int)

	if len(wins[max]) == 1 {
		for name := range wins[max] {
			fmt.Println(name)
		}
	} else {
		winners := wins[max]
		for true {
			for i := 0; i < len(histn); i++ {
				name := histn[i]
				if winners[name] {
					result[name] += hists[i]
					if result[name] >= max {
						fmt.Print(name)
						return
					}
				}
			}
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	n := readNum(reader)

	mem := make(map[string]int)

	records := make([]Pair, n)

	for i := 0; i < n; i++ {
		s, _ := reader.ReadBytes('\n')

		var j int
		for j < len(s) && s[j] != ' ' {
			j++
		}
		name := string(s[:j])
		var score int
		readInt(s, j + 1, &score)
		mem[name] += score
		records[i] = Pair{name, mem[name]}
	}
	var best int

	for _, score := range mem {
		best = max(best,score)
	}

	var winner string

	for i := 0; i < n; i++ {
		if records[i].second == best {
			winner = records[i].first
			break
		}
	}

	fmt.Println(winner)
}

func max(a, b int) int {
	if a >= b {
		return a
	}
	return b
}

type Pair struct {
	first string
	second int
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	var round int

	scanner := bufio.NewScanner(os.Stdin)

	if scanner.Scan() {
		line := scanner.Text()
		fmt.Sscanf(line, "%d", &round)
	}

	scoreMap := make(map[string]int)
	scoreMapReverse := make(map[int]string)
	topScore := 0
	topPlayer := ""

	for i := 0; i < round && scanner.Scan(); i++ {
		line := scanner.Text()
		var name string
		var score int

		fmt.Sscanf(line, "%s %d", &name, &score)

		scoreMap[name] += score

		if topScore < scoreMap[name] {
			topPlayer = name
			topScore = scoreMap[name]
		} else if topPlayer == name && score < 0 {

			topScore = 0
			for _, s := range scoreMap {
				if topScore < s {
					topScore = s
					topPlayer = scoreMapReverse[topScore]
				}
			}
		}

		if scoreMap[name] < topScore {
			scoreMapReverse[scoreMap[name]] = topPlayer
		}
	}
	fmt.Println(topPlayer)
}

package main

import (
	"fmt"
)

func main() {
	score := map[string]int{}
	turn := map[string]int{}
	var n int
	fmt.Scanf("%d", &n)
	for i := 0; i < n; i++ {
		var name string
		var mark int
		fmt.Scanf("%s %d", &name, &mark)
		score[name] = score[name] + mark
		turn[name] = i
	}
	max := -1000001
	minTurn := 99999
	var winner string

	for name, mark := range score {
		if mark == max && turn[name] < minTurn || mark > max {
			winner = name
			max = mark
			minTurn = turn[name]
		}
	}
	fmt.Printf("%s", winner)

}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

var reader = bufio.NewReader(os.Stdin)
var writer = bufio.NewWriter(os.Stdout)

func scanf(f string, a ...interface{})  { fmt.Fscanf(reader, f, a...) }
func printf(f string, a ...interface{}) { fmt.Fprintf(writer, f, a...) }

func getLine() string {
	s, _ := reader.ReadString('\n')
	if strings.HasSuffix(s, "\r\n") {
		s = s[:len(s)-2]
	} else if strings.HasSuffix(s, "\n") {
		s = s[:len(s)-1]
	}
	return s
}
func getLine2Int() (n int) {
	scanf("%d\n", &n)
	return
}
func getLine2Int2() (a, b int) {
	scanf("%d %d\n", &a, &b)
	return
}
func getLine2Ints(n int) []int {
	ans := make([]int, n)
	for i := 0; i < n; i++ {
		scanf("%d ", &ans[i])
	}
	scanf("%d\n", &ans[n-1])
	return ans
}

var debug = false

func see(a interface{}) {
	if debug {
		printf("DEBUG:%v\n", a)
	}
}

func main() {
	defer writer.Flush()

	n := getLine2Int()
	scoreCounter := make(map[string]int)
	var name string
	var max int
	for i := 0; i < n; i++ {
		var str string
		var score int
		scanf("%s %d\n", &str, &score)
		scoreCounter[str] += score
		if scoreCounter[str] > max {
			max, name = scoreCounter[str], str
		}
	}
	printf("%s\n", name)
}

package main

import "fmt"

func main(){

  m := make(map[string]int,1000)
  ln := make([]string,1000)
  ls := make([]int,1000)

  var t int
  fmt.Scanln(&t)

  var n string
  var s int
  ms := int(-2000*1000)

  for i:=0 ; i<t ; i++ {

    fmt.Scanln(&n,&s)

    ln[i] = n
    ls[i] = s

    m[n] += s
  }

  for _,v := range m {
    if v>ms { ms = v }
  }

  k := make(map[string]int,1000)

  for i:=0;i<t;i++ {

    n = ln[i]
    s = ls[i]

    k[n] += s

    if k[n] == ms && m[n] == ms {
      fmt.Println(n)
      return;
    }

  }

}

// https://codeforces.com/contest/2/0
package main

import (
	"fmt"
	"bufio"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &n)
	sum := make(map[string]int)
	last := make(map[string][]int)
	max := 0
	maxName := ""
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanln(input, &name, &score)
		sum[name] += score
		last[name] = append(last[name], score)
		if max < sum[name] {
			max = sum[name]
			maxName = name
		}
	}

	fmt.Println(maxName)
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanln(&n)

	scores := make(map[string]int)
	maxScore := 0
	var winner string
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Scanf("%s %d\n", &name, &score)
		scores[name] += score
		if scores[name] > maxScore {
			winner = name
			maxScore = scores[name]
		}
	}

	fmt.Println(winner)
}

// 2A-mic
package main

import (
    "fmt"
)

type hmm struct {
    nama [1010]string
    skor [1010]int
    cou  [1010]int
}

func hmmm() *hmm {
    return &hmm{}
}

func main() {
    time := 1
    max := -1010
    count := 100
    s := hmmm()
    x := false
    y := 0
    var k string
    var n, sk, c int
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        x = false
        fmt.Scan(&k, &sk)
        for z := 0; z < n; z++ {
            if s.nama[z] == k {
                s.skor[z] += sk
                s.cou[z] = time
                x = true
            }
        }
        if !x {
            s.nama[y] = k
            s.skor[y] = sk
            s.cou[y] = time
            x = false
            y++
        }
        time++
    }
    for l := 0; l < n; l++ {
        if s.skor[l] >= max && s.cou[l] <= count {
            max = s.skor[l]
            c = l
            count = s.cou[l]
        }
    }
    //fmt.Println(s.cou)
    //fmt.Println(s.nama)
    //fmt.Println(s.skor)
    fmt.Println(s.nama[c])
}

package main

import (
	"fmt"
)

func main() {
	var roundCount int
	fmt.Scanln(&roundCount)
	rounds := make([]map[string]int, roundCount+1)
	roundNames := make([]string, roundCount + 1)
	for i := 1; i <= roundCount; i++ {
		rounds[i] = make(map[string]int)
		for k, v := range rounds[i-1] {
			rounds[i][k] = v
		}
		var name string
		var score int
		fmt.Scan(&name, &score)
		rounds[i][name] += score
		roundNames[i] = name
	}
	var winners []string
	var m int
	for k, v := range rounds[roundCount] {
		switch {
		case v > m:
			winners = []string{k}
			m = v
		case v == m:
			winners = append(winners, k)
		}
	}
	var winner string
	if len(winners) > 1 {
		FIND_WINNER:
		for i := 1; i <= roundCount; i++ {
			if (rounds[i][roundNames[i]] >= m) {
				winner = roundNames[i]
				break FIND_WINNER
			}
		}
	} else {
		winner = winners[0]
	}
	fmt.Println(winner)
}

package main

import "fmt"

type ScoreRound struct {
	score int
	round int
}

func main() {
	var times int
	fmt.Scanln(&times)

	countMap := make(map[string]*ScoreRound)
	var maxScoreName string
	maxScoreRound := ScoreRound{score: -1, round: 0}
	for i := 1; i <= times; i++ {
		var name string
		var score int
		fmt.Scanln(&name, &score)
		scoreRound, ok := countMap[name]
		if !ok {
			scoreRound = &ScoreRound{score: 0, round: 0}
			countMap[name] = scoreRound
		}
		scoreRound.score += score
		scoreRound.round = i
	}

	for k, v := range countMap {
		if v.score > maxScoreRound.score || (v.score == maxScoreRound.score && v.round < maxScoreRound.round) {
			maxScoreName = k
			maxScoreRound = *v
		}
	}
	fmt.Println(maxScoreName)
}

package main

import "fmt"

func main(){

  m := make(map[string]int,1000)
  var t int

  fmt.Scanf("%d",&t)

  var n string
  var s int
  var mn string
  ms := int(-2000*1000)

  for i:=0 ; i<t ; i++ {

    fmt.Scanf("%s%d",&n,&s)

    m[n] += s

    if(m[n] > ms){
      mn = n
      ms = m[n]
    }
  }

  fmt.Println(mn)

}

// codeforces_002A_winner
package main

import (
	"fmt"
)

func main() {
	var (
		num       int
		name      string
		number    int
		m, n      map[string]int
		names     []string
		numbers   []int
		maxNumber int
		maxName   string
	)

	fmt.Scanln(&num)
	m = make(map[string]int)
	maxNumber = -1000 * 1001

	for i := 0; i < num; i++ {
		fmt.Scanln(&name, &number)
		m[name] += number
		names = append(names, name)
		numbers = append(numbers, number)
	}

	for name, _ = range m {
		//		fmt.Printf("%s\t%d\n", name, m[name])
		if m[name] >= maxNumber {
			maxNumber = m[name]
		}
	}

	n = make(map[string]int)
	for i := 0; i < num; i++ {
		n[names[i]] += numbers[i]
		if maxNumber >= n[names[i]] && maxNumber >= m[names[i]] {
			maxName = names[i]
			break
		}
	}
	fmt.Printf("%s\n", maxName)
}

package main
import (
	"fmt"
	//"sort"
	//"unicode/utf8"
)
func main() {
	var n int
	a:=make(map[string]int)
	b:=make(map[string]int)

	var c [1000]int
	var s [1000]string
	m:=0
	fmt.Scan(&n)
	for i:=0;i<n;i++ {
		fmt.Scan(&s[i],&c[i])
		a[s[i]]+=c[i]
	}
	for i:=0;i<n;i++ {
		if m<a[s[i]] {
			m=a[s[i]]
		}
		fmt.Println(m)
	}
	j:=0
	b[s[0]]+=c[0]
	for ;a[s[j]]<m || b[s[j]]<m;j++ {
		b[s[j]]+=c[j]
	}
	fmt.Println(s[j])
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	highestScore := -1
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		if scoreTable[token[0]] > highestScore {
			highestScore = scoreTable[token[0]]
			scoreRecord = append(scoreRecord, highestScore)
			winnerRecord = append(winnerRecord, token[0])
		}
	}

	winnerCnt := 0
	l := len(scoreRecord)
	winningScore := scoreRecord[l-1]
	for _, score := range scoreTable {
		if score == winningScore {
			winnerCnt += 1
		}
	}

	if winnerCnt > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winnerRecord[l-1])
	}
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanln(&n)

	scores := make(map[string]int)
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Scanf("%s %d\n", &name, &score)
		scores[name] += score
	}

	var winner string
	var maxScore = 0
	for k, v := range scores {
		if v > maxScore {
			winner = k
		}
	}

	fmt.Println(winner)
}

package main

import "fmt"

func main() {
    var n,a int
    var s string
    score := make(map[string]int)
    max, winner := -1001, ""
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&s,&a)
        score[s] += a
        if score[s] > max {
            max = score[s]
            winner = s
        }
    }
    fmt.Println(winner)
}

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	score := map[string]int{}
	turn := map[string]int{}
	var n int
	s := bufio.NewScanner(os.Stdin)
	s.Scan()
	fmt.Sscanf(s.Text(), "%d", &n)
	for i := 0; i < n; i++ {
		var name string
		var mark int
		s.Scan()
		fmt.Sscanf(s.Text(), "%s %d", &name, &mark)
		score[name] = score[name] + mark
		turn[name] = i
	}
	max := -1000001
	minTurn := 99999
	var winner string

	for name, mark := range score {
		if (mark == max && turn[name] < minTurn) || mark > max {
			winner = name
			max = mark
			minTurn = turn[name]
		}
	}
	fmt.Printf("%s", winner)

}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	highestScore := -1
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		if scoreTable[token[0]] > highestScore {
			highestScore = scoreTable[token[0]]
			scoreRecord = append(scoreRecord, highestScore)
			winnerRecord = append(winnerRecord, token[0])
		}
	}

	winnerCnt := 0
	l := len(scoreRecord)
	winningScore := scoreRecord[l-1]
	for _, score := range scoreTable {
		if score == winningScore {
			winnerCnt += 1
		}
	}

	if winnerCnt > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore && scoreTable[winnerRecord[i]] == winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winnerRecord[l-1])
	}
}

package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d\n", &n)

	var (
		name  string
		score int
	)
	var (
		hashScore    map[string]int = make(map[string]int)
		currentScore int
		ok           bool

		maximumName  string
		maximumScore int
	)
	for i := 0; i < n; i++ {
		fmt.Scanf("%s %d\n", &name, &score)
		if score < 0 {
			continue
		}

		if currentScore, ok = hashScore[name]; !ok {
			currentScore = 0
		}

		currentScore += score
		hashScore[name] = currentScore

		if currentScore > maximumScore {
			maximumName = name
			maximumScore = currentScore
		}
	}
	fmt.Println(maximumName)
}

package main

import (
	"fmt"
)

type s1 struct {
	name  string
	score int
}

func main() {
	var n int
	fmt.Scanln(&n)

	scores := make(map[string]int)
	logs := make([]s1, n)
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Scanf("%s %d\n", &name, &score)
		scores[name] += score
		logs[i] = s1{name, scores[name]}
	}

	maxScore := 0
	for _, score := range scores {
		if score > maxScore {
			maxScore = score
		}
	}

	var winner string
	for _, log := range logs {
		if log.score >= maxScore {
			winner = log.name
			break
		}
	}

	fmt.Println(winner)
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		scoreRecord = append(scoreRecord, scoreTable[token[0]])
		winnerRecord = append(winnerRecord, token[0])
	}

	l := len(scoreRecord)
	var winner string
	scorerCnt := map[int]int{}
	winningScore := -1
	for name, score := range scoreTable {
		if score > winningScore {
			winner = name
			winningScore = score
			scorerCnt[score] += 1
		}
	}

	if scorerCnt[winningScore] > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore && scoreTable[winnerRecord[i]] == winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winner)
	}
}

package main

import "fmt"

func main() {
    var n,a int
    var s string
    score := make(map[string]int)
    last := make(map[string]int)
    fmt.Scan(&n)
    for i := 0; i < n; i++ {
        fmt.Scan(&s,&a)
        score[s] += a
        last[s] = i
    }
    max, in, winner := -1001, 1001, ""
    for k, v := range score {
        if (max < v) || ((max == v) && (last[k] < in)) {
            max = v
            in = last[k]
            winner = k
        }
    }
    fmt.Println(winner)
}

package main

import (
	"fmt"
)

func main() {
	var roundCount int
	fmt.Scanln(&roundCount)
	rounds := make([]map[string]int, roundCount+1)
	for i := 1; i <= roundCount; i++ {
		rounds[i] = make(map[string]int)
		for k, v := range rounds[i-1] {
			rounds[i][k] = v
		}
		var name string
		var score int
		fmt.Scanf("%s %d", &name, &score)
		rounds[i][name] += score
	}
	var winners []string
	var m int
	for k, v := range rounds[roundCount] {
		switch {
		case v > m:
			winners = []string{k}
			m = v
		case v == m:
			winners = append(winners, k)
		}
	}
	var winner string
	if len(winners) > 1 {
		for i := 1; i <= roundCount; i++ {
			for k, v := range rounds[i] {
				if v == m {
					winner = k
					break
				}
			}
			if winner != "" {
				break
			}
		}
	} else {
		winner = winners[0]
	}
	fmt.Println(winner)
}

package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	var rounds []map[string]int16
	for i := 0; i < n; i++ {
		var name string
		var score int16
		fmt.Scan(&name, &score)
		m := make(map[string]int16)
		if i != 0 {
			for k, v := range rounds[i-1] {
				m[k] = v
			}
		}
		m[name] = m[name] + score
		rounds = append(rounds, m)
	}
	var max int16
	for _, v := range rounds[n-1] {
		if v > max {
			max = v
		}
	}
	for _, r := range rounds {
		for k, v := range r {
			if v == max {
				fmt.Print(k)
				return
			}
		}
	}
}

package main

import (
	"container/heap"
	"fmt"
)

type Item struct {
	name  string
	score int
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int           { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool { return pq[i].score > pq[j].score }
func (pq PriorityQueue) Swap(i, j int)      { pq[i], pq[j] = pq[j], pq[i] }

func (pq *PriorityQueue) Push(x interface{}) {
	*pq = append(*pq, x.(*Item))
}

func (pq *PriorityQueue) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n - 1]
	*pq = old[0 : n - 1]
	return item
}

func (pq *PriorityQueue) update(name string, score int) {
	n := -1

	for i, v := range *pq {
		if v.name == name {
			v.score += score
			n = i
			break
		}
	}

	item := Item{name, score}

	if n == -1 {
		heap.Push(pq, &item)
	} else {
		heap.Fix(pq, n)
	}
}

func main() {
	var n int
	fmt.Scanf("%d", &n)
	var pq PriorityQueue
	heap.Init(&pq)

	for ; n > 0; n-- {
		var name string
		var score int
		fmt.Scanf("%s %d", &name, &score)
		pq.update(name, score)
	}

	fmt.Println(pq[0].name)
}

// https://codeforces.com/contest/2/problem/A
package main

import (
	"fmt"
	"bufio"
	"os"
)

// (c) Dmitriy Blokhin (sv.dblokhin@gmail.com)

func main () {
	var (
		n int
	)

	//f, _ := os.Open("input.txt")
	//input := bufio.NewReader(f)
	input := bufio.NewReader(os.Stdin)
	fmt.Fscan(input, &n)
	sum := make(map[string]int)
	hist := make(map[string][]int)
	wins := make(map[int][]string)
	max := 0
	for i := 0; i < n; i++ {
		var name string
		var score int
		fmt.Fscanf(input, "%s %d\n", &name, &score)
		if len(hist[name]) == 0 {
			hist[name] = append(hist[name], 0)
		}
		hist[name] = append(hist[name], score)
		sum[name] += score
		if  sum[name] >= max {
			max = sum[name]
			wins[max] = append(wins[max], name)
		}
	}

	if len(wins[max]) == 1 {
		fmt.Println(wins[max][0])
	} else {
		i := 0
		winners := wins[max]
		for true {
			for _, name := range winners {
				if i >= len(hist[name]) {
					continue
				}

				if hist[name][i] >= max {
					fmt.Print(name)
					return
				}

				hist[name][i + 1] += hist[name][i]
			}
			i++
		}
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	highestScore := -1
	scoreTable := map[string]int{}

	lineReader := bufio.NewReader(os.Stdin)
	input, _ := lineReader.ReadString('\n')
	drop := 1
	if input[len(input)-2] == '\r' {
		drop = 2
	}
	n, _ := strconv.Atoi(input[:len(input)-drop])

	// winner changed record, record only whenever there is a change of winner
	winnerRecord := make([]string, n)
	scoreRecord := make([]int, n)

	var debug bool

	for i := 0; i < n; i++ {
		input, _ := lineReader.ReadString('\n')
		drop := 1
		if input[len(input)-2] == '\r' {
			drop = 2
		}
		line := input[:len(input)-drop]

		token := strings.Split(line, " ")

		if !debug && token[0] == "ys" {
			debug = true
		}
		if debug {
			if token[0] == "gczuitwphlv" {
				fmt.Printf("gc: %s\n", token[1])
			} else if token[0] == "mxcdbcgzfpgnfumhz" {
				fmt.Printf("mx: %s\n", token[1])
			}
		}
		roundScore, _ := strconv.Atoi(token[1])
		scoreTable[token[0]] += roundScore

		if scoreTable[token[0]] > highestScore {
			highestScore = scoreTable[token[0]]
			scoreRecord = append(scoreRecord, highestScore)
			winnerRecord = append(winnerRecord, token[0])
		}
	}

	winnerCnt := 0
	l := len(scoreRecord)
	winningScore := scoreRecord[l-1]
	for _, score := range scoreTable {
		if score == winningScore {
			winnerCnt += 1
		}
	}

	if winnerCnt > 1 {
		for i := 0; i < l; i++ {
			if scoreRecord[i] >= winningScore {
				fmt.Println(winnerRecord[i])
				break
			}
		}
	} else {
		fmt.Println(winnerRecord[l-1])
	}
}