题解 | #成绩排序# 非常简单 一看就会
成绩排序
https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1
#include <iostream>
#include<string>
#include<algorithm>
using namespace std;
struct student{
string name;
int score;
int rank;
}stu[1000];
bool cmp1(student st1, student st2){
if(st1.score == st2.score ){
return st1.rank < st2.rank;
}else{
return st1.score > st2.score;
}
}
bool cmp2(student st1, student st2){
if(st1.score == st2.score ){
return st1.rank < st2.rank;
}else{
return st1.score < st2.score;
}
}
int main() {
//freopen("in.txt","r",stdin);
int n,k;
while(cin >> n >> k) { // 注意 while 处理多个 case
for(int i=0; i<n; i++){
cin >> stu[i].name ;//读入 name score rank 进入struct
cin >> stu[i].score;
stu[i].rank = i;//通过rank保证先输入的先输出
}
if(k==0){//cmp1
sort(stu, stu+n, cmp1);
}else{//cmp2
sort(stu, stu+n, cmp2);
}
for(int i=0; i<n; i++){//输出
cout << stu[i].name << " ";
cout << stu[i].score << endl;
}
}
}
查看14道真题和解析

