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

原题链接: https://codeforces.com/problemset/problem/1029/C

在这里插入图片描述
测试样例

Input
4
1 3
2 6
0 4
3 3
Output
1
Input
5
2 6
1 3
0 4
1 20
0 4
Output
2
Input
3
4 5
1 2
9 20
Output
0
Input
2
3 10
1 5
Output
7

Note

In the first example you should remove the segment [ 3 ; 3 ] [3;3] [3;3], the intersection will become [ 2 ; 3 ] [2;3] [2;3] (length 1). Removing any other segment will result in the intersection [ 3 ; 3 ] [3;3] [3;3] (length 0).

In the second example you should remove the segment [ 1 ; 3 ] [1;3] [1;3] or segment [2;6], the intersection will become [ 2 ; 4 ] [2;4] [2;4] (length 2) or [ 1 ; 3 ] [1;3] [1;3](length 2), respectively. Removing any other segment will result in the intersection [ 2 ; 3 ] [2;3] [2;3](length 1).

In the third example the intersection will become an empty set no matter the segment you remove.

In the fourth example you will get the intersection [ 3 ; 10 ] [3;10] [3;10](length 7) if you remove the segment [ 1 ; 5 ] [1;5] [1;5] or the intersection [ 1 ; 5 ] [1;5] [1;5] (length 4) if you remove the segment [ 3 ; 10 ] [3;10] [3;10].

题意: 给定很多个区间,现在允许你删掉一个区间,使得这并区间的长度尽可能大,问你最大是多少?

解题思路: 首先我们要知道,决定并区间的是左端点最近的和右端点最近的,即区间长度就为: l − r l-r lr。所以我们自然可以枚举删除一个区间来计算这并区间长度,那么我们可以对左端点和右端点分别用multiset容器来实现,它可以自动排序,我们利用一个来存储左端点,一个存储右端点,最后长度就为 ∗ m 1. b e g i n − ∗ m 2. r b e g i n ( ) *m1.begin-*m2.rbegin() m1.beginm2.rbegin()。注意枚举删除,我们应该要将每次枚举删除计算完后重新放回去。

AC代码

/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h>//POJ不支持

#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=a;i>=n;i--)

using namespace std;

const int inf=0x3f3f3f3f;//无穷大。
const int maxn=1e5;//限定值。
typedef long long ll;

int l[maxn],r[maxn];
int n;
int main(){
	while(cin>>n){
		multiset<int> m1,m2;
		rep(i,1,n){
			cin>>l[i]>>r[i];
			m1.insert(l[i]);
			m2.insert(r[i]);
		}
		int maxx=0;
		rep(i,1,n){
			m1.erase(m1.find(l[i]));
			m2.erase(m2.find(r[i]));
			maxx=max(maxx,*m2.begin()-*m1.rbegin());
			m1.insert(l[i]);
			m2.insert(r[i]);
		}
		cout<<maxx<<endl;
	}
	return 0;
}
posted @ 2022-03-26 16:49  unique_pursuit  阅读(19)  评论(0)    收藏  举报