[贪心+优先队列]活动安排问题
题目
有若干个活动,第i个开始时间和结束时间是[Si,fi),同一个教室安排的活动之间不能交叠,求要安排所有活动,最少需要几个教室?
思路
最少需要几个教室,那么贪心让每个教室尽可能安排多的活动。依次按左端点和右端点从小到大排序。然后利用优先队列动态维护已有组里结束时间最早的,如果当前要加入的区间可以接到结束时间最早的组上,那就接上去并更新该端点。反之创建一个新的组
代码
#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
typedef long long LL;
typedef pair<int,int> PII;
/*DATA & KEY
n 1 1e4
t 0 1e9
1 2
2 9
3 4
*/
const int N=1e4+10;
struct Node
{
int l,r;
}a[N];
bool cmp(Node a,Node b)
{
if(a.l!=b.l)return a.l<b.l;
return a.r<b.r;
}
int main()
{
int n;cin>>n;
for(int i=1;i<=n;i++)cin>>a[i].l>>a[i].r;
sort(a+1,a+1+n,cmp);
int ans=0;
priority_queue<int,vector<int>,greater<int>>heap;
for(int i=1;i<=n;i++)
{
if(heap.empty())
{
ans++;heap.push(a[i].r);
}
else
{
if(heap.top()<=a[i].l)
{
heap.pop();heap.push(a[i].r);
}
else
{
ans++;heap.push(a[i].r);
}
}
}
cout<<ans<<endl;
return 0;
}
总结
对于最少使用几次这类贪心,考虑将每个载体或者操作的效果最大化。
区间问题一般考虑左右端点排序
优先队列与贪心结合的一个常规操作就是将当前要加入元素与堆顶元素做比较,根据比较结果决定是否替换堆顶元素