PROBLEM C
CLASSROOMS
The new semester is about to begin, and finding classrooms for orientation activities is always a headache.
There are k classrooms on campus and n proposed activities that need to be assigned a venue. Every proposed activity has specfic starting time si and ending time fi. Any such an activity should take place at one of the classrooms. Any of the k classrooms is big enough to hold any of the proposed activities, and each classroom can hold at most one activity at any time. No two proposed activities can take place at the same classroom at the same time. Even if two proposed activities overlap momentarily (the ending time of one activity equals the starting time another activity), they cannot be assigned to the same classroom.
There are so many proposed activities that there may not be enough classrooms to hold all the activities. It is desirable to have as many activities as possible. At most how many proposed activities can be assigned to the classrooms?
Input
- The first line contains two positive integers n and k (1≤k≤n≤200000 ), representing the number of proposed activities and number of classrooms, respectively.
- The following n lines each contains two positive integers: the ith line among these n lines contains si and fi (1≤si≤fi≤109), indicating the starting time and ending time of proposed activity i
Output
Output an integer indicating the maximum number proposed activities that can be scheduled.
Sample Input 1
4 2
1 4
2 9
4 7
5 8
Sample Output 1
3
题意
题意,n个活动,k个教室,给定每个活动开始和结束时间,在同一个教室举行的连续两个活动结束时间和开始时间之间必须有间隔。问最多能举办多少个活动。
贪心,把每个活动按结束时间排序,然后从头到尾扫一遍。
multiset里存放每个教室正在进行的活动的结束时间。
如果multiset里有某个教室的活动在活动i开始之前就结束的,活动i就可以举办,把原来的结束时间删掉,再把活动i的结束时间存进去。
如果multiset里没有比a[i].begin小的结束时间,即当前有活动的教室在活动i开始之前都结束不了活动,此时multiset里元素的数量表示有多少个教室在同时进行活动,如果还有空教室,活动i就可以在这个教室进行,把活动i的结束时间存入multiset。
注:实际存入multiset的是 (-a[i].ed-1),而查找时用的是(-a[i].begin)。因为要使用lower_bound函数,而lower_bound(start,end,k)返回的是集合里大于等于k的第一个数的下标,而题目里面要查找的是 比 开始时间 小的 第一个 结束时间,加个负号就刚好。
#include <algorithm>
#include <iostream>
#include <set>
#define N 200005
using namespace std;
int n , k;
struct node{
int bg,ed;
}a[N];
bool cmp(node a , node b){ //sort-cmp
if(a.ed== b.ed) return a.bg < b.bg;
return a.ed< b.ed;
}
int main(){
cin >> n >> k;
for (int i = 0 ; i < n ; ++i)
cin >> a[i].bg >> a[i].ed;
sort(a,a+n,cmp); //按照结束时间排序
multiset<int> endtime;
//multiset存放每个教室正在进行的活动的结束时间
endtime.clear();
int ans = 0; //活动个数
for (int i = 0 ; i < n ; i++){ //遍历每个活动
multiset<int> :: iterator iter;
iter = endtime.lower_bound(-a[i].bg);
//是否存在某个教室的活动在i开始时间前前就结束了
if (iter == endtime.end()){
//如果没有在活动i开始前就结束活动的教室,就另找一个教室
if (endtime.size() < k){
endtime.insert(-a[i].ed- 1);
ans++;
}
continue;
}
endtime.erase(iter);
//找到了某个教室活动已经结束了,活动i在这个教室进行
endtime.insert( - a[i].ed - 1);
//更新活动的结束时间
ans++;
}
cout << ans << endl;
return 0;
}
网友评论