某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过 200 岁的老人,而今天是 2014 年 9 月 6 日,所以超过 200 岁的生日和未出生的生日都是不合理的,应该被过滤掉。
输入格式:
输入在第一行给出正整数 N,取值在(0,105];随后 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
分析:
其实是很简单的一道题,想不明白通过率为什么会这么低。这里要学会比较日期,我的代码里采用了最基础的方法,就是依次比较年月日。其实可以有更简洁的计算方法,换算成天数:
int Compare(node a, node b){
int x = 0;
x = (a.year - b.year) * 365 + (a.month - b.month) * 30 + (a.day - b.day);
if(x > 0) return 1;
else if(x == 0) return 0;
else return -1;
}
再就是注意C++中scanf,printf对string的处理。
//scanf
string s;
s.resize(5);
scanf("%s", &s[0]);
//printf
printf("%s", s.c_str());
还有结构体可以直接赋值,注意一下全是非法输入的特例。
#include<iostream>
using namespace std;
struct People{
int year;
int month;
int day;
string name;
};
int Compare(People a, People b){
if(a.year != b.year) return a.year - b.year;
else if(a.month != b.month) return a.month - b.month;
else return a.day - b.day;
}
int main(){
int N;
People old, young, temp;
int cnt = 0;
cin >> N;
temp.name.resize(5);
for(int i = 0; i < N; i++){
scanf("%s %d/%d/%d", &temp.name[0], &temp.year, &temp.month, &temp.day);
if(temp.year > 1814 || (temp.year == 1814 && temp.month > 9) || (temp.year == 1814 && temp.month == 9 && temp.day >= 6)){
if(temp.year < 2014 || (temp.year == 2014 && temp.month < 9) || (temp.year == 2014 && temp.month == 9 && temp.day <= 6)){
cnt++;
if(cnt == 1)
old = young = temp;
if(Compare(young, temp) < 0)
young = temp;
if(Compare(old, temp) > 0)
old = temp;
}
}
}
if(cnt) printf("%d %s %s", cnt, old.name.c_str(), young.name.c_str());
else printf("0");
}