题解:P1104 生日

· · 题解

题意简化

按序给出学生姓名和出生年月日,要求按照生日(年龄)从大到小输出学生姓名,生日(年龄)相同则输入靠后的同学先输出。

做法

存储时,由于每个人对应有姓名、年、月、日和输入顺序的多个信息,我们可以用结构体捆绑这些信息。

struct student {
    string name;
    int year, month, day, num; //num 为输入顺序
} stu[105];

排序时,由于我们使用了结构体,所以可以用 sort 来进行排序。

sort(stu + 1, stu + n + 1, cmp); //cmp 的写法在下面

判断先后顺序时,我们先判断出生年,一样再判断月,还一样判断日,还一样判断输入顺序。

bool cmp(student a, student b) {
    if(a.year != b.year) return a.year < b.year;
    else if(a.month != b.month) return a.month < b.month;
    else if(a.day != b.day) return a.day < b.day;
    else return a.num > b.num;
}

最终,按序输出。

AC代码

#include <bits/stdc++.h>
using namespace std;

struct student {
    string name;
    int year, month, day, num;
} stu[105];

bool cmp(student a, student b) {
    if(a.year != b.year) return a.year < b.year;
    else if(a.month != b.month) return a.month < b.month;
    else if(a.day != b.day) return a.day < b.day;
    else return a.num > b.num;
}

int main() {
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> stu[i].name >> stu[i].year >> stu[i].month >> stu[i].day ;
        stu[i].num = i;
    }
    sort(stu + 1, stu + n + 1, cmp);
    for (int i = 1; i <= n; i++) cout << stu[i].name << endl;
    return 0;
}