排序刷题10

题目来源:生日 - 洛谷

解题思路:这道题使用自定义的排序方法并用sort()函数就可以实现。需要注意的是输入生日的顺序也要考虑进去,不然得不到满分。

解题步骤:定义一个结构体peoples来存储每个同学的姓名、出生年月日以及输入顺序。使用自定义的比较函数cmp,首先根据年份、月份、日期从小到大进行排序,以确保年龄从大到小的顺序;对于生日完全相同的情况,通过比较输入顺序(order字段)的逆序来保证输入顺序靠后的同学在排序后排在前面

#include
#include

using namespace std;

struct peoples {

	string s;
	int y, m, d;
	// 用于稳定排序相同生日的学生
	int order;
}a[100];

// 比较函数,根据年月日从小到大排序,即年龄从大到小
bool cmp( peoples a,  peoples b) {
	if (a.y != b.y) return a.y < b.y;// 年份小的在前(年龄大)
	if (a.m != b.m) return a.m < b.m;// 月份小的在前
	if (a.d != b.d) return a.d < b.d;// 日期小的在前
	// 对于生日相同的情况,输入顺序靠后的排在前面
	return a.order > b.order;
}

int main()
{
	
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i].s >> a[i].y >> a[i].m >> a[i].d;
		// 记录输入顺序
		a[i].order = i;
	}
	// 根据出生日期进行排序
	sort(a, a + n, cmp);
	for (int i = 0; i < n; i++)
	{
		cout << a[i].s << endl;
	}
	return 0;
}

你可能感兴趣的:(排序,算法,数据结构,c++,排序算法,c语言)