UVA Meeting Room Arrangement

来源:互联网 发布:知乎广州it培训机构 编辑:程序博客网 时间:2024/05/19 10:36

Problem Description
Faculty of Engineering of PSU has a large meeting room for faculty staff to organize events and meetings. The use of the meeting room must be reserved in advance. Since the meeting room is available in 10 hours per day and there may be several events that want to use the meeting room, the best usage policy is to maximize the number of events in day. Suppose that the meeting room is available from time 0 to 10 (10 hours). Given the list of start time and finish time of each candidate event, you are to write a program to select the events that fit in the meeting room (i.e. their times do not overlap) and give the maximum number of events in a day.
Input
The first line is a positive integer n (1 ≤ n ≤ 100) which determines the number of days (test cases). Each test case consists of the time of the candidate events (less than 20 events). Each event time includes 2 integers which are start time(s) and finish time(f), 0 ≤ s ≤ 9, 1 ≤ f ≤ 10 and s < f. The line containing ‘0 0’ indicates the end of each test case. Note that an event must use at least 1 hour.
Output
For each test case, print out the maximum number of events that can be arranged in the meeting room.
Sample Input
3
0 6
5 7
8 9
5 9
1 2
3 4
0 5
0 0
6 10
5 6
0 3
0 5
3 5
4 5
0 0
1 5
3 9
0 0
Sample Output
4 4 1
题意
会议室只能在0-10时内使用,有一些事情需要使用会议室,要求选择最好的策略在不干扰的情况下使用会议室的次数最多。
有n组测试数据,其中每组数据包括不超过20组的事件时间(开始时间和结束时间[s,e]),要求输出可以使用会议室的最大次数。
思路
涉及贪心算法,具体用一个结构体来记录区间,s代表开始时间,e代表结束时间,算法入门经典(刘汝佳)的232页有具体的分析,主要做法是先对结束时间从小打到排序,排序后e1 <= e2 <= e3…. 贪心策略一定要选第一个区间,可以分为2种情况讨论:
1: s1 > s2 这样第二个区间包含第一个区间,那么肯定不会选区间2,对于后面的区间[si, ei],
如果s1 > si 同样不会选这些区间。
2: 排除情况1,那么肯定有s1 <= s2 <= s3…. 这样区间2和区间1相比肯定选区间1,以此类推,肯定会选择区间1
选了区间1以后,只需要记录上一次选择区间的结束时间,排除相交的区间,循环一次完成贪心过程即可。

#include <iostream>#include <algorithm>#include <cstdio>using namespace std;struct aaa{    int s, e;}a[25];bool cmp(aaa b, aaa c){    return b.e < c.e;    //按照结束时间排序}int main(){    int t;    cin >> t;    while(t--)    {        int s1, e1, len = 0;        while(scanf("%d%d", &s1, &e1) && (s1 || e1))        {            a[len].s = s1,  a[len].e = e1;     //输入每个区间,记录开始时间和结束时间            len++;        }        sort(a, a + len, cmp);     //排序        int i, sum = 0;            //sum记录使用次数        if(len == 0) sum = 0;        else sum = 1;              //选择区间1,per记录前一个区间的结束时间        int pre = a[0].e;        for(i = 1; i < len; i++)        {            if(a[i].s >= pre)            {                sum++; pre = a[i].e;            }        }        printf("%d\n", sum);    }    return 0;}

练习网址:https://vjudge.net/problem/UVALive-6606

0 0
原创粉丝点击