查找重叠节的最大数目

finds the maximum number of overlapping sections

本文关键字:最大数 重叠 查找      更新时间:2023-10-16

假设您在X轴上收到一组截面。

截面有一个ID、一个起点和一个终点编写伪代码或实际代码,以找到重叠部分的最大数量及其ID

描述用于表示数据的数据结构或类。

我要使用的数据结构是Segment Tree这与你使用什么语言无关。

对于表示数据的类,它要求您概述分段树的节点设计。

struct node{
    int L,R,v; // the end point and the # of segments lying in this interval, init = 0
}

然后,对于每个段,运行范围更新操作(总O(N lg(N))

我认为在更新时需要延迟传播

然后对端点进行排序,然后查询这些端点之间的2N-1"间隙"(例如:给定[1,3],[2,5],我会查询[1,2],[2,3],[3,5])(总O(N lg(N))

最后,您应该知道哪个"间隙"包含最大重叠段数,以找到这些段的ID,只需O(N)即可检查每个段是否与该"间隙"相交

我对分段树很陌生,但我希望我能给你一个正确的方向:)

编辑:

  1. 我认为可以为ID提供多个解决方案,我认为您可以输出其中的任何一个
  2. 如何处理触摸情况(即[1,3],[3,5])与问题有关,通常认为在坐标3处最多有2个重叠

这有点盲目,因为它没有说明关键是性能、清晰度等。在C#中,让我们假设Section是一个类似的对象

class Section
{
public double StartX;
public double EndX;
public int ID;
//[...]
}

然后我需要一个外部类来获得重叠(假设一个部分可以与其他几个部分重叠,并且每个重叠必须独立计数)

 class OverlapCounter
        {
            public static int GetOverlaps(Section[] inputSections, out List<int> OverlappedSectionsIDs)
            {
                int numOverlaps = 0;
                OverlappedSectionsIDs = new List<int>();
                for (int i= inputSections.Length-1; i>=1; i--)
                {
                    bool isNotListed = true;
                    double S1_start = inputSections[i].StartX;
                    double S1_end= inputSections[i].EndX;
                    for (int j= i-1; j>=0; j--)                     
                    {
                        double S2_start = inputSections[j].StartX; //stored for the sake of clarity
                        double S2_end = inputSections[j].EndX;
                        if (S1_start<= S2_end && S1_end>= S2_start) 
                        {
                            numOverlaps++; //all the overlappings are counted
                            if(isNotListed)
                            {
                                //IDs should not be repeated
                                OverlappedSectionsIDs.Add(inputSections[i].ID); 
                                isNotListed = false;
                            }
                        }
                        
                    }
                }
                return numOverlaps;
            }
        }

最后,您可以使用获得所需内容

    List<int> OverlappedSectionsIDs;
    int numMaxOverlaps = OverlapCounter.GetOverlaps(SectionsArray,out OverlappedSectionsIDs);