AcWing 906. 區間分組(模板題)

題目鏈接:點擊這裏

在這裏插入圖片描述

貪心策略:

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章