1. 程式人生 > 實用技巧 >906. 區間分組(貪心)

906. 區間分組(貪心)

  分析:先將區間按左端點排序,然後建一個小堆存放以有組的右端點,然後遍歷區間,當堆為空或堆中最小的右端點都大於當前區間的左端點,

     則當前區間另分一組,否則就將當前區間劃分給堆中最小左端點的那個區間,並更新這個區間的右端點,最後返回堆的大小

#include <bits/stdc++.h>
using namespace std;

const int N = 100010;
int n;
struct Edge{int a, b;} edges[N];
bool operator <(Edge e1, Edge e2) {
    return e1.a < e2.a;
}

int main() { scanf("%d",&n); for(int i = 0; i < n; i++) { int a, b; scanf("%d%d",&a,&b); edges[i] = {a,b}; } sort(edges,edges+n); priority_queue<int,vector<int>,greater<int>> q; for(int i = 0; i < n; i++) { int
a = edges[i].a, b = edges[i].b; if(q.size() == 0 || q.top() >= a) { q.push(b); } else { q.pop(); q.push(b); } } printf("%d\n",q.size()); return 0; }