一二三四五 上山打老虎

NC24867-Selfish Grazing

题目链接:https://ac.nowcoder.com/acm/problem/24867

题意:给定n个区间,起始坐标分别是l~r,计算最多能选出多少个区间,使得这些区间两两互不相交,

思路:区间贪心,尽量选择更多的区间
思路一:总是选择左端点最大的区间使得此区间左边有更大的范围放置更多区间
思路二:总是选择右端点最小的区间使得此区间右侧有更大的范围

#include<iostream>
#include<algorithm>

using namespace std;
struct node{
    int l,r;
}a[(int)5e5+5];
bool cmp(struct node s,struct node t){
    return s.r<t.r;
}
int main (){
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>a[i].l>>a[i].r;
    sort(a,a+n,cmp);
    int res=0,ans=0;
    for(int i=0;i<n;i++){
        if(a[i].l>=res){
            ans++;
                res=a[i].r;
        }
    }
    cout<<ans<<endl;
    return 0;
}
posted @ 2021-01-26 16:57  黒川川  阅读(100)  评论(0)    收藏  举报