Snippets

Camilo Rocha Minimal Covering Algorithm with failure checking

Created by Camilo Rocha
# input:  L and H integers with L<=H, and a[0..N) array of pairs of
#         integers, with a[i][0]<a[i][1] for 0 <= i < N and N>=0,
#         representing closed intervals [a[i][0],a[i][1]] NOT
#         necessarily covering the closed interval [L,H]
#
# output: an array b[0..M) with indexes of a[0..N) representing a
#         minimal interval covering of [L,H] with intervals in a; or
#         an empty array in case a does not cover [L,H]
#
# time complexity O(N) without sorting; O(N log N) with sorting

def mic_wf(L,H,a):
  a.sort()
  ans,low,n,ok,N = list(),L,0,True,len(a)
  while ok and low<H and n!=N:
    ok = a[n][0]<=low
    best,n = n,n+1
    while ok and n!=N and a[n][0]<=low:
      if a[n][1]>a[best][1]:
        best = n
      n += 1
    ans.append(best)
    low = a[best][1]
  ok = ok and low>=H
  if ok==False:
    ans = list()
  return ans

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.