【问题标题】:Can You help me to find a greedy algorithm for covering a line segment?你能帮我找到一个覆盖线段的贪心算法吗?
【发布时间】:2021-10-02 12:21:06
【问题描述】:

问题是:给定 n 段线(进入 X 轴),坐标为 [Li , Ri](坐标可以是负数)。您要选择覆盖整个段 [0 , M] 的最小段数。

这里我做了什么:实际上我已经按照它们的起始坐标 (Li) 以升序对段进行了排序。然后选择从最小的 Li 开始的段,然后选择最大的。

但我的算法不适用于某些情况。你们对这个问题有其他想法吗?请给我一些解决这个问题的提示。

【问题讨论】:

  • 这是一个相当简单的问题,典型的家庭作业(注意你知道贪心算法确实有效)。您的方法不太清楚,请提供更多详细信息。

标签: algorithm math optimization


【解决方案1】:

首先删除具有R < 0 的段。在其余段中,您必须至少选择一个段,例如L <= 0 <= R。在具有L <= 0 的段中选择具有最大R 的段没有损失。 用[R, M] 代替[0, M] 冲洗并重复。

【讨论】:

    【解决方案2】:
    1. 通过增加 Li 对段进行排序。

    2. 令 L=0,最左边的横坐标被覆盖。

    3. 扫描列表只要 Li

    4. 设置 L= Ri 并继续扫描 (3) 您离开它的位置,除非列表已用尽。

    主循环的不变量表示“已扫描的段最小覆盖 [0, L],其余段覆盖 [L, M](尽管不是最小)”。

    【讨论】:

    • 一种改进是将段插入堆中,而不是对它们进行排序。如果它们已排序,另一种选择是使用二进制搜索来查找最后一个 Li,使得 Li
    • @Gribouillis 二分搜索可能比顺序搜索要糟糕得多:每次搜索都会花费 Log(K),其中 K 是剩余元素的数量;在最坏的情况下(也可能是平均情况下),复杂度为 O(N Log N)。保证顺序搜索 O(N)。
    • @Gribouillis:你将如何使用堆(除了执行 HeapSort)?
    • 我的想法是该算法唯一需要的特征是拉最低Li的段。这就是为什么我想到了优先队列。然而,具体而言,可能没有明显的收获。
    • 关于二分查找,这完全取决于段的大小。例如,如果平均段的长度是一个固定值,例如 M/100,则最佳覆盖的大小通常是例如 200。这与段数 N 无关。在这种情况下,我将进行固定数量的搜索,每次都具有 Log(N) 复杂度。
    【解决方案3】:

    我正在发布针对此问题的 python 解决方案。

    def calculateOptimizedPoint(numOfCordinates, cordinates):
         sortedCordinate = sorted((cordinate for cordinate in cordinates), key = lambda itm:itm[0])
         points = []
         currentRange = sortedCordinate[0][1]
         points.append(currentRange)
         for i in range(numOfCordinates-1):
             if (currentRange < sortedCordinate[i][0]) or currentRange > sortedCordinate[i][1]):
                  currentRange = sortedCordinate[i][1]
                  points.append(currentRange)
         return points
    
    numOfCordinates = int(input("How many coordinate you want to input : "))
    cordinates = [(int(input("Enter the a{} cordinate".format(i))),int(input("Enter the b{} cordinate".format(i)))) for i in range(numOfCordinates)]
    
    print(calculateOptimizedPoint(numOfCordinates,cordinates))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多