牛客网计算机考研复试-KY2-成绩排序
题目链接:点这里
题目描述:
输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。
思路1:
对结构体排序,sort()是不稳定排序,stable_sort()是稳定排序,题目中要求用输出按照输入的顺序,应为稳定排序。时间复杂度O(n$\log_2n$)。

代码1:
#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;
}
思路2:使用Vector数组,时间复杂度是O(n),题目中是多组输入,记得每一次清空一下Vector数组。
代码2:
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<string> score[101];
string name;
int type,n,t;
while(cin >> n >> type){
for(int i=0;i<=100;i++)
score[i].clear();
while(n--){
cin >> name >> t;
score[t].push_back(name);
}
if(type==1){
for(int i=0;i<=100;i++){
if(score[i].size()!=0)
for(int j=0;j<score[i].size();j++)
cout << score[i][j] << " " << i << endl;
}
}
else{
for(int i=100;i>=0;i--){
if(score[i].size()!=0)
for(int j=0;j<score[i].size();j++)
cout << score[i][j] << " " << i << endl;
}
}
}
return 0;
}

浙公网安备 33010602011771号