I was solving a problem, QuestionsLink, where we are given a name along with an integer. You have to print three names with the maximum integer values.
So, I converted the number to a string and concatenated it before the names. After sorting I was getting desired results. But it failed some test cases which made me curious about how the sort function in c++ works.
Here is my code:
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main() {
ll n;
cin >> n;
string names[n];
int arr[n], digits[n];
for (int i = 0; i < n; i++) {
cin >> names[i] >> arr[i];
names[i] = to_string(arr[i]) + names[i];
}
for (int i = 0; i < n; i++) {
digits[i] = floor(log10(arr[i]) + 1);
}
sort(names, names + n, greater<string>());
for (int i = 0; i < n; i++) {
cout << names[i] << endl;
}
/*for(int i=0;i<3;i++){
string s = names[i].substr(digits[i],names[i].length());
cout<<s<<endl;
}
cout<<digits[98];
*/
return 0;
}
Test cases:
9huDmy
995YnAYoAEE
990RUTM
96ipORo
956LNjFa
So, After sorting in descending order how is 9huDmy on top while the next two are sorted based on the digits in front of them.