Score changes arrive one at a time on a game leaderboard. The first line gives the number of events q, and each of the next q lines gives an event "name change" separated by one space. For each event, add the change to that name's score. A name seen for the first time starts at 0 points. The change may be 0 or negative, and scores may become negative too. Even with a change of 0, the name joins the leaderboard. After handling each event, print on one line the three leading people on the leaderboard as "name:score", separated by single spaces. A higher score leads; with equal scores, the name that comes first in dictionary order leads. Dictionary order compares the names character by character from the start, and the smaller character code (ASCII) comes first (digits come before lowercase letters); if one name is the beginning of the other, the shorter one comes first. If fewer than three people are on the leaderboard, print all of them.
Input
1 ≤ q ≤ 2000, −100 ≤ change ≤ 100 (integers). Names are 1 to 10 lowercase English letters or digits, with at most 100 different names
Output
q lines, each with at most three "name:score" entries, leader first
When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).
$ Ready
Open this on a computer to write and run code. On mobile you can read the problem and the solutions.
In other languagesShow solutions by language · 8 languages
Updating the map means "start from 0 if missing, then add". Languages differ in the one-liner and in what happens when you read a missing key. Python scores[name] += d raises KeyError for a new name, so use scores.get(name, 0) + d or defaultdict(int). JS Map.get returns undefined when missing, so undefined + 5 is NaN, silently (add ?? 0). Java scores.get(name) + d unboxes null into int and throws NullPointerException, so use merge(name, d, Integer::sum); C# scores[name] += d throws KeyNotFoundException, so read with TryGetValue (0 when missing). C++ scores[name] += d just works because [] creates a 0. Craykon stops when you read a missing key, so first do if (!scores.Contains(name)) { scores[name] = 0; } (만약 (!scores.있나(name)) { … }). C has no map, but with only 100 names you can search a name table in order and pick the leader three times. For the ranking, iterate the map, collect (name, score) pairs and sort: Python sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[:3], Java comparingByValue().reversed().thenComparing(comparingByKey()), C# OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key), C++ partial_sort for just the first three. Two traps: sorting (score, name) with reverse=True also reverses names among ties, starting from z. A JS compare function that returns true/false like b[1] > a[1] never returns a negative number and sorts wrongly; return negative/0/positive as in b[1] - a[1].
Pythonmain.py · 13 lines
import syslines = sys.stdin.read().split("\n")q = int(lines[0])scores = {}out = []for line in lines[1:q + 1]: name, delta = line.split() scores[name] = scores.get(name, 0) + int(delta) # 처음 나온 이름은 0점부터 # 점수가 높은 사람 먼저, 같으면 이름 사전 순 top = sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[:3] out.append(" ".join(f"{n}:{s}" for n, s in top))print("\n".join(out))
JavaScriptmain.js · 13 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);const scores = new Map();const out = [];for (const line of lines.slice(1, q + 1)) { const [name, delta] = line.trim().split(" "); scores.set(name, (scores.get(name) ?? 0) + Number(delta)); // 없으면 undefined + 수 = NaN const top = [...scores.entries()] .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)) // 점수 높은 사람 먼저, 같으면 이름 순 .slice(0, 3); out.push(top.map(([n, s]) => `${n}:${s}`).join(" "));}console.log(out.join("\n"));
TypeScriptmain.ts · 14 lines
import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").split("\n");const q = Number(lines[0]);const scores = new Map<string, number>();const out: string[] = [];for (const line of lines.slice(1, q + 1)) { const [name, delta] = line.trim().split(" "); scores.set(name, (scores.get(name) ?? 0) + Number(delta)); // 없으면 undefined + 수 = NaN const top: [string, number][] = [...scores.entries()] .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)) // 점수 높은 사람 먼저, 같으면 이름 순 .slice(0, 3); out.push(top.map(([n, s]) => `${n}:${s}`).join(" "));}console.log(out.join("\n"));
JavaMain.java · 25 lines
import java.io.*;import java.util.*;public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int q = Integer.parseInt(br.readLine().trim()); Map<String, Integer> scores = new HashMap<>(); StringBuilder out = new StringBuilder(); Comparator<Map.Entry<String, Integer>> order = Map.Entry.<String, Integer>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()); for (int i = 0; i < q; i++) { String[] p = br.readLine().trim().split(" "); scores.merge(p[0], Integer.parseInt(p[1]), Integer::sum); // 없으면 그 값을, 있으면 더한 값을 넣는다 List<Map.Entry<String, Integer>> all = new ArrayList<>(scores.entrySet()); all.sort(order); StringJoiner sj = new StringJoiner(" "); for (int j = 0; j < Math.min(3, all.size()); j++) sj.add(all.get(j).getKey() + ":" + all.get(j).getValue()); out.append(sj).append('\n'); } System.out.print(out); }}
C#Main.cs · 28 lines
using System;using System.Collections.Generic;using System.Linq;using System.Text;class Program{ static void Main() { int q = int.Parse(Console.ReadLine().Trim()); var scores = new Dictionary<string, int>(); var sb = new StringBuilder(); for (int i = 0; i < q; i++) { string[] p = Console.ReadLine().Trim().Split(' '); scores.TryGetValue(p[0], out int now); // 없으면 now = 0 scores[p[0]] = now + int.Parse(p[1]); var top = scores .OrderByDescending(kv => kv.Value) .ThenBy(kv => kv.Key, StringComparer.Ordinal) .Take(3) .Select(kv => $"{kv.Key}:{kv.Value}"); sb.Append(string.Join(" ", top)).Append('\n'); } Console.Write(sb); }}
C++main.cpp · 29 lines
#include <algorithm>#include <iostream>#include <map>#include <string>#include <vector>int main() { int q; std::cin >> q; std::map<std::string, int> scores; std::string out; for (int i = 0; i < q; i++) { std::string name; int delta; std::cin >> name >> delta; scores[name] += delta; // 없는 열쇠는 []가 0으로 만들어 준다 std::vector<std::pair<std::string, int>> all(scores.begin(), scores.end()); // 셋만 필요하니 partial_sort로 앞 세 자리만 맞춘다 size_t k = std::min<size_t>(3, all.size()); std::partial_sort(all.begin(), all.begin() + k, all.end(), [](const auto& a, const auto& b) { if (a.second != b.second) return a.second > b.second; return a.first < b.first; }); for (size_t j = 0; j < k; j++) out += (j ? " " : "") + all[j].first + ":" + std::to_string(all[j].second); out += "\n"; } std::cout << out;}
Cmain.c · 46 lines
#include <stdio.h>#include <string.h>/* C에는 사전이 없다: 이름은 많아야 100개라 이름 표를 차례로 찾는다 */static char names[100][11];static int score[100];static int count = 0;/* i가 j보다 앞서야 하나: 점수가 높거나, 같으면 이름이 사전 순으로 앞선다 */static int before(int i, int j) { if (score[i] != score[j]) return score[i] > score[j]; return strcmp(names[i], names[j]) < 0;}int main(void) { int q; scanf("%d", &q); for (int e = 0; e < q; e++) { char name[11]; int delta, at = -1; scanf("%10s %d", name, &delta); for (int i = 0; i < count; i++) if (strcmp(names[i], name) == 0) { at = i; break; } if (at < 0) { /* 처음 나온 이름은 0점부터 */ at = count++; strcpy(names[at], name); score[at] = 0; } score[at] += delta; /* 세 번 돌며 아직 뽑지 않은 사람 중 가장 앞서는 사람을 고른다 */ int top[3], k = count < 3 ? count : 3; for (int t = 0; t < k; t++) { int best = -1; for (int i = 0; i < count; i++) { int used = 0; for (int u = 0; u < t; u++) used |= top[u] == i; if (!used && (best < 0 || before(i, best))) best = i; } top[t] = best; printf(t ? " %s:%d" : "%s:%d", names[best], score[best]); } printf("\n"); } return 0;}
Craykonmain.cray · 35 lines
q = Console.ReadLine().ToNumber();scores = Dict();for (e = 0; e < q; e++){ p = Console.ReadLine().Trim().Split(); name = p[0]; if (!scores.Contains(name)) { scores[name] = 0; // 없는 열쇠를 읽으면 멈추니 먼저 0점으로 넣는다 } scores[name] = scores[name] + p[1].ToNumber(); names = scores.Keys; names.Sort(앞선사람먼저); top = []; for (i = 0; i < names.Count && i < 3; i++) { top.Add(names[i] + ":" + scores[names[i]]); } Console.WriteLine(top.Join(" "));}// 점수가 높은 사람 먼저, 같으면 이름 사전 순앞선사람먼저(앞, 뒤){ if (scores[앞] != scores[뒤]) { return scores[뒤] - scores[앞]; } if (앞 < 뒤) { return -1; } return 1;}