区间合并
作者:
Oct_9
,
2024-04-07 20:03:37
,
所有人可见
,
阅读 6
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int, int> PII;
const int N = 100000 + 10;
vector<PII> segs;
int n;
void merge(vector<PII> &segs)
{
vector<PII> res;
sort(segs.begin(), segs.end()); //默认是按照左端点排序
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(seg.second, ed);
//加入最后一个区间
if (st != -2e9) res.push_back({st, ed});
segs = res;
}
int main()
{
cin >> n;
while (n --)
{
int l, r;
cin >> l >> r;
segs.push_back({l, r});
}
merge(segs);
cout << segs.size() << endl;
}