贪心5--活动选择

一、心得

 

二、题目和分析

 

问题描述:

        有一个需要使用每个资源的n个活动组成的集合S= {a1,a2,···,an },资源每次只能由一个活动使用。每个活动a都有一个开始时间和结束时间,且 0<= s < f < 。一旦被选择后,活动a就占据半开时间区间[s,f]。如果[s,f]和[s,f]互不重叠,则称两个活动是兼容的。该问题就是要找出一个由互相兼容的活动组成的最大子集。

三、代码和结果

 输入

11

3 5

1 4

12 14

8 12

0 6

8 11

6 10

5 7

3 8

5 9

2 13



1 #include <iostream>
2 #include <algorithm>
3 using namespace std;
4 struct act{
5 int begin;
6 int end;
7 };
8
9 int mycmp(const act &a,const act &b){
10 return a.end<b.end;
11 }
12
13 //贪心,选最快结束就好
14 int main(){
15 freopen("in.txt","r",stdin);
16 int n;
17 cin>>n;
18 act a[1005];
19 for(int i=1;i<=n;i++){
20 cin>>a[i].begin>>a[i].end;
21 }
22 sort(a+1,a+n+1,mycmp);
23 cout<<"排序后的序列"<<endl;
24 for(int i=1;i<=n;i++){
25 cout<<a[i].begin<<" "<<a[i].end<<endl;
26 }
27 int total=0;
28 int begin=0;
29 for(int i=1;i<=n;i++){
30 if(a[i].begin>=begin){
31 total++;
32 begin=a[i].end;
33 }
34
35 }
36 cout<<"ans:"<<total<<endl;
37
38 return 0;
39 }


贪心5--活动选择_贪心


我的旨在学过的东西不再忘记(主要使用艾宾浩斯遗忘曲线算法及其它智能学习复习算法)的偏公益性质的完全免费的编程视频学习网站: ​​fanrenyi.com​​;有各种前端、后端、算法、大数据、人工智能等课程。

​版权申明:欢迎转载,但请注明出处​

一些博文中有一些参考内容因时间久远找不到来源了没有注明,如果侵权请联系我删除。

博主25岁,前端后端算法大数据人工智能都有兴趣。