求助

P1104 生日

禹天钧2016 @ 2024-09-17 15:27:59

#include<bits/stdc++.h>
using namespace std;
int t,n;
struct q {
    string s;
    int n,y,r;
} a[100000];
int main() {
    cin>>n;
    for(int i=1; i<=n; i++)cin>>a[i].s>>a[i].n>>a[i].y>>a[i].r;
    for(int i=1;i<n;i++){
        for(int j=i;j<=n;j++){
            if(a[i].n>a[j].n)swap(a[i],a[j]);
            else if(a[i].y>a[j].y&&a[i].n==a[j].n)swap(a[i],a[j]);
            else if(a[i].r>a[j].r&&a[i].y==a[j].y)swap(a[i],a[j]);
            else if(a[i].r==a[j].r)swap(a[i],a[j]);
        }
    }
    for(int i=1; i<=n; i++)cout<<a[i].s<<"\n";
    return 0;
}

by manis @ 2024-09-17 15:49:04

@禹天钧2016
建议写一个cmp函数比较


by manis @ 2024-09-17 16:02:40

虽然用cmp代码偏长,但可读性更强。

#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define int long long

const int N = 100;
struct Node {
    string name;
    int year, month, day;
    int num;
} stu[N + 5];
int n;

bool cmp(Node x, Node y) {
    if (x.year != y.year) 
        return x.year < y.year;
    if (x.month != y.month)
        return x.month < y.month;
    if (x.day != y.day)
        return x.day < y.day;
    return x.num > y.num;
}

signed main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> stu[i].name;
        cin >> 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;
}

|