题目的链接:(https://pintia.cn/problem-sets/994805260223102976/problems/994805293282607104)
今天看到《算法笔记》上面这道题,觉得书上给的参考代码实在是太臃肿了,都不忍心读完。
书上的参考代码是这样的:
#include <cstdio>
struct person{
char name[10];
int yy,mm,dd;
}oldest,youngest,left,right,temp;
bool LessEqu(person a, person b){
if (a.yy!=b.yy) return a.yy<=b.yy;//既然a.yy不等于b.yy才执行后面语句,那么<=换成<从逻辑上说更好。
else if (a.mm!=b.mm) return a.mm<=b.mm;
else return a.dd<=b.dd;
}
bool MoreEqu(person a, person b){
if (a.yy!=b.yy) return a.yy>=b.yy;
else if (a.mm!=b.mm) return a.mm>=b.mm;
else return a.dd>=b.dd;
}
void init(){
youngest.yy=left.yy=1814;
oldest.yy=right.yy=2014;
youngest.mm=oldest.mm=left.mm=right.mm=9;
youngest.dd=oldest.dd=left.dd=right.dd=6;
}
int main(){
init();
int n,num=0;
scanf("%d",&n);
for (int i=0; i<n; i++){
scanf("%s %d/%d/%d",temp.name,&temp.yy,&temp.mm,&temp.dd);
if (MoreEqu(temp,left) && LessEqu(temp,right)){
num++;
if (LessEqu(temp,oldest)) oldest=temp;
if (MoreEqu(temp,youngest)) youngest=temp;
}
}
if (num==0) printf("0\n");
else printf("%d %s %s\n",num,oldest.name,youngest.name);
}
诚然,思路确实很简单,常规,但是太原始,对于这种不算很难的题目,竟然定义了四个函数,自造车轮写出比较日期大小的函数,甚至还有初始化函数赋一大堆值,感觉像是调试单片机,其实完全没有必要,对于这道题,添加一个cstring.h这个常用的头文件,就变得很简单了,一点也不难想。
20行代码方案:
#include <cstdio>
#include <cstring>
struct Person{
char name[10];
char birthDate[20];
}temp,oldest,youngest;
int main(){
int n,count=0;
scanf("%d",&n);
strcpy(oldest.birthDate,"2014/09/06\0");//日期上限
strcpy(youngest.birthDate,"1814/09/06\0");
for (int i=0; i<n; i++){
scanf("%s %s",temp.name,temp.birthDate);
if (strcmp(temp.birthDate,"1814/09/06")>=0 && strcmp("2014/09/06",temp.birthDate)>=0){
count++;
if (strcmp(oldest.birthDate,temp.birthDate)>0) oldest=temp;
if (strcmp(youngest.birthDate,temp.birthDate)<0) youngest=temp;
}
}
if (!count) printf("0");
else printf("%d %s %s",count,oldest.name,youngest.name);
}
用strcmp()来解决这道题,不仅代码量小,而且直观易懂,在测评的时候,耗时和占用空间方面都优于书上给的参考代码。