活动选择

D14554. 活动选择

时间限制1.0s   内存限制256.0MB   代码提交间隔1分钟(现在可以提交)  

输入文件名:test.in   输出文件名:test.out

问题描述

  假设有一个需要使用某一资源的n个活动组成的集合S,S={1,…,n}。该资源一次只能被一个活动所占用,每一个活动有一个开始时间bi和结束时间ei(bi<=ei)。若bi>ej或者bj>ei,则活动兼容。
  你的任务是:选择由互相兼容的活动组成的最大集合中元素的个数。

输入格式

  共n+1行,其中第1行为n,第2行到第n+1行表示n个活动的开始时间和结束时间(中间用空格隔开),格式为:
  n
  b1 e1
  ……
  bn en
  (注:所有数据不超过整型)

输出格式

  一个整数,表示可以兼容活动的最大个数。

样例输入

11
3 5
1 4
12 14
8 12
0 6
8 11
6 10
5 7
3 8
5 9
2 13

样例输出

4

思路:

各个区间不能重叠。

贪心策略:

按照结束时间排序,记录当前最后结束时间,判断第i区间是否可以选中,若可以修改最大结束时间的值,ans+1,反之不理它。

证明:

当前有第一个区间和第i个区间,如若两者不冲突,都可以选中,自然能多选,反之第一个区间结束时间更早,影响后续选择的可能就小,如此必选靠前的区间。
实现时使用pair定义结构体,排序时可以默认优先级。

Code:

#include<bits/stdc++.h>

#define e first

#define b second

 

using namespace std;

 

int n, ans = 0;

pair <int, int> act[100010];

 

int main(){

       freopen("test.in","r",stdin);

       freopen("test.out","w",stdout);

       cin >> n;

       for (int i = 1; i <= n; i++)

              cin >> act[i].b >> act[i].e;

       sort(act + 1, act + n + 1);

       int last = 0;

       for (int i = 1; i <= n; i++) {

              if (act[i].b > last) {

                     ans++;

                     last = act[i].e;

              }/冲突性判断

       }

       cout << ans << endl;

       return 0;

}
原文地址:https://www.cnblogs.com/sun915/p/9494077.html