欢迎来到PJCK的博客

(贪心 区间) 51nod1091 线段的重叠

X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,[10 20]和[12 25]的重叠部分为[12 20]。
给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。
 

输入

第1行:线段的数量N(2 <= N <= 50000)。
第2 - N + 1行:每行2个数,线段的起点和终点。(0 <= s , e <= 10^9)

输出

输出最长重复区间的长度。

输入样例

5
1 5
2 4
2 8
3 7
7 9

输出样例

4

---------------------------------------------------------------------------------------------
区间贪心,是以线段的开头进行排序的如果线段的开头一样,就让线段的段尾从大到小进行排序。进行一次遍历,O(n)。
C++代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn = 50003;
struct Node {
    int l, r;
}n[maxn];
bool cmp(Node a, Node b) {
    if (a.l == b.l)
        return a.r > b.r;
    return a.l < b.l;
}
int main() {
    int N;
    cin >> N;
    for (int i = 0; i < N; i++) {
        cin >> n[i].l >> n[i].r;
    }
    sort(n, n + N, cmp);
    Node cnt = n[0];
    int ans = 0;
    for (int i = 1; i < N; i++) {
        if (cnt.r >= n[i].r) {
            ans = max(ans, n[i].r - n[i].l);
        }
        else {
            ans = max(ans, cnt.r - n[i].l);
            cnt = n[i];
        }
    }
    cout << ans << endl;
    system("pause");
    return 0;
}

 

posted @ 2019-04-08 16:51  PJCK  阅读(147)  评论(0编辑  收藏  举报