P1104 生日

题目描述

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 1s<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;
	}
}

三、注意点

重点注意:如果有两个同学生日相同,输入靠后的同学先输出。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值