AcWing 907. 区间覆盖 区间贪心

 

//1.将所有区间按照左端点从小到大排序
//2.从前往后依次枚举每个区间
//首先选择能够覆盖左端点的区间当中右端点最靠右的端点
//在所有能覆盖start的区间当中,选择右端点最大的区间
//选完之后将start更新成右端点的最大值
#include <iostream>
#include <algorithm>
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() {
    int st, ed;
    scanf("%d%d", &st, &ed);
    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);
    int res = 0;
    bool success = false;
    for (int i = 0; i < n; i ++ ) {
        int j = i, r = -2e9;
        //找所有左端点在start左边的区间右端点最大值是多少
        while (j < n && range[j].l <= st) {
            r = max(r, range[j].r);
            j ++ ;
        }
        if (r < st) {
            res = -1;
            break;
        }
        res ++ ;
        if (r >= ed) {
            success = true;
            break;
        }
        st = r;
        i = j - 1;
    }
    if (!success) res = -1;
    printf("%d\n", res);
    return 0;
}

 

posted @ 2019-11-22 03:32  晴屿  阅读(161)  评论(0编辑  收藏  举报