找到最大k,使得存在由k个区间覆盖的点

时间:2015-12-25 21:28:26

标签: algorithm

假设给出实线上的n个闭区间[a [i],b [i]](i = 1..n)。找到最大k,使得存在由k个区间覆盖的点(“层”的最大数量)。操作次数应为nlogn。

有一个解决方案。 [暗示。将间隔的所有左端点和右端点排序在一起。在排序时,假设左端点位于位于实线相同点的右端点之前。然后从左向右移动计算层数。当我们越过左端点时,将层数增加1;当我们越过右端点时,将层数减少1.请注意,两个相邻的间隔处理正确;也就是说,根据我们的惯例,左端点在右端点之前。]

我的问题是,如何知道遇到的点是左端点还是右端点?我需要额外的空间来记录吗?

1 个答案:

答案 0 :(得分:0)

The question itself contains the steps of the expected algorithm, almost a pseudo-code.

I turned the description into a python 3 program as an excercise:

def prefix_sum(seq, acc = 0):
  for i in seq:
    acc += i
    yield acc

def count_layers(intervals):
  endpoints = sorted([(s, -1) for s,e in intervals] + [(e, +1) for s,e in intervals])
  return -min(prefix_sum(delta for _,delta in endpoints))

print(count_layers([[2,3],[1,2]]))

Tested with:

def test(intervals):
  print()
  print('Test')
  for s,e in intervals:
    print(' ' * s + '-' * (e - s + 1))
  print('Answer:', count_layers(intervals))

TEST_CASES = [
  [ [ 1, 5], [ 4, 9], [ 2, 4], [ 6,12], ],
  [ [ 1, 3], [ 3, 5], [ 7, 9], [ 5, 7], ],
  [ [ 3, 4], [ 1, 2], ],
  [ [ 2, 3], [ 1, 2], ],
]

for test_case in TEST_CASES:
  test(test_case)