题意:
X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,[10 20]和[12 25]的重叠部分为[12 20]。
给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。
思路:
按照先l排序,再r排序,然后从左往右扫一遍,维护最靠右的r的线段的编号,比较更新最大重叠部分。
代码:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 5e4 + 10;
struct node {
int l, r;
bool operator < (const node &x) const {
if (l == x.l) return r < x.r;
return l < x.l;
}
}a[MAXN];
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a[i].l, &a[i].r);
}
sort (a + 1, a + 1 + n);
int x = 1, ans = 0;
for (int i = 2; i <= n; i++) {
if (a[i].l < a[x].r) {
if (a[i].r < a[x].r) ans = max(ans, a[i].r - a[i].l);
else {
ans = max(ans, a[x].r - a[i].l);
x = i;
}
}
}
printf("%d\n", ans);
return 0;
}