一个较短的写法
思路都在注释里了
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef pair<int, int> PII;
vector<PII> a;
int n, res, l, r;
int main(){
cin >> n;
for (int i = 0; i < n; ++i) {
scanf("%d%d", &l, &r);
a.push_back({l, r});
}
sort(a.begin(), a.end());
int pre = a.begin()->second; //只需要记录前一个区间的右端点
for (vector<PII>::iterator it = a.begin(); it != a.end(); ++it) { //原始的迭代器方式遍历
if (it->first > pre) res++; //如果和后一个区间不相交,那么就答案+1
pre = max(pre, it->second); //不管相交不相交,都更新一次
}
cout << res + 1 << endl; //第一次计算的区间本身没有计入,所以加一(每次计入的是后一个不相连的区间)
return 0;
}