Challenge: Leaderboard
Completed
Read n players (name and score). Print them from highest score to lowest; ties in alphabetical order. Use sort with a comparator.
Input
Line 1: n. Then n lines name score.
Output
One line per player: name score.
Example
Input
4 Ravi 78 Asha 91 Meera 91 Zoya 85
Output
Asha 91 Meera 91 Zoya 85 Ravi 78
Editor
C++
Hints
Store pair<string, int>.
Comparator: different scores -> bigger first; same score -> smaller name first.
Solution explanation
The comparator decides the order; sort does the work in O(n log n).
Show solution
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<pair<string, int>> p(n);
for (auto& [name, score] : p) cin >> name >> score;
sort(p.begin(), p.end(), [](const pair<string, int>& a, const pair<string, int>& b) {
if (a.second != b.second) return a.second > b.second;
return a.first < b.first;
});
for (auto& [name, score] : p) cout << name << " " << score << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module