您的位置:首页 > 其它

PAT乙级1028. 人口普查(20)

2017-12-14 01:42 363 查看

题目

链接https://www.patest.cn/contests/pat-b-practise/1028

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

这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过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型范围

有个测试点没有过,本来以为是 闰年、月份、天数超出范围,又加了上去,后来发现,是如果输入的都不符合,那么年长和年轻人的姓名就不用输出来了

代码

考虑 闰年、月份、天数范围

#include <iostream>
#include <vector>
#include <cstring>
#include <string>
using namespace std;

int main()
{
//freopen("in.txt" , "r" , stdin);//
int n;
cin>>n;
char a[10];//保存出生日期
string s1,s2;//保存最老和最年轻的人的名字
char name[10];
int old=20140906,young=18140906,cnt=0,age;
while(n--)
{
cin>>name;
cin>>a;
age=((a[0]-'0')*1000+(a[1]-'0')*100+(a[2]-'0')*10+(a[3]-'0'))*10000+((a[5]-'0')*10+(a[6]-'0'))*100+(a[8]-'0')*10+(a[9]-'0');
int year,month,day;
year=(a[0]-'0')*1000+(a[1]-'0')*100+(a[2]-'0')*10+(a[3]-'0');
month=(a[5]-'0')*10+(a[6]-'0');
day=(a[8]-'0')*10+(a[9]-'0');
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
if(day>31||day<1) continue;
if(month==4||month==6||month==9||month==11)
if(day>30||day<1) continue;
if(month==2)
{
if(year/4==0||year%100!=0)
if(day>29||day<1) continue;
else
if(day>28||day<1) continue;
}
if(age>=18140906&&age<=20140906&&month<=12&&month>=1)
{
if(age>young)
{s2=name;young=age;}
if(age<old)
{s1=name;old=age;}
cnt++;
}
}
cout<<cnt;
if(cnt!=0)
cout<<" "<<s1<<" "<<s2;
cout<<endl;
return 0;
}

不考虑 闰年、月份、天数范围

#include <iostream>
#include <vector>
#include <cstring>
#include <string>
using namespace std;

int main()
{
//freopen("in.txt" , "r" , stdin);//
int n;
cin>>n;
char a[10];//保存出生日期
string s1,s2;//保存最老和最年轻的人的名字
char name[10];
int old=20140906,young=18140906,cnt=0,age;
while(n--)
{
cin>>name;
cin>>a;
age=((a[0]-'0')*1000+(a[1]-'0')*100+(a[2]-'0')*10+(a[3]-'0'))*10000+((a[5]-'0')*10+(a[6]-'0'))*100+(a[8]-'0')*10+(a[9]-'0');
if(age>=18140906&&age<=20140906)
{
if(age>young)
{s2=name;young=age;}
if(age<old)
{s1=name;old=age;}
cnt++;
}
}
cout<<cnt;
if(cnt!=0)
cout<<" "<<s1<<" "<<s2;
cout<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: