- 注意使用stable sort,因为如果在没有指定 string 顺序的时候,sort排序方法是不稳定的。就算score相同,基于只关注我们要的进行比较就行的思想,他也会在相等时发生顺序改变,因此要用stable sort。vector 排序,只能sort!!!!!不要构造的时候发生变化。
#include<bits/stdc++.h>
using namespace std;
struct cmpu{
bool operator()(pair<string,int> a, pair<string,int> b){
return a.second < b.second;//如果只关注一种或比较,直接写这个
}
};
struct cmpd{
bool operator()(pair<string,int> a, pair<string,int> b){
return a.second > b.second;//如果只关注一种或比较,直接写这个
}
};
int main(){
int M;
int op;
vector<pair<string,int>> up;
vector<pair<string,int>> down;
while(cin>>M>>op){
up.clear();
down.clear();
string s; int score;
if(op==1){//升序
for(int i =0; i< M;i++){
cin>>s>>score;
up.push_back({s,score});
}
stable_sort(up.begin(),up.end(),cmpu());//因为要在score一样的情况下先后顺序不变,因此需要稳定排序
for(int i =0; i< M;i++){
cout<<up[i].first<<" "<<up[i].second<<endl;
}
}else{
for(int i =0; i< M;i++){
cin>>s>>score;
down.push_back({s,score});
}
stable_sort(down.begin(),down.end(),cmpd());//因为要在score一样的情况下先后顺序不变,因此需要稳定排序
for(int i =0; i< M;i++){
cout<<down[i].first<<" "<<down[i].second<<endl;
}
}
}
}