贪心5--活动选择

贪心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 } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值