给定 n 个区间 [li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3] 和 [2,6] 可以合并为一个区间 [1,6]。
输入格式
第一行包含整数 n。
接下来 n 行,每行包含两个整数 l 和 r。
输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。
数据范围
1≤n≤100000;
−109≤li≤ri≤109;
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef pair<int, int> PII;
vector<PII> all;
int n;
void merge(vector<PII> &all)
{
vector<PII> res;
sort(all.begin(), all.end()); //注:要先对区间进行从小到大的排序
int sta = -2e9, end = -2e9; //sta与end分别表示维护区间的起始点
for (auto a: all) {
if (end < a.first) { //当前维护的区间的终点小于下一区间的起点,则说明这两区间无法合并了,可将当前区间进行存入
if (sta != -2e9) res.push_back({ sta,end }); //存入时应注意是否是初始区间
sta = a.first; //更新维护的区间
end = a.second;
}
else end = max(end, a.second); //若当前维护的区间与下一区间有交集,更新终点,也就是合并两个区间
}
if (sta != -2e9) res.push_back({ sta,end }); //存入最后一个区间
all = res; //将合并后的区间进行覆盖
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
all.push_back({ a,b });
}
merge(all);
cout << all.size() << endl;
}