Codeforces Round #506 (Div. 3) C. Maximal Intersection (枚举)

Posted willendless

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces Round #506 (Div. 3) C. Maximal Intersection (枚举)相关的知识,希望对你有一定的参考价值。

【题目描述】

You are given $n$ 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 $0$ in case the intersection is an empty set.
Your task is to remove exactly one segment from the given sequence in such a way that the intersection of the remaining $(n?1)$ segments has the maximal possible length.

【算法】

    预处理前后缀最大左区间和最小右区间,枚举remove的位置,取区间长度的最大值。复杂度O(n)。

【代码】

#include <bits/stdc++.h>
using namespace std;
int n,ans;
int a[300010][2],pre[300010][2],post[300010][2];
inline int read() {
    int x=0,f=1; char c=getchar();
    while(c<‘0‘||c>‘9‘) { if(c==‘-‘)f=-1; c=getchar(); }
    while(c>=‘0‘&&c<=‘9‘) { x=x*10+c-‘0‘; c=getchar(); }
    return x*f;
}
int main() {
    n=read(); post[n+1][1]=pre[0][1]=2e9;
    for(int i=1;i<=n;i++) a[i][0]=read(),a[i][1]=read();
    int max1=a[1][0],min1=a[1][1],max2=a[n][0],min2=a[n][1];
    for(int i=1;i<=n;i++) {
        max1=max(max1,a[i][0]),min1=min(min1,a[i][1]);
        max2=max(max2,a[n-i+1][0]),min2=min(min2,a[n-i+1][1]);
        pre[i][0]=max1,pre[i][1]=min1;
        post[n-i+1][0]=max2,post[n-i+1][1]=min2;
    }
    for(int i=1;i<=n;i++) {
        int l=max(pre[i-1][0],post[i+1][0]),r=min(pre[i-1][1],post[i+1][1]);
        ans=max(ans,r-l);
    }
    printf("%d
",ans);
    return 0;
}


以上是关于Codeforces Round #506 (Div. 3) C. Maximal Intersection (枚举)的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #506 (Div. 3)

Codeforces Round #506 (Div. 3) C. Maximal Intersection

Codeforces Round #506 (Div. 3) C. Maximal Intersection (枚举)

Codeforces Round #506 (Div. 3) D. Concatenated Multiples

Codeforces Round #506 (Div. 3) D-F

Codeforces Round #506 D. Concatenated Multiples题解