905. 区间选点 - AcWing题库

 
 
思路:就是将所有区间按照右端点排序, 然后选取一些区间的右端点
代码:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 100010;
typedef pair<int, int> PII;
vector<PII> arr;
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        int a_i, b_i;
        scanf("%d%d", &a_i, &b_i);
        arr.push_back({a_i, b_i});
    }
    sort(arr.begin(), arr.end());
    int redge = -2e9;
    int res = 0;
    for (vector<PII>::iterator i = arr.begin(); i != arr.end(); i++)
    {
        if (i->first > redge)
        {
            res++;
            redge = i->second;
        }
        else
        {
            redge = min(redge, i->second);
        }
    }
    printf("%d", res);
    return 0;
}类似题目:

 
 
这题一看就是和区间选点一模一样,
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 100010;
struct Range{
    int first;
    int second;
    bool operator<(Range& r){
        return second<r.second;
    }
};
typedef Range PII;
vector<PII> arr;
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
    {
        int a_i, b_i;
        scanf("%d%d", &a_i, &b_i);
        arr.push_back({a_i, b_i});
    }
    sort(arr.begin(), arr.end());
    //for(auto x:arr) cout<<x.first<<" "<<x.second<<endl;
    
    int redge = -2e9;
    int res = 0;
    for (vector<PII>::iterator i = arr.begin(); i != arr.end(); i++)
    {
        if (i->first > redge)
        {
            res++;
            redge = i->second;
            printf("%d ",redge);
        }
        else
        {
            redge = min(redge, i->second);
        }
    }
    printf("\n");
    return 0;
}



















