题目传送门
思路:
本来还以为要很复杂的算法,没想到muktiset也可以。其实计算一下复杂度,确实可以过。
复杂度是O(n*logn*logn),n = 3e5时,是1.2*e8.所以要好好利用c++的STL.
AC code:
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 3e5 + 10;
pair<int,int> s[maxn];
//复杂度计算一下,还是可以过的
int main(){
int n = 0;
while(scanf("%d",&n) != EOF){
multiset<int> l,r;
for(int i = 0;i < n;++i){
scanf("%d %d",&s[i].first,&s[i].second);
l.insert(s[i].first),r.insert(s[i].second);
}
int maxv = 0;
for(int i = 0;i < n;++i){
l.erase(l.find(s[i].first)),r.erase((r.find(s[i].second)));
maxv = max ( maxv , *r.begin() - *l.rbegin());//rbegin()指向的是最后一个元素
// maxv = max ( maxv , *r.begin() - *l.end());//而end()指向的是最后一个元素的下一个
l.insert(s[i].first),r.insert(s[i].second);
}
printf("%d\n",maxv);
}
return 0;
}
大佬的简洁版:
#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0) , cout.tie(0) , cin.tie(0);
int n ;
cin >> n;
multiset<int> L;
multiset<int> R;
pair<int , int> arr[n];
for(int i = 0 ; i <n ; i++){
cin >> arr[i].first >> arr[i].second;
L.insert(arr[i].first);
R.insert(arr[i].second);
}
int ans = 0;
for(int i = 0 ; i < n ; i++) {
L.erase(L.find(arr[i].first));
R.erase(R.find(arr[i].second));
ans = max(ans , *R.begin() - *L.rbegin());
L.insert(arr[i].first);
R.insert(arr[i].second);
}
cout << ans;
return 0 ;
}