題目鏈接:點擊這裏
貪心策略:
1.將所有區間按左端點從小到大排序
2.從前往後處理每個區間,判斷能否將其放到某個現有的組中
如果不存在這樣的組,則開新組,然後再將其放進去;
如果存在這樣的組,將其放進去,並更新當前組的Max_r
用一個小根堆維護最小的Max_r
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
using namespace std;
const int N = 100010;
struct Range
{
int l, r;
bool operator < (const Range &a) const
{
return l < a.l;
}
}range[N];
int main()
{
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i) scanf("%d%d", &range[i].l, &range[i].r);
sort(range, range + n);
priority_queue<int, vector<int>, greater<int>> heap;
for(int i = 0; i < n; ++i)
{
auto t = range[i];
if(heap.empty() || heap.top() >= t.l) // 開一個新組
{
heap.push(t.r);
}
else // 放到最小值的組裏
{
heap.pop();
heap.push(t.r);
}
}
printf("%d\n", heap.size());
return 0;
}