算法基础-区间合并 AcWing 803
作者:
gzcoder
,
2021-10-24 13:44:23
,
所有人可见
,
阅读 199
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
void merge(vector<PII> &segs)
{
vector<PII> res;
//注意一定要先将区间排序,PII排序首先排序first再排序second
sort(segs.begin(), segs.end());
int st = -2e9, ed = -2e9;//维护的当前区间,题目范围是(-1e9,1e9) 所以初始化为(-2e9,-e29)
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);//seg.second有可能比ed小
if (st != -2e9) res.push_back({st, ed});//循环退出后最后一个区间还未加入res,并且判断st防止segs中没有区间
segs = res;
}
int main()
{
int n;
scanf("%d", &n);
vector<PII> segs;
for (int i = 0; i < n; i ++ )
{
int l, r;
scanf("%d%d", &l, &r);
segs.push_back({l, r});
}
merge(segs);
cout << segs.size() << endl;
return 0;
}