C++Server Side ProgrammingProgramming

Suppose we have to design a Leaderboard class, there are three different functions −

• addScore(playerId, score) − This will update the leaderboard by adding score to the given player's score. When there is no such player with given id in the leaderboard, add him to the leaderboard with the given score.
• top(K) − This will return the score sum of the top K players.
• reset(playerId) − This will reset the score of the player with the given id to 0. It is guaranteed that the player was added to the leaderboard before calling this function.

If we perform the operations like below −

• leaderboard.top(3); // returns 141 = 51 + 51 + 39;

To solve this, we will follow these steps −

• Define a priority queue of integer pairs called pq, make one map of int type keys and int type values m. For the initialization, it will clear the map, and if queue is not empty, delete all elements from the queue.
• The addScore() method will be like −
• if playerId is present, then m[playerId] := m[playerId] + score
• insert a pair (m[playerId], playerId) into pq
• otherwise m[playerId] = score
• The top() method will be like
• make a vector of pairs temp, set sum := 0
• while k is not 0
• curr := top of pq, delete from pq
• if m[second value of curr pair] = first value of curr pair
• decrease k by 1
• sum := sum + first value of curr
• insert curr into temp
• for i in range 0 to size of temp
• insert temp[i] into pq
• The reset() function will be like −
• m[playerId] = 0

Example(C++)

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
public:
priority_queue< pair <int,int> > pq;
map < int, int > m;
m.clear();
while(!pq.empty())pq.pop();
}
void addScore(int playerId, int score) {
if(m.find(playerId)!=m.end()){
m[playerId] += score;
}
else m[playerId] = score;;
pq.push({m[playerId], playerId});
}
int top(int k) {
vector < pair <int,int> > temp;
int sum = 0;
while(k){
pair <int, int> curr = pq.top();
pq.pop();
if(m[curr.second] == curr.first){
k--;
sum += curr.first;
temp.push_back(curr);
}
}
for(int i = 0; i < temp.size(); i++)pq.push(temp[i]);
return sum;
}
void reset(int playerId) {
m[playerId] = 0;
}
};
main(){
cout <<ob.top(1) << endl;
ob.reset(1);
ob.reset(2);