zoukankan      html  css  js  c++  java
  • 线段的重叠(贪心)

    题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1091

    先按线段起点升序排序,此时有两大种情况:

    第一种是第二根线段的左边在第一根线段右边的右边,

    即两根线段不相交,此时要将终点更新,因为是按起点升序排序,如果第二根的就不相交那之后的线段都不相交;

    第二种大情况是相交,其第一种小情况是包含,此时要将重叠长度与最大重叠比较,但不需要更新终点,

    第二种小情况是相交但不包含,此时不仅要比较最大重叠长度,还需要更新终点。

    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.Scanner;
    
    class Line
    {
        public int left,right;
    }
    public class N1091 {
    
        public static void main(String[] args) {
            Scanner cin=new Scanner(System.in);
            int n=cin.nextInt();
            Line []a=new Line [n];
            
            for(int i=0;i<n;i++)
            {
                a[i]=new Line();
                a[i].left=cin.nextInt();
                a[i].right=cin.nextInt();
            }
            Arrays.sort( a,new Comparator<Line> ()
            {
                    public int compare(Line l1,Line l2)
                    {
                        if(l1.left>=l2.left)
                            return 1;
                        else
                            return -1;
                    }
            });
            int end=a[0].right,ans=0;
            
            for(int i=1;i<n;i++)
            {
                if(a[i].left>end)
                    end=a[i].right;
                else
                {
                    if(a[i].right<=end)
                        ans=max(ans,a[i].right-a[i].left);
                    else
                    {
                        ans=max(ans,end-a[i].left);
                        end=a[i].right;
                    }
                }
            }
            System.out.println(ans);
        }
        public static int max(int a,int b)
            {
                return a>=b?a:b;
            }
    }
  • 相关阅读:
    mysql面试题1
    vim常用命令总结转
    centos7编译php扩展详细版
    php阻塞模式与非阻塞模式
    Linux 基础入门
    Jenkins搭建
    Git教程 注: 该博客为转载博客!!!
    centos7 安装apache+php
    熟知error_log快速调试
    Centos7yum安装Redis详细教程
  • 原文地址:https://www.cnblogs.com/NDKY9/p/7544995.html
Copyright © 2011-2022 走看看