Seeking interval intersection

#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>

using namespace std;

struct region
{
    int left,right;
};

bool cmp(struct region &A,struct region &B)
{
    return A.left < B.left;
}

typedef pair<int,int> PII;

vector<PII> v;

int main()
{
    int n;
    int x,y;
    cin >> n;
    region r[1100];
    for (int i = 0; i < n; i ++ )
    {
        cin >> x >> y;
        r[i].left = x;
        r[i].right = y;
    }
    sort(r,r+n,cmp);
    int a = r[0].right;
    int b = r[0].left;
    for (int i = 1; i < n ; i ++ )
    {
        if(r[i].left <= a)
        {
            a = min(a,r[i].right);
            b = max(b,r[i].left);
        }
        else
        {
            v.push_back({b,a});
            a = r[i].right;
            b = r[i].left;
        }
    }
    v.push_back({b,a});
    for (auto x : v)
    {
        cout << x.first << " " << x.second << endl;
    }
    return 0;
}

Released five original articles · won praise 21 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_43134194/article/details/104028918