PAT_B 1028 人口普查

PAT_B 1028 人口普查

分析

按照题目要求进行模拟即可,min表示日期最小,max表示日期最大,每次对输入的数据进行判断与比较,针对所有输入均不合法的情况要特殊处理

题目的描述

某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。

这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过 200 岁的老人,而今天是 2014 年 9 月 6 日,所以超过 200 岁的生日和未出生的生日都是不合理的,应该被过滤掉。

输入格式:

输入在第一行给出正整数 N,取值在\((0,10^5]\);随后 N 行,每行给出 1 个人的姓名(由不超过 5 个英文字母组成的字符串)、以及按 yyyy/mm/dd(即年/月/日)格式给出的生日。题目保证最年长和最年轻的人没有并列。

输出格式:

在一行中顺序输出有效生日的个数、最年长人和最年轻人的姓名,其间以空格分隔。

输入样例:

5
John 2001/05/12
Tom 1814/09/06
Ann 2121/01/30
James 1814/09/05
Steve 1967/11/20

输出样例:

3 Tom John

AC的代码

#include<bits/stdc++.h>

using namespace std;
class age{
    public:
    string names;
    int year;
    int month;
    int day;
    age(){}
    age(string n,int y,int m,int d){
        names=n;
        year=y;
        month=m;
        day=d;
    }
    bool issmaller(age t){
        if(t.year==this->year){
            return 
                t.month==this->month ? t.day>this->day : t.month >this->month;
        }
        else{
            return t.year>this->year;
        }
    }
    bool islarger(age t){
        if(t.year==this->year){
            return 
                t.month==this->month ? t.day<this->day : t.month <this->month;
        }
        else{
            return t.year<this->year;
        }
    }

};
int main(){
    int N=0,c=0;
    age minlimit("",1814,9,6),maxlimit("",2014,9,6),maxage("",1814,9,6),minage("",2014,9,6);
    cin>>N;
    while(N--){
        string tname,tbirthday;
        cin>>tname>>tbirthday;
        age t(
            tname,
            stoi(tbirthday.substr(0,4)),
            stoi(tbirthday.substr(5,2)),
            stoi(tbirthday.substr(8,2))
        );
        if(!(t.issmaller(minlimit)||t.islarger(maxlimit))){
            c++;
            if(t.issmaller(minage)){
                minage=t;
            }
            if(t.islarger(maxage)){
                maxage=t;
            }
        }
    }
    if(c)cout<<c<<' '<<minage.names<<' '<<maxage.names<<endl;
    else cout<<c<<endl;
    return 0;
}
posted @ 2022-01-24 22:39  ghosteq  阅读(29)  评论(0编辑  收藏  举报