Nowadays, we have to keep a safe social distance to stop the spread of virus due to the COVID-19 outbreak. Consequently, the access to a national lab is highly restricted. Everyone has to submit a request for lab use in advance and is only allowed to enter after the request has been approved. Now given all the personal requests for the next day, you are supposed to make a feasible plan with the maximum possible number of requests approved. It is required that at most one person can stay in the lab at any particular time.
Input Specification:
Each input file contains one test case. Each case starts with a positive integer N (≤2×103 ), the number of lab access requests. Then N lines follow, each gives a request in the format:
hh:mm:ss hh:mm:ss
where hh:mm:ss represents the time point in a day by hour:minute:second, with the earliest time being 00:00:00 and the latest 23:59:59. For each request, the two time points are the requested entrance and exit time, respectively. It is guaranteed that the exit time is after the entrance time.
Note that all times will be within a single day. Times are recorded using a 24-hour clock.
Output Specification:
The output is supposed to give the total number of requests approved in your plan.
Sample Input:
7
18:00:01 23:07:01
04:09:59 11:30:08
11:35:50 13:00:00
23:45:00 23:55:50
13:00:00 17:11:22
06:30:50 11:42:01
17:30:00 23:50:00
结尾无空行
Sample Output:
5
结尾无空行
Hint:
All the requests can be approved except the last two.
题目分析:与时间有关的题目真的就那几个套路在一个时间戳上,使用贪心思想
,比较两个人哪个人结束时间早,谁早实验室就给谁用。
1. 题目给你的时间是乱的,你需要对时间重新排序,先按开始时间,再按结束时间。
2. 定义一个start和end,表示当前的实验室正在被使用的开始和结束时间,cnt用来表示答案。
3. 逐个人员进入,如果进入的人开始时间比end晚,则直接进入,并且更新cnt,start,end;如果进入的人开始时间比end早,且进入的人的结束时间也比end早,更新start,end。
注:时间可以转换为时间戳
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct node{
int start, end;
};
bool cmp(node n1, node n2){
if(n1.start != n2.start) return n1.start < n2.start;
else return n1.end < n2.end;
}
int main(){
int n;
scanf("%d", &n);
vector<node> v(n);
for(int i = 0; i < n; i ++){
int shh, smm, sss, ehh, emm, ess;
scanf("%d:%d:%d %d:%d:%d", &shh, &smm, &sss, &ehh, &emm, &ess);
v[i] = node{(shh * 60 + smm) * 60 + sss, (ehh * 60 + emm) * 60 + ess};
}
sort(v.begin(), v.end(), cmp);
int start = v[0].start, end = v[0].end;
int cnt = 1;
for(int i = 1; i < v.size(); i ++){
if(v[i].start >= end){//如果后面人的开始时间比前面人结束晚,直接进入并且更新开始和结束时间
cnt ++;
start = v[i].start;
end = v[i].end;
}else if(v[i].start <= end){//如果后面人的开始时间比前面人结束早
//判断后面人的结束时间是否比前面人早
if(v[i].end < end){//后面人进入,前面人退出
start = v[i].start;
end = v[i].end;
}
}
}
cout << cnt << endl;
return 0;
}