题目链接:点这里
思路:对结构体排序,sort()是不稳定排序,stable_sort()是稳定排序,题目中要求用输出按照输入的顺序,应为稳定排序。
代码:
#include <bits/stdc++.h>
using namespace std;
struct student{
string name;
int score;
}st[1000];
bool cmp1(student s1,student s2){
if(s1.score<s2.score)
return true;
return false;
}
bool cmp2(student s1,student s2){
if(s1.score>s2.score)
return true;
return false;
}
int main(){
int n,t;
while(cin >> n >> t){
for(int i=0;i<n;i++){
cin >> st[i].name >> st[i].score;
}
if(t==1)
stable_sort(st,st+n,cmp1);
else
stable_sort(st,st+n,cmp2);
for(int i=0;i<n;i++){
cout << st[i].name << " " << st[i].score << endl;
}
}
return 0;
}