人因梦想而伟大,又因坚持梦想而成长。|

TomLove

园龄:1年10个月粉丝:1关注:1

贪心分组问题

贪心区间分组

image-20240108155719885

image-20240108160346475

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int N = 100010;
int n;
struct Range{
int l, r;
bool operator< (const Range &W)const{
return l < W.l;
}
}range[N];
int main(){
scanf("%d", &n);
for(int i = 0; i < n; i++){
int l, r;
scanf("%d%d", &l, &r);
range[i] = {l, r};
}
sort(range, range + n);
priority_queue<int, vector<int>, greater<int>> heap; // 小根堆, 用来记录每个分组区间的最右侧端点
// 小根堆会自动对堆中的元素进行排序,小的放在堆顶 heap.top() 取得堆顶元素
// heap.pop() 弹出堆顶元素, 删除的意思
// heap.push(i) 向堆中插入元素 i
for(int i = 0; i < n; i++){
auto r = range[i];
if(heap.empty() || heap.top() >= r.l) heap.push(r.r);
else{
heap.pop();
heap.push(r.r);
}
}
printf("%d", heap.size());
return 0;
}

本文作者:TomLove

本文链接:https://www.cnblogs.com/tomlove/p/17952835

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   TomLove  阅读(14)  评论(0编辑  收藏  举报
   
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起