class Leaderboard {
public:
Leaderboard() {
}
void addScore(int playerId, int score) {
}
int top(int K) {
}
void reset(int playerId) {
}
};
/**
* Your Leaderboard object will be instantiated and called as such:
* Leaderboard* obj = new Leaderboard();
* obj->addScore(playerId,score);
* int param_2 = obj->top(K);
* obj->reset(playerId);
*/
class Leaderboard {
public:
unordered_map<int, int> id_score;
multiset<int> m;
Leaderboard() {
}
void addScore(int playerId, int score) {
if (id_score.find(playerId) == id_score.end())
{
id_score[playerId] = score;
m.insert(score);
}
else
{
int old_score = id_score[playerId];
id_score[playerId] += score;
m.erase(m.find(old_score));
m.insert(id_score[playerId]);
}
}
int top(int K) {
int res = 0;
int cnt = 0;
for (auto it = m.rbegin(); it != m.rend(); it ++) {
if (cnt == K)
break;
res += (*it);
cnt ++;
}
return res;
}
void reset(int playerId) {
int old_score = id_score[playerId];
id_score.erase(playerId);
m.erase(m.find(old_score));
}
};
/**
* Your Leaderboard object will be instantiated and called as such:
* Leaderboard* obj = new Leaderboard();
* obj->addScore(playerId,score);
* int param_2 = obj->top(K);
* obj->reset(playerId);
*/
/*
【平衡树】
*/
class Leaderboard {
TreeMap<Integer, Set<Integer>> map;
Map<Integer, Integer> playerScore;
public Leaderboard() {
map = new TreeMap<>((a, b) -> b - a);
playerScore = new HashMap<>();
}
public void addScore(int playerId, int score) {
int lastScore = playerScore.getOrDefault(playerId, 0);
playerScore.put(playerId, lastScore + score);
if (lastScore > 0) {
map.get(lastScore).remove(playerId);
}
if (!map.containsKey(lastScore + score)) map.put(lastScore + score, new HashSet<>());
map.get(lastScore + score).add(playerId);
}
public int top(int K) {
int res = 0;
for (int score : map.keySet()) {
res += score * Math.min(K, map.get(score).size());
K -= map.get(score).size();
if (K <= 0) return res;
}
return res;
}
public void reset(int playerId) {
map.get(playerScore.remove(playerId)).remove(playerId);
}
}
/**
* Your Leaderboard object will be instantiated and called as such:
* Leaderboard obj = new Leaderboard();
* obj.addScore(playerId,score);
* int param_2 = obj.top(K);
* obj.reset(playerId);
*/