Merge the intervals that have intersections (including endpoints)
802. Interval Sum - AcWing Question Bank
For example, now there is such a data
1 2
2 4
5 6
7 8
7 9
The final result of the merger is
1 —— 4
5 —— 6
7 —— 9
get three intervals
Step 1: Sort by the left endpoint of the interval
Step 2: Scan the entire interval (during scanning, merge intervals)
Maintain the current range, e.g.
- left endpoint:
st
- right endpoint:
ed
There are several situations
within the range
In this case, both st and ed不需要变化
Intersect
At this time 修改ed
, that is
no intersection
Because the left endpoint has been sorted from small to large, so the latter case will only be behind the purple point, and will not appear in the front
- Then put the st and ed at this point in the answer
- and update st and ed
resolve code
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
typedef pair <int , int > pii;
vector<pii> nums;
void merge(vector<pii> &nums){
vector<pii> res;
int st = -2e9 , ed = -2e9;
for(auto item : nums){
if(item.first > ed){
if(st != -2e9) res.push_back({
item.first , item.second});
st = item.first , ed = item.second;
}else{
ed = max(ed , item.second);
}
}
if(st != -2e9){
res.push_back({
st , ed});
}
nums = res;
}
int main(){
int n ;
cin >> n;
int l , r;
for(int i = 0 ; i <n ; i ++){
cin >> l >> r;
nums.push_back({
l , r});
}
sort(nums.begin() , nums.end());
merge(nums);
cout << nums.size();
return 0;
}
Use pair to store left and right endpoints
- first: left endpoint
- second: right endpoint
typedef pair <int , int > pii;
vector<pii> nums;
Interval merge template
When sorting, it is the default sort first, when first is equal, sort second
void merge(vector<pii> &nums){
vector<pii> res;
int st = -2e9 , ed = -2e9;
for(auto item : nums){
if(item.first > ed){
if(st != -2e9) res.push_back({
item.first , item.second});
st = item.first , ed = item.second;
}else{
ed = max(ed , item.second);
}
}
if(st != -2e9){
res.push_back({
st , ed});
}
nums = res;
}
-
Set the default value to 2e9, because the title defaults to 10 9
-
The current interval is strictly on the left of the maintenance interval
——(corresponding to the case of no intersection)
-
in the interval
(corresponding to intersection + interval)