Files
python/TangDou/AcWing/Section/905.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

37 lines
1.0 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
int n; // 线段数量
int res; // 结果
int ed = -INF; // 当前覆盖区间的结束边界,即右端点位置
// 结构体
struct Node {
int l, r;
// 按每个区间的右端点从小到大排序
const bool operator<(const Node &b) const {
return r < b.r;
}
} range[N];
int main() {
cin >> n;
// 注意这里的数组下标是从0开始的
for (int i = 0; i < n; i++) cin >> range[i].l >> range[i].r;
// 右端点从小到大排序,排序也需要从数组下标1开始
sort(range, range + n);
// 思想:① 所有区间按右端点从小到大排序
// ② 遍历每一个区间,如果当前区间的左与前一个区间的右有交集,则只需要一个点就可以覆盖掉两个区间
for (int i = 0; i < n; i++)
if (range[i].l > ed) {
res++;
ed = range[i].r;
}
cout << res << endl;
return 0;
}