(贪心)acwing 905. 区间选点

905. 区间选点

题目链接https://www.acwing.com/problem/content/907/
题目:
(贪心)acwing 905. 区间选点_第1张图片
思路:按照右区间升序排序,然后每次选区间的右端点,如果r<新区间的左端点,就ans++,r=新区间的右端点。因为已经按右端点排序,所以新区间的右端点一定在旧的右边

#include
#include
#include
#include
#include
using namespace std;
typedef pair<int ,int>PII;
PII p[100010];
int main(){
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        scanf("%d%d",&p[i].second,&p[i].first);

    }
    sort(p,p+n);

    int ans=0,r=-1e9-10;
    for(int i=0;i<n;i++){
        if(r<p[i].second){
            ans++;
            r=p[i].first;
        }
    }
    cout<<ans;
    return 0;
}

你可能感兴趣的:(AcWing,算法,贪心算法)