803. Range Merge

Given n intervals [li,ri], it is required to merge all intervals with intersection.

Note that if they intersect at the endpoints, there is also an intersection.

Output the number of intervals after merging is completed.

For example: [1,3] and [2,6] can be combined into an interval [1,6].

Input format
The first line contains the integer n.

The next n lines each contain two integers l and r.

Output Format
A total of one line, including an integer, indicates the number of intervals after the merge interval is completed.

Data range
1≤n≤100000,
−109≤li≤ri≤109
Input example:
5
1 2
2 4
5 6
7 8
7 9
Output example:
3


#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
vector<pair<int, int>> p;

void merge()
{
    
    
    vector<pair<int, int>> res;
    sort(p.begin(), p.end());
    
    int st = -2e9, end = -2e9;
    for(auto item : p) {
    
    
        if(end < item.first) {
    
    
            if(end != -2e9) res.push_back({
    
    st, end});
            st = item.first;
            end = item.second;
        }
        else end = max(end, item.second);
    }
    if(st != -2e9) res.push_back({
    
    st, end});
    p = res;
}

int main()
{
    
    
    int n;
    cin >> n;
    for(int i=0; i<n; i++) {
    
    
        int l, r;
        cin >> l >> r;
        p.push_back({
    
    l, r});
    }
    
    merge();
    
    cout << p.size() << endl;
    
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324120380&siteId=291194637