Skip to content

Instantly share code, notes, and snippets.

@mrchnk
Created September 20, 2021 10:44
Show Gist options
  • Save mrchnk/c3ab63c850ed5158b4e4d7457787f57b to your computer and use it in GitHub Desktop.
Save mrchnk/c3ab63c850ed5158b4e4d7457787f57b to your computer and use it in GitHub Desktop.
Segment Tree (update by segment, query by index)
function SegmentTree(size, merge, zero)
local tree = {}
local function get(v, tl, tr, index)
local value = tree[v] or zero
if tl == tr then
return value
end
local tm = math.floor((tl + tr) / 2)
if index <= tm then
return merge(value, get(v * 2, tl, tm, index))
else
return merge(value, get(v * 2 + 1, tm + 1, tr, index))
end
end
local function update(v, tl, tr, l, r, add)
if l == tl and r == tr then
tree[v] = merge(tree[v] or zero, add)
else
local tm = math.floor((tl + tr) / 2)
if l <= tm then
update(v * 2, tl, tm, l, math.min(r, tm), add)
end
if r >= tm+1 then
update(v * 2 + 1, tm+1, tr, math.max(l, tm+1), r, add)
end
end
end
return {
tree = tree,
get = function (index)
return get(1, 1, size, index)
end,
update = function (l, r, add)
return update(1, 1, size, l, r, add)
end
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment