Algorithm to calculate number of intersecting discs

前端 未结 30 1566
鱼传尺愫
鱼传尺愫 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:40

    Thanks to Falk for the great idea! Here is a ruby implementation that takes advantage of sparseness.

    def int(a)
    
        event = Hash.new{|h,k| h[k] = {:start => 0, :stop => 0}}
        a.each_index {|i|
            event[i - a[i]][:start] += 1
            event[i + a[i]][:stop ] += 1
        }
        sorted_events = (event.sort_by {|index, value| index}).map! {|n| n[1]}
    
        past_start = 0
        intersect = 0
    
        sorted_events.each {|e|
    
            intersect += e[:start] * (e[:start]-1) / 2 +
                         e[:start] * past_start
    
            past_start += e[:start]
            past_start -= e[:stop]
        }
        return intersect
    end
    
    puts int [1,1]
    
    puts int [1,5,2,1,4,0]
    

提交回复
热议问题