905. 区间选点(贪心)

905. 区间选点(贪心)

   分析:先按区间的右端点排序,然后从左到右遍历,当前区间左端点小于上一区间的右端点,总个数不变,否则总个数加一,并更新右端点

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

const int N = 100010;
struct Edge{int a, b;} edges[N];
bool operator < (Edge e1, Edge e2) {
    return e1.b < e2.b;
}
int n;
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);
    int res = 1, pre = edges[0].b;
    for(int i = 1; i < n; i++) {
        int a = edges[i].a, b = edges[i].b;
        if(a <= pre) {
            continue;
        }
        res++;
        pre = b;
    }
    printf("%d\n",res);
    return 0;
}

 

上一篇:Codeforces Round #656 (Div. 3)E. Directing Edges(拓扑排序+构造dag图)


下一篇:掌握魔法の东东 I