user1008537
user1008537

Reputation:

Covering all the numbers with the given intervals

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!

Upvotes: 1

Views: 787

Answers (1)

Peter de Rivaz
Peter de Rivaz

Reputation: 33509

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.

Upvotes: 2

Related Questions