1028. 人口普查(20)
某城镇进行人口普查,得到了全体居民的生日。现请你写个程序,找出镇上最年长和最年轻的人。
这里确保每个输入的日期都是合法的,但不一定是合理的——假设已知镇上没有超过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 Joh n
//自己的方法:
#include <stdio.h> #include <stdlib.h> struct birthday{ char name[10]; int year; int month; int day; }; int main() { int number; int count=0; struct birthday max={"chen",3000,0,0},min={"cong",0,0,0},p; scanf("%d",&number); getchar(); for(int i=1;i<=number;i++){ scanf("%s",p.name); scanf("%d/%d/%d",&p.year,&p.month,&p.day); getchar(); if((p.year<1814||p.year==1814&&p.month<9||p.year==1814&&p.month==9&&p.day<6)||(p.year>2014||p.year==2014&&p.month>9||p.year==2014&&p.month==9&&p.day>6)) continue; else{ count++; if(p.year<max.year||p.year==max.year&&p.month<max.month||p.year==max.year&&p.month==max.month&&p.day<max.day) max=p; if(p.year>min.year||p.year==min.year&&p.month>min.month||p.year==min.year&&p.month==min.month&&p.day>min.day) min=p; } } printf("%d",count); if(count) printf(" %s %s\n",max.name,min.name); return 0; }
//他人的办法:
#include <stdio.h> #include <stdlib.h> int main() { char s[20],min[20]="0000/00/00",max[20]="3000/00/00"; char name[10],namemax[10],namemin[10]; int n; scanf("%d",&n); getchar(); int count=0; for(int i=1;i<=n;i++) { scanf("%s",name); scanf("%s",s); if((strcmp(s,"2014/09/06")>0)||(strcmp("1814/09/06",s)>0)) continue; else { count++; if(strcmp(s,min)>0){ strcpy(namemin,name); strcpy(min,s); } if(strcmp(s,max)<0){ strcpy(namemax,name); strcpy(max,s); } } } if(count) printf("%d %s %s\n",count,namemax,namemin); else printf("%d\n",0); return 0; }<pre name="code" class="html">
//由此可见,要活学活用,注意最好的方法,代码要精炼