题意:
输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。
例示:
jack 70
peter 96
Tom 70
smith 67
从高到低 成绩
peter 96
jack 70
Tom 70
smith 67
从低到高
smith 67
jack 70
Tom 70
peter 96
注:0代表从高到低,1代表从低到高
方法一:
结构体稳定快排
思路:首先,定义一个结构体,包含用户和成绩;
重写升序和降序两个函数,
最后根据题意要求实现升序或降序的稳定排序。
#include <bits/stdc++.h>
using namespace std;
struct node{
string name;
int score;
}a[205];
bool cmp1(const node& x,const node& y){
return x.score<y.score;//成绩从小到大排序
}
bool cmp2(const node& x,const node& y){
return x.score>y.score;//成绩从大到小排序
}
int main(){
int n,m;
cin >> n >> m;
for(int i=0;i<n;i++){
cin >> a[i].name >> a[i].score;
}
if(m==1)
stable_sort(a,a+n,cmp1);
else
stable_sort(a,a+n,cmp2);
for(int i=0;i<n;i++){
cout << a[i].name << " " << a[i].score << endl;
}
return 0;
}
时间复杂度:
空间复杂度:![]()
方法二:
桶排序(稳定排序)
思路:桶排序,(即下标与数值的映射关系)。
因为成绩的区间在0到100,所以可以初始化101个桶。
遍历输入,之后根据题意要求实现升序或降序的输出即可。
#include <bits/stdc++.h>
using namespace std;
vector<string> a[105];
string name;
int score;
int main(){
int n,m;
cin >> n >> m;
for(int i=0;i<n;i++){
cin >> name >> score;
a[score].push_back(name);
}
if(m==0){//降序
for(int i=100;i>=0;i--){
for(int j=0;j<a[i].size();j++){
cout << a[i][j] << " " << i << endl;
}
}
}else{//升序
for(int i=0;i<=100;i++){
for(int j=0;j<a[i].size();j++){
cout << a[i][j] << " " << i << endl;
}
}
}
return 0;
}
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号