【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?0?3?? 乱码了,好尴尬~   貌似是不超过2000 ), 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.

题意:

就是给出活动的个数,然后输入每个活动的开始时间和结束时间。一天有24个小时,问最多可以安排几个活动~

好离谱,我根本就没看到是啥地方举行活动。其实 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. 这句是最重要的。

分析:【贪心算法】

我觉得这道题是最简单的,或者说中规中矩~ 上学期算法学过活动安排问题,和这个一毛一样的。(所以说真的是课后题哈哈哈

贪心贪的是什么呢?贪心策略就是依次选择最早结束的活动。

所以先按照活动结束的早晚对活动进行排序,然后把排序后的第一个活动(所有活动中最早结束的活动)加入book数组。

这里的book数组存放的是被选中的活动。然后把下一个活动的开始时间与上一个被选中的活动的结束时间进行比较,如果不冲突,就将其加入book数组。循环整个活动直至最后一个活动。

由于所有活动都已经事先按照结束时间的早晚有序的排好,所以存于book数组中的活动也是按照时间的先后排序的。

最后,book数组中的元素个数即一天最大限度可以安排的活动个数,Bingo!

代码:

#include<iostream>
#include<algorithm>
using namespace std;
struct plan{
	string start,end;
}p[2001];
int cmp(plan a,plan b){
	return a.end<b.end;
}
int book[2001]={0};
int main(){
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>p[i].start>>p[i].end;
	}
	sort(p,p+n,cmp);
    book[0]=0;    //选中第1个活动 可以没有这个哦,因为已经初始化为0了,为了更方便理解,把这个加上了。
	int j=0;
	for(int i=1;i<n;i++){
		if(p[i].start>=p[book[j]].end)
			book[++j]=i;
	}
	printf("%d",j+1);	
	return 0;
}

真easy~   这道题我每一句代码都不是废话,虽然其他题写的每一句都是废话( 哭笑不得...

菜并不丢人,丢人的是我真是没想到坐在旁边的大佬是我们专业的第一名,我...我可真是社死极了,还好他提前走人了( 捂脸

猜你喜欢

转载自blog.csdn.net/WKX_5/article/details/114755296