[51nod] 1091 线段的重叠 贪心

X轴上有N条线段,每条线段包括1个起点和终点。线段的重叠是这样来算的,[10 20]和[12 25]的重叠部分为[12 20]。
给出N条线段的起点和终点,从中选出2条线段,这两条线段的重叠部分是最长的。输出这个最长的距离。如果没有重叠,输出0。
 
Input
第1行:线段的数量N(2 <= N <= 50000)。
第2 - N + 1行:每行2个数,线段的起点和终点。(0 <= s , e <= 10^9)
Output
输出最长重复区间的长度。
Input示例
5
1 5
2 4
2 8
3 7
7 9
Output示例
4

贪心策略

按照起点升序排列,选择当前该区间的最长覆盖长度为min(end, L[i].e)-L[i].b, end为该区间之前最长的尾端点,则当前的最长覆盖长度为之前的最大值与选择该区间最大值中较大的一个,
最后一直维护最大值和最长尾端点即可。
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define LL long long
struct line
{
    int b, e;
}L[50010];
int n;

int cmp(line a, line b)
{
    if (a.b != b.b)
        return a.b < b.b;
    else
        return a.e < b.e;
}

int main()
{
    //freopen("1.txt", "r", stdin);
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%d%d", &L[i].b, &L[i].e);
    sort(L, L+n, cmp);
    
    int maxlen = 0, end = L[0].e;
    for (int i = 1; i < n; i++) {
        maxlen = max(maxlen, min(end, L[i].e)-L[i].b);
        end = max(end, L[i].e);
    }
    printf("%d\n", maxlen);


    return 0;
}

 

 

 

 
posted @ 2017-07-13 10:22  whileskies  阅读(237)  评论(0编辑  收藏  举报