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

37 lines
1.2 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;
// 注意这里的数组下标是从1开始的
for (int i = 1; i <= n; i++) cin >> range[i].l >> range[i].r;
// 右端点从小到大排序,排序也需要从数组下标1开始
sort(range + 1, range + n + 1);
// 思想:按右端点从小到大排序后,再遍历每一个区间,尽可能取右端点,如果中间出现中断现象,只能再多一个点
// 其实,每一个点都可能有多个选择,只要是多个区间的共同点即可,不是唯一点
for (int i = 1; i <= n; i++)
if (range[i].l > ed) {
res++;
ed = range[i].r;
}
cout << res << endl;
return 0;
}