算法-区间合并

题目

解题思路

注意add读完后要将最后一组st,ed存入res 

代码模板

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int N=1e5+10;
vector <pair<int,int>>add,res;
int n;

int main()
{
    int st=-2e9,ed=-2e9;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        int l,r;
        scanf("%d%d",&l,&r);
        add.push_back({l,r});
    }
    sort(add.begin(),add.end());
    for(auto item:add)
    {
        if(ed<item.first)
        {
            if(ed!=-2e9) res.push_back({st,ed});
            st=item.first,ed=item.second;
        }
        else if(ed<item.second)
        ed=item.second;
    }
    res.push_back({st,ed});
    printf("%d",res.size());
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xx_xb/article/details/132205260
今日推荐