题目
给定 n 个区间 [li,ri],要求合并所有有交集的区间。
注意如果在端点处相交,也算有交集。
输出合并完成后的区间个数。
例如:[1,3] 和 [2,6] 可以合并为一个区间 [1,6]。
输入格式
第一行包含整数 n。
接下来 n 行,每行包含两个整数 l 和 r。
输出格式
共一行,包含一个整数,表示合并区间完成后的区间个数。
数据范围
1≤n≤100000,
−109≤li≤ri≤109
输入样例:
5
1 2
2 4
5 6
7 8
7 9
输出样例:
3
代码
// 先按照区间的左端点排序,然后从左往右遍历,然后分情况讨论
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int, int> PII;
int main()
{
int n;
cin >> n;
vector<PII> s;
while( n -- ){
int l, r;
cin >> l >> r;
s.push_back({l,r});
}
sort(s.begin(),s.end()); // 默认以s.first升序排序
int cnt = 1;
int st = s[0].first, ed = s[0].second;
for( auto t : s){
if(ed < t.first){
cnt ++ ;
st = t.first;
ed = t.second;
}
else if(ed < t.second) ed = t.second;
}
cout << cnt << endl;
return 0;
}
总结
这个题就比较简单了,排个序,遍历一下, 属于贪心的思想,这种区间的问题很多都是用贪心来做,正好我也想先做一下贪心的题目,再做第二章数据结构的题目。