Skip to content

Instantly share code, notes, and snippets.

@JCSooHwanCho
Last active April 8, 2021 13:51
Show Gist options
  • Save JCSooHwanCho/1fd0695fc00a8160212bd16c5e4a2f63 to your computer and use it in GitHub Desktop.
Save JCSooHwanCho/1fd0695fc00a8160212bd16c5e4a2f63 to your computer and use it in GitHub Desktop.
FenwickTree의 Swift 구현체
struct FenwickTree {
var tree: [Int]
var arr: [Int]
init(size n: Int) {
tree = Array(repeating: 0, count: n+1)
arr = Array(repeating: 0, count: n)
}
func sum(_ pos: Int) -> Int {
var ret = 0
var pos = pos + 1
while pos > 0 {
ret += tree[pos]
pos &= (pos-1)
}
return ret
}
mutating func add(at pos: Int, _ val: Int) {
var pos = pos + 1
while pos < tree.count {
tree[pos] += val
pos += (pos & -pos)
}
}
mutating func replace(at pos: Int, val: Int) {
let diff = val-arr[pos]
arr[pos] = diff
add(pos,diff)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment