活动选择问题

题目链接

Problem Description
sdut 大学生艺术中心每天都有n个活动申请举办,但是为了举办更多的活动,必须要放弃一些活动,求出每天最多能举办多少活动。


Input
输入包括多组输入,每组输入第一行为申请的活动数n(n<100),从第2行到n+1行,每行两个数,是每个活动的开始时间b,结束时间e


Output
输出每天最多能举办的活动数。


Sample Input
12
15 20
15 19
8 18
10 15
4 14
6 12
5 10
2 9
3 8
0 7
3 4
1 3

Sample Output
5

思路:
贪心法,先按照结束时间长短排序,然后遍历选择即可

 

AC代码:

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstdio>
 4 using namespace std;
 5 struct activity{
 6     int s,e;
 7     bool friend operator < (activity a,activity b){
 8         if(a.e == b.e)
 9             return a.s < b.s;
10         return a.e < b.e;
11     }
12     activity(int st = 0,int en = 0) : s(st),e(en){}
13 }act[105];
14 int main(){
15     int n,a,b,num,id;
16     while(~scanf("%d",&n)){
17         num = 1,id = 0; //第一个活动必选,所以num初始化为1,id表示选择到哪个活动
18         for(int i = 0;i < n;i++){
19             scanf("%d%d",&a,&b);
20             act[i] = activity(a,b);
21         }
22         sort(act,act + n);
23         for(int i = 1;i < n;i++)
24             if(act[i].s >= act[id].e){
25                 num++;
26                 id = i;
27             }
28         printf("%d\n",num);
29     }
30     return 0;
31 }
View Code

 

posted @ 2018-10-04 08:25  永不&言弃  阅读(127)  评论(0编辑  收藏  举报