问题描述
给定 n 个区间 [li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3] 和 [2,6] 可以合并为一个区间 [1,6]。
思路
- 创建结构体数组,读入数据,并排序结构体数组(以左端数值为关键字从小到大进行排序)
- 排序后有三种情况:
– 1、可以合并
– 2、可以合并
– 3、不能合并,当做两个区间处理 - 遍历数组
– 如果下一个区间的左端在上一个区间内,那么更新右端最大值,对应1、2情况
– 否则说明下一个区间的左端在上一个区间的右边,对应3情况
代码
#include <iostream>
#include <algorithm>
using namespace std;
const int N=1e5+10;
struct node
{
int l,r;
bool operator< (const node &a) const
{
return l<a.l;
}
}node[N];
int main()
{
int n;cin>>n;
for(int i=0;i<n;i++)
{
int l,r;
cin>>l>>r;
node[i]={l,r};
}
sort(node,node+n);
int res=1;
int maxn=node[0].r;
for(int i=1;i<n;i++)
{
if(node[i].l<=maxn) maxn=max(maxn,node[i].r);//如果下一个区间的左端在上一个区间内,那么更新右端最大值,对应1、2情况
else
{
res++;//说明下一个区间的左端在上一个区间的右边,对应3情况
maxn=node[i].r;
}
}
cout<<res<<endl;
return 0;
}
可以得到具体区间值的版本
需要注意的几点:
- 对vector < pair > 排序默认对第一个关键字排序
- 需要注意边界问题(在这里将l,r初始化为-2e9)
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int,int> pii;
vector<pii> segs,res;
int main()
{
int n;cin>>n;
while(n--)
{
int l,r;
cin>>l>>r;
segs.push_back({l,r});
}
sort(segs.begin(),segs.end());
int l=-2e9,r=-2e9;//初始化区间
for(auto seg:segs)
{
if(r<seg.first)//说明是两个不同区间
{
if(r!=-2e9) res.push_back({l,r});
l=seg.first,r=seg.second;
}
else if(r<seg.second)
{
r=seg.second;
}
}
if(r!=-2e9) res.push_back({l,r});
cout<<res.size();
return 0;
}