Skip to content

Instantly share code, notes, and snippets.

@miwest929
Created November 29, 2016 02:18
Show Gist options
  • Select an option

  • Save miwest929/4f3b80faab5bde553f30e86bdac3b1d1 to your computer and use it in GitHub Desktop.

Select an option

Save miwest929/4f3b80faab5bde553f30e86bdac3b1d1 to your computer and use it in GitHub Desktop.
class BinaryIndexedTree
def initialize(n)
@freq = Array.new(n, 0)
@btree = Array.new(n + 1, 0)
end
def sum(index)
sum = 0
index += 1
while (index > 0)
sum += @btree[index]
index = sum_parent_fn(index)
end
sum
end
def update(index, newValue)
@freq[index] += newValue
index += 1
while (index <= @freq.length)
@btree[index] += newValue
index = update_parent_fn(index)
end
end
def freq
@freq
end
private
def sum_parent_fn(index)
index - (index & -index)
end
def update_parent_fn(index)
index + (index & -index)
end
end
tree = BinaryIndexedTree.new(13)
skyline = [
[2, 9, 10],
[3, 7, 15],
[5, 12, 12]
]
skyline.each do |left, right, height|
curr_left_height = tree.sum(left)
curr_right_height = tree.sum(right)
if curr_left_height < height
tree.update(left, height - curr_left_height)
end
if curr_right_height < height
tree.update(right, curr_right_height - height)
end
end
puts "freq: #{tree.freq.to_s}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment