题目描述
cjf 君想调查学校 OI 组每个同学的生日,并按照年龄从大到小的顺序排序。但 cjf 君最近作业很多,没有时间,所以请你帮她排序。
输入格式
输入共有 n + 1 n + 1 n+1 行,
第 1 1 1 行为 OI 组总人数 n n n;
第 2 2 2 行至第 n + 1 n+1 n+1 行分别是每人的姓名 s s s、出生年 y y y、月 m m m、日 d d d。
输出格式
输出共有 n n n 行,
即 n n n 个生日从大到小同学的姓名。(如果有两个同学生日相同,输入靠后的同学先输出)
样例 #1
样例输入 #1
3
Yangchu 1992 4 23
Qiujingya 1993 10 13
Luowen 1991 8 1
样例输出 #1
Luowen
Yangchu
Qiujingya
提示
数据保证, 1 < n < 100 1<n<100 1<n<100, 1 ≤ ∣ s ∣ < 20 1\leq |s|<20 1≤∣s∣<20。保证年月日实际存在,且年份 ∈ [ 1960 , 2020 ] \in [1960,2020] ∈[1960,2020]。
解析
一、主要思路
将年月日转换为一个数字,这样就无需多重比较了。比如2000 12 30,用statis变量统计为20001230,这样直接比较比较方便。
二、代码
这里用了两种排序方法
1、冒泡排序
#include <iostream>
using namespace std;
class Student{
public:
string name;
int year;
int month;
int day;
int statis;
};
int main(){
int n;
cin >> n;
Student stu[n+5];
for(int i = 0; i < n; i ++){
cin >> stu[i].name >> stu[i].year >> stu[i].month >> stu[i].day;
stu[i].statis = stu[i].year*10000 + stu[i].month*100 + stu[i].day;
}
//冒泡排序重点代码
for(int i = 0; i < n-1; i ++){
for(int j = n-1; j > i; j --){
if(stu[j-1].statis >= stu[j].statis){
swap(stu[j], stu[j-1]);
}
}
}
for(int i = 0; i < n; i ++){
cout << stu[i].name << endl;
}
}
2、直接插入排序
#include <iostream>
using namespace std;
class Student{
public:
string name;
int year;
int month;
int day;
int statis;
};
int main(){
int n;
cin >> n;
Student stu[n+5];
for(int i = 0; i < n; i ++){
cin >> stu[i].name >> stu[i].year >> stu[i].month >> stu[i].day;
stu[i].statis = stu[i].year*10000 + stu[i].month*100 + stu[i].day;
}
Student p;
//从小排到大,直接插入排序
for(int i = 1; i < n; i ++){
if(stu[i].statis <= stu[i - 1].statis){
p = stu[i];
int j = 0;
for(j = i - 1; stu[j].statis >= p.statis; j --){
stu[j+1] = stu[j];
}
stu[j+1] = p;
}
}
for(int i = 0; i < n; i ++){
cout << stu[i].name << endl;
}
}
三、注意点
重点注意:如果有两个同学生日相同,输入靠后的同学先输出。