某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过 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
思路:
创建结构保体存居民的名字、出生日期。在录入信息时对年龄的合理性进行判断,合理则计数加一并登记在册,同时记录下合理年龄中年龄最大者与年龄最小者的位置。最后输出有效生日的个数、最年长人和最年轻人的姓名。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define INIT_SIZE 100
#define INCREMENT 100
typedef struct{
char name[6],birthday[11];
}resident;
typedef struct{
resident *elem;
int length,listsize;
}residentlist;
int main(){
resident *newbase;
residentlist L;
L.elem=(resident *)malloc(INIT_SIZE*sizeof(resident));
L.listsize=INIT_SIZE;
L.length=0;
int N;
scanf("%d",&N);
char temp_name[6],temp_birthday[11],t_year[9];
int thisyear=20140906;
int birthday,age;
int max=2000000,min=0;
int oldest=min,youngest=max;
int p_oldest=0,p_youngest=0;
for(int i=0;i<N;++i){
if(L.length>=L.listsize){
newbase= (resident *)realloc(L.elem,(L.listsize+INCREMENT)*sizeof(resident));
L.elem=newbase;
L.listsize+=INCREMENT;
}
scanf("%s %s",temp_name,temp_birthday);
for(int j=0,k=0;j<strlen(temp_birthday);++j){
if(temp_birthday[j]!='/'){
t_year[k++]=temp_birthday[j];
}
}
birthday=atoi(t_year);
age=thisyear-birthday;
if(age<=max&&age>=min){
if(age>oldest){
oldest=age;
p_oldest=L.length;
}
if(age<youngest){
youngest=age;
p_youngest=L.length;
}
strcpy(L.elem[L.length].name,temp_name);
strcpy(L.elem[L.length++].birthday,temp_birthday);
}
}
if(L.length>0){
printf("%d %s %s",L.length,L.elem[p_oldest].name,L.elem[p_youngest].name);
}
else{
printf("0");
}
return 0;
}