题目 人口普查
某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过 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
代码
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std
;
int main()
{
const int present
= 2014*10000+9*100+6;
int n
;
cin
>> n
;
int valid
= 0;
string oldest_name
, youngest_name
;
int oldest_birth
= present
, youngest_birth
= 0;
for (int i
= 0; i
< n
; i
++)
{
int year
, month
, day
;
string name
;
cin
>> name
;
scanf("%d/%d/%d", &year
, &month
, &day
);
int birth
= year
* 10000 + month
* 100 + day
;
if (birth
<=present
&&birth
>=present
- 200 * 10000)
{
valid
++;
if (birth
<= oldest_birth
)
{
oldest_name
= name
;
oldest_birth
= birth
;
}
if (birth
>= youngest_birth
)
{
youngest_name
= name
;
youngest_birth
= birth
;
}
}
}
if (valid
== 0)
cout
<< valid
;
else
cout
<< valid
<< " " << oldest_name
<< " " << youngest_name
;
}
这个题就直接把日期变成一个八位数,前四位是年份,后四位是月份和日期,然后比较大小就行。
我用的scanf输入的年份月份和日期,理论上来说可以直接用,pta上直接跑也能过,但是我用的visual studio就非得在一开头加上下面这句,在#include前面加,才能不报错
#define _CRT_SECURE_NO_DEPRECATE