题目来源:PAT (Advanced Level) Practice
At the beginning of every day, the first person who signs in the computer room will unlock the door, and the last one who signs out will lock the door. Given the records of signing in's and out's, you are supposed to find the ones who have unlocked and locked the door on that day.
Input Specification:
Each input file contains one test case. Each case contains the records for one day. The case starts with a positive integer M, which is the total number of records, followed by M lines, each in the format:
ID_number Sign_in_time Sign_out_time
where times are given in the format HH:MM:SS
, and ID_number
is a string with no more than 15 characters.
Output Specification:
For each test case, output in one line the ID numbers of the persons who have unlocked and locked the door on that day. The two ID numbers must be separated by one space.
Note: It is guaranteed that the records are consistent. That is, the sign in time must be earlier than the sign out time for each person, and there are no two persons sign in or out at the same moment.
Sample Input:
3
CS301111 15:30:28 17:00:10
SC3021234 08:00:00 11:25:25
CS301133 21:45:00 21:58:40
Sample Output:
SC3021234 CS301133
words:
sign in 登录,进入 sign out 退出,离开 be supposed to 需要 positive integer 正整数 characters 字符 be separated by 以...分隔
consistent 一致的 guarantee 保证,担保
思路:
1. 本题的要求是在m条记录(每条记录由学生ID、进入时间、离开时间组成)中找出进入时间最早和离开时间最晚的学生 ID;
2. 为了便于比较进入和离开时间的早晚,学生的ID用字符串name来表示,进入和离开时间用整数start、end来表示(在输入时分别使用三个整数h,m,s来输入,然后转化(h*10000+m*100+s)为一个整数);
3.使用排序函数按开始时间start从早到晚排序得到最早进入教室的学生;再使用排序函数按结束时间end从晚到早排序得到最晚离开教室的学生;
#include <iostream>
using namespace std;
#include <algorithm>
#define N 10000
struct hms
{
string name; //学生ID
int start,end; //开始时间,结束时间
}p[N];
bool cmp1(hms x,hms y)
{
return x.start<y.start; //按开始时间从早到晚排序
}
bool cmp2(hms x,hms y)
{
return x.end>y.end; //按结束时间从晚到早排序
}
int main()
{
int n,i;
int h,m,s;
cin>>n;cin.ignore();
for(i=0;i<n;i++)
{
cin>>p[i].name;
scanf("%d:%d:%d",&h,&m,&s);p[i].start=h*10000+m*100+s;
scanf("%d:%d:%d",&h,&m,&s);p[i].end=h*10000+m*100+s;
}
sort(p,p+n,cmp1);
cout<<p[0].name<<" "; //最早进入
sort(p,p+n,cmp2);
cout<<p[0].name<<endl; //最晚离开
return 0;
}