区间合并

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int,int> PII;
vector<PII>a,b;
void merset(vector<PII>&a)
{
    
    int st=-2e9,ed=-2e9;
    for(auto c : a)//遍历a
    {
      if(ed>=c.first)
      {
        ed=max(ed,c.second);//两个区间有交集,合并
      }
      else {
      if(ed!=-2e9)b.push_back({st,ed});
      st=c.first;
      ed=c.second;
    }
    }
    if(ed!=-2e9)b.push_back({st,ed});//将最后一个区间放入b中
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        int l,r;
        cin>>l>>r;
        a.push_back({l,r});
    }
    sort(a.begin(),a.end());
    merset(a);
    cout<<b.size();
}

全部评论

相关推荐

07-15 11:35
门头沟学院 Java
心里踏实多了,可以安心准备论文了
看不见我ffgh:牛哇佬,要不要来试一试pdd,部门氛围很好
京东开奖153人在聊
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务