题目链接(https://pintia.cn/problem-sets/994805342720868352/problems/994805516654460928)
今天看到《算法笔记》上面的PAT A1006的参考代码,觉得小题大作,和pat b1004和pat b1028用的是同一个套路,但我感觉这个套路并不好,虽然简单直观,但是很啰嗦臃肿。
本题书上的参考代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct pNode{
char id[20];
int hh,mm,ss;
}temp,ans1,ans2;
bool great(pNode node1, pNode node2){
if (node1.hh!=node2.hh) return node1.hh>node2.hh;
else if (node1.mm!=node2.mm) return node1.mm>node2.mm;
else return node1.ss>node2.ss;
}
int main(){
int n;
scanf("%d",&n);
ans1.hh=24, ans1.mm=60, ans1.ss=60;
ans2.hh=0, ans2.mm=0; ans2.ss=0;
for (int i=0; i<n; i++){
scanf("%s %d:%d:%d",temp.id,&temp.hh,&temp.mm,&temp.ss);
if (great(temp,ans1)==false) ans1=temp;
scanf("%d:%d:%d",&temp.hh,&temp.mm, &temp.ss);
if (great(temp,ans2)==true) ans2=temp;
}
printf("%s %s",ans1.id,ans2.id);
}
因为这个代码比较啰嗦,赋值都要半天,很容易出错,虽然思路简单,但实现繁琐,书上好几道题都是用和这道题完全一样的套路,说明这个套路有他可取的地方,例如大小比较那里的函数,在其他题里面就经常用到。但是这种题的套路完全可以被另一种更简洁的套路取代。即直接使用cstring,h里面的strcpy()和strcmp()这两个常见的函数。
另一种套路:
#include <cstdio>
#include <cstring>
int main(){
int m;
char lock[20],unlock[20],earliest[20]="23:59:59",latest[20]="00:00:00";
scanf("%d",&m);
for (int i=0; i<m; i++){
char id[20],sign_in[20],sign_out[20];
scanf("%s %s %s",id,sign_in,sign_out);
if (strcmp(earliest,sign_in)>0) {
strcpy(earliest,sign_in);
strcpy(unlock,id);
}
if (strcmp(latest,sign_out)<0){
strcpy(latest,sign_out);
strcpy(lock,id);
}
}
printf("%s %s",unlock,lock);
}
后一种套路更简洁,耗时更短(大部分都是1ms),占用内存更小,没有那么多结构体变量(赋值起来麻烦死了),不用自己写比较函数,strcmp()函数好好地躺在哪里,为什么还要闭门造车呢?等你把比较函数和初始化这些车造好了,别人代码都写完了。