• 51nod 1091 线段的重叠


    基准时间限制: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;
    }

  • 相关阅读:
    ubuntu 14.04 如何安装nvidia显卡驱动 [转载]
    torch Tensor学习:切片操作
    Graphviz(转载)
    torch 深度学习(5)
    torch 深度学习(4)
    torch 深度学习(3)
    torch 深度学习 (2)
    C# 初识Ref和Out
    Unity发送短信
    Unity 3D 动画帧事件
  • 原文地址:https://www.cnblogs.com/NaCl/p/9580218.html
Copyright © 2020-2023  润新知