zoukankan      html  css  js  c++  java
  • 51nod 1091 线段的重叠 分类: 51nod 2015-07-18 21:49 7人阅读 评论(0) 收藏

    基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
    收藏
            
    关注
    取消关注
                 
    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示例

    51 52 42 83 77 9

    Output示例

    4

    这题先按起点从小到大排序,然后在遍历,遍历的过程中更新最大的覆盖值。时间复杂度为O(n^2),但有n*longn的做法。。

    #include<stdio.h>
    #include<string.h>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    struct node
    {
     int x,y;
    };
    bool cmp(node a,node b)
    {
     if(a.x!=b.x)
     return a.x<b.x;
     return a.y<b.y;
    }
    int main()
    {
     int n;
     node point[50005];
     while(scanf("%d",&n)!=EOF)
     {
      for(int i=0;i<n;i++)
      {
       scanf("%d%d",&point[i].x,&point[i].y);
      }
      sort(point,point+n,cmp);
      int max=-100000;
      int cnt=0;
      for(int i=0;i<n;i++)
      {
       for(int j=i+1;j<n;j++)
       {
        if(point[i].y-point[i].x<max)
        break;//当线段长度小于已知的最大覆盖值直接跳出来,没有这句则程序会超时= =
        if(point[i].y<point[j].x)
        continue;
        else if(point[i].x<point[j].y&&point[i].y>point[j].y)
        {
         cnt=point[j].y-point[j].x;
        }
        else
        cnt=point[i].y-point[j].x;
        if(cnt>max)
        max=cnt;
       }
      }
      printf("%d ",max);
     }
     return 0;
    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Mvc+三层(批量添加、删除、修改)
    js中判断复选款是否选中
    EF的优缺点
    Git tricks: Unstaging files
    Using Git Submodules
    English Learning
    wix xslt for adding node
    The breakpoint will not currently be hit. No symbols have been loaded for this document."
    Use XSLT in wix
    mfc110ud.dll not found
  • 原文地址:https://www.cnblogs.com/NaCl/p/4700596.html
Copyright © 2011-2022 走看看