清华大学计算机考研复试上机题
成绩排序
本题要求获得成绩从高到低或从低到高的排列,相同成绩都按先录入排列在前的规则处理。这里我使用了一个id标识符,表示输入顺序。
#include <cstdio>
#include <algorithm>
using namespace std;
struct student {
char name[20];
int id; //输入顺序
int score;
};
bool cmp0(struct student a, struct student b) {
if (a.score != b.score) return a.score > b.score;
else return a.id < b.id; //相同成绩按先录入排列在前
}
bool cmp1(struct student a, struct student b) {
if (a.score != b.score) return a.score < b.score;
else return a.id < b.id; //相同成绩按先录入排列在前
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
int method;
scanf("%d", &method);
//getchar();
struct student std[n];
for (int i = 0; i < n; i++) {
std[i].id = i + 1;
scanf("%s%d", std[i].name, &std[i].score);
}
if (method) {
sort(std, std + n, cmp1); //升序
} else {
sort(std, std + n, cmp0); //降序
}
for (int i = 0; i < n; i++) {
printf(