https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1091
按照左端点从小到大,相等时右端点从小到大排序,扫一遍数组,维护之前所有线段最右的端点,由于数组已经排过序了,所以可以保证之前所有线段的左端点一定小于等于当前所选择线段的左端点,所以就不用管左端点,直接用当前线段的右端点和之前所有线段的最大右端点比较一下,更新答案和最大右端点。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e4 + 5;
pair<int, int> a[maxn];
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; ++i){
cin >> a[i].first >> a[i].second;
if (a[i].second < a[i].first) swap(a[i].second, a[i].first);
}
sort(a, a + n);
int maxr = a[0].second, ans = 0;
for (int i = 1; i < n; ++i){
if (a[i].second > maxr){
ans = max(ans, maxr - a[i].first);
maxr = a[i].second;
}else ans = max(ans, a[i].second - a[i].first);
}
cout << ans << endl;
return 0;
}