Maximal Intersection Codeforces Round #506 Div. 3 贪心+暴力

You are given nn segments on a number line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide.

The intersection of a sequence of segments is such a maximal set of points (not necesserily having integer coordinates) that each point lies within every segment from the sequence. If the resulting set isn't empty, then it always forms some continuous segment. The length of the intersection is the length of the resulting segment or 00 in case the intersection is an empty set.

For example, the intersection of segments [1;5] and [3;10] is [3;5] (length 2), the intersection of segments [1;5] and [5;7]is [5;5](length 0) and the intersection of segments [1;5] and [6;6] is an empty set (length 0).

Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining (n−1)(n−1)segments has the maximal possible length.

Input

The first line contains a single integer nn (2≤n≤3⋅10^5) — the number of segments in the sequence.

Each of the next nn lines contains two integers lili and riri (0≤li≤ri≤10^9) — the description of the ii-th segment.

Output

Print a single integer — the maximal possible length of the intersection of (n−1) remaining segments after you remove exactly one segment from the sequence

把题意弄错了,想了好久……

题意删除一段区间,使得剩下的区间都相交的部分最大;

假设现在不删区间,所有区间都相交的部分长度一定是 R_{min}-L_{max} ;  L,R分别表示区间左右端点;

现在要删去一个,直接暴力枚举删哪个区间即可,剩下的区间求R_{min}-L_{max}

#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
#include<cstdio>
using namespace std;
typedef long long LL;
const int MOD=1e9+7;
const int maxn=1e5+7;
multiset<int> l,r;
vector<pair<int,int> > v;
int main()
{
    int n;
    scanf("%d",&n);
    int L,R;
    for(int i=0;i<n;++i)
    {
        scanf("%d%d",&L,&R);
        v.push_back(make_pair(L,R));
        l.insert(L);
        r.insert(R);
    }
    int ans=0;
    for(int i=0;i<n;++i)
    {
        l.erase(l.find(v[i].first));
        r.erase(r.find(v[i].second));
        ans=max(ans,*r.begin()-*l.rbegin());
        l.insert(v[i].first);
        r.insert(v[i].second);
    }
    cout<<ans<<endl;
}

猜你喜欢

转载自blog.csdn.net/codetypeman/article/details/82108998