Skip to content

Instantly share code, notes, and snippets.

@pocarist
Created March 26, 2015 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocarist/681e010c460349c23cf0 to your computer and use it in GitHub Desktop.
Save pocarist/681e010c460349c23cf0 to your computer and use it in GitHub Desktop.
// http://www.prefield.com/algorithm/container/fenwick_tree.html
// add(k, a) == v[k] = v[k] + a
// sum(i, j) == v[i] + ... + v[j] (両端を含む)
type FenwickTree(N : int) =
let zero = LanguagePrimitives.GenericZero
let x = Array.create N zero
member me.sum i j =
if i = 0 then
let rec loop acc k =
if k >= 0 then loop (acc + x.[k]) ((k &&& (k+1)) - 1)
else acc
loop zero j
else
me.sum 0 j - me.sum 0 (i-1)
member me.add i a =
let rec loop k =
if k < x.Length then
x.[k] <- x.[k] + a
loop (k ||| (k+1))
loop i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment