Algorithm to calculate number of intersecting discs

前端 未结 30 1369
鱼传尺愫
鱼传尺愫 2020-12-12 10:57

Given an array A of N integers we draw N discs in a 2D plane, such that i-th disc has center in (0,i) and a radius

30条回答
  •  有刺的猬
    2020-12-12 11:52

    This can even be done in linear time. In fact, it becomes easier if you ignore the fact that there is exactly one interval centered at each point, and just treat it as a set of start- and endpoints of intervals. You can then just scan it from the left (Python code for simplicity):

    from collections import defaultdict
    
    a = [1, 5, 2, 1, 4, 0]
    
    start = defaultdict(int)
    stop = defaultdict(int)
    
    for i in range(len(a)):
        start[i - a[i]] += 1
        stop[i + a[i]] += 1
    
    active = 0
    intersections = 0
    for i in range(-len(a), len(a)):
        intersections += active * start[i] + (start[i] * (start[i] - 1)) / 2    
        active += start[i]
        active -= stop[i]
    
    print intersections
    

提交回复
热议问题