Covering all the numbers with the given intervals

别等时光非礼了梦想. 提交于 2019-12-11 04:15:17

问题


This is a question for the algorithms gurus out there :-)

Let S be a set of intervals of the natural numbers that might overlap and N be a list of numbers.

I want to find the smallest subset (let's call P) of S such that for each number in our list N, there exists at least one interval in P that contains it. The intervals in P are allowed to overlap.

Trivial example:

S = {[1..4], [2..7], [3..5], [8..15], [9..13]}
N = [1, 4, 5]
// so P = {[1..4], [2..7]}

I think a dynamic algorithm might not work always, so if anybody knows of a solution to this problem (or a similar one that can be converted into), that would be great.

Thanks!


回答1:


You can do this with a greedy algorithm.

Consider the points in N in order.

For each point, if it is already covered by an interval then skip it.

Otherwise, consider the intervals that include the point. Out of these intervals, choose the one that covers the most uncovered points. (This will be the interval with the highest end point.)

EXAMPLE

  1. First point is 1, covered by just 1..4 so add this interval to our set.
  2. Next point is 4, but it is already covered so continue.
  3. Next point is 5, covered by 2..7 and 3..5. Choose either of these to get the answer that covers all points with 2 sets.


来源:https://stackoverflow.com/questions/26604562/covering-all-the-numbers-with-the-given-intervals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!