一、区间合并
给定 n个区间 [li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3]和 [2,6]可以合并为一个区间 [1,6]。
输入格式
第一行包含整数 n。
接下来 n行,每行包含两个整数 l 和 r。
输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。
数据范围
1≤n≤100000,
−10^9≤li≤ri≤10^9
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int N=100010;
vector<pair<int,int>>segs;
void merge(vector<pair<int,int>>&segs){
vector<pair<int,int>>res;
sort(segs.begin(),segs.end());//pair优先左端点排序,再按右端点
int st=-2e9,ed=-2e9;//左右端点
for(auto seg:segs){
if(ed<seg.first){//更新区间
if(st!=-2e9)res.push_back({st,ed});
st=seg.first,ed=seg.second;
}else{//两个区间有交集 或者是包含 合并一下
ed=max(ed,seg.second);
}
}
if(st!=-2e9)res.push_back({st,ed});
segs=res;
}
//贪心
//1.按区间左端点排序(从小到大)
//2.扫描
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++){
int l,r;
cin>>l>>r;
segs.push_back({l,r});
}
//区间合并模板
merge(segs);
//返回区间个数
cout<<segs.size()<<endl;
return 0;
}