Last active
April 8, 2021 13:51
-
-
Save JCSooHwanCho/1fd0695fc00a8160212bd16c5e4a2f63 to your computer and use it in GitHub Desktop.
FenwickTree의 Swift 구현체
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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