PAT(甲级)2021年春季考试 7-2 Lab Access Scheduling (25 分) 区间贪心

PAT(甲级)2021年春季考试
7-2 Lab Access Scheduling (25 分) 区间贪心

【题目描述】
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×10 3), 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.

【解题思路】

区间贪心模板题。

我们使用结构体存储每个人开始和结束时间,按照结束时间从早到晚排序。从前往后遍历一遍,如果时间不重叠,贪心选择结束时间最早的即可。

【满分代码】

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct node
{
	int begin,end;
	bool operator < (const node b) const
	{
		return end<b.end;
	}
}p[2005];
int main()
{
	int n,h,m,s,ans=1;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d:%d:%d",&h,&m,&s);
		p[i].begin=h*3600+m*60+s;
		scanf("%d:%d:%d",&h,&m,&s);
		p[i].end=h*3600+m*60+s;
	}
	sort(p,p+n);
	//for(int i=0;i<n;i++)
	//	cout<<p[i].end<<endl;
	int sta=p[0].end;
	for(int i=1;i<n;i++)
	{
		if(p[i].begin>=sta)
		{
			ans++;
			sta=p[i].end;
		}
	}
	cout<<ans<<endl;
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

球王武磊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值