知识概览
区间合并使用贪心算法,对于区间问题,通常需要对左端点排序、右端点排序或者左端点和右端点双关键字排序。
区间合并算法的算法步骤:
1. 按照区间左端点排序。
2. 扫描过程中,每次维护一个当前的区间。
例题展示
题目链接
https://www.acwing.com/problem/content/805/
代码
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int, int> PII;
int n;
vector<PII> segs;
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(ed, seg.second);
if (st != -2e9) res.push_back({st, ed});
segs = res;
}
int main()
{
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;
}
参考资料
- AcWing算法基础课