2022-5-11 每日一题 NewCoder KY2 成绩排序
题目描述:
解题思路:
知识点总结:
- c++ 有string字符串类型,c 没有,所以string输入使用cin, 输出使用cout
- 数据范围未知时,不使用 全局变量
- 结构体尾括号处要加 分号;
- 排序规则-黄金法则:当比较函数返回为true时,表示比较函数的第一个参数 排在 第二个参数的 前面
解题分析:
根据输入的 排序方法不同,需要自定义两个比较函数 CompareAsc,CompareDesc
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct Student {
string name; //姓名 字符串类型string
int score; //成绩
int order; //录入次序
}; //结构体括号外要加 分号;
//升序
bool CompareAsc(Student x, Student y)
{
if (x.score == y.score) { //相同成绩,按次序在前排列
return x.order < y.order;
} else {
return x.score < y.score; //ture时,第一个参数x排在第二个参数y 之前
}
}
//降序
bool CompareDesc(Student x, Student y)
{
if (x.score == y.score) {
return x.order < y.order;
} else {
return x.score > y.score; //ture时,第一个参数x排在第二个参数y 之前
}
}
int main()
{
int n, r; //r 排序规则
while (scanf("%d%d", &n, &r) != EOF) {
Student stu[n]; //数据范围未知
for (int i = 0; i < n; ++i) {
cin >> stu[i].name >> stu[i].score; //string输入 使用cin
stu[i].order = i;
}
if (r == 0) {
sort(stu, stu + n, CompareDesc); //降序排
} else {
sort(stu, stu + n, CompareAsc); //升序排
}
for (int i = 0; i < n; ++ i) {
cout << stu[i].name << " " << stu[i].score << endl; //string输出 使用cout
}
}
return 0;
}