其他分享
首页 > 其他分享> > 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;
}

 

标签:选点,905,int,scanf,edges,端点,区间,Edge,贪心
来源: https://www.cnblogs.com/yonezu/p/13563589.html