题目链接
http://codeforces.com/problemset/problem/1029/C
题意
给定n个段,要求删掉一个段,使得剩下的n-1个段的交集最大。
[1;5]和[3;10]的交集是[3;5],大小是2.
[1;5]和[5;7]的交集是[5;5],大小是0.
[1;5]和[6;6]的交集是空,大小是0.
题解
观察发现,n个段的交集为[ansL,ansR].其中ansL是所有li中的最大值,ansR是所有ri中的最小值。
枚举删除的段,然后求出剩下的段的交集即可。
动态维护俩个multiset,一个维护li,一个维护ri。每次删除一个段,然后查询li的最大值和ri的最小值。multiset是有序的且默认是升序,所以li的最大值就是集合的最后一个元素,ri的最小值就是集合的第一个元素。循环打擂求出最终结果。
时间复杂度O(nlogn).
AC代码
#include <bits/stdc++.h>
using namespace std;
const int maxn=3e5+7;
struct node
{
int l,r;
node(int l,int r):l(l),r(r){}
node(){}
}a[maxn];
multiset<int> L,R;
multiset<int>::iterator ite;
int main()
{
int n;
while(~scanf("%d",&n))
{
L.clear();
R.clear();
for(int i=1;i<=n;i++)
{
int l,r;
scanf("%d%d",&l,&r);
a[i]=node(l,r);
L.insert(l);
R.insert(r);
}
int ansL=0,ansR=0,ans=0;
for(int i=1;i<=n;i++)
{
int l=a[i].l,r=a[i].r;
ite=L.lower_bound(l);
L.erase(ite);
ite=L.end();--ite;
ansL=*ite;
L.insert(l);
ite=R.lower_bound(r);
R.erase(ite);
ite=R.begin();
ansR=*ite;
R.insert(r);
ans=max(ans,ansR-ansL);
}
printf("%d\n",ans);
}
return 0;
}