Last active
May 29, 2023 06:44
-
-
Save NamPE286/349cbd190933f0ad7c3b293e8983e7a4 to your computer and use it in GitHub Desktop.
Segment Tree C++ iterative implementation (only support point update)
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
#include <bits/stdc++.h> | |
using namespace std; | |
typedef long long ll; | |
struct segment_tree { | |
//0-indexed | |
vector<ll> tree; | |
ll n; | |
segment_tree(vector<ll> &nums) { | |
n = nums.size(); | |
tree = vector<ll>(2 * n); | |
for (ll i = n; i < 2 * n; i++) { | |
tree[i] = nums[i - n]; | |
} | |
for (ll i = n - 1; i > 0; i--) { | |
tree[i] = tree[2 * i] + tree[2 * i + 1]; | |
} | |
} | |
void update(ll pos, ll val) { | |
pos += n; | |
tree[pos] += val; // edit "=" to change edit mode | |
while (pos > 0) { | |
ll l = pos; | |
ll r = pos; | |
if (pos % 2 == 0) | |
r = pos + 1; | |
else | |
l = pos - 1; | |
tree[pos / 2] = tree[l] + tree[r]; | |
pos /= 2; | |
} | |
} | |
ll query(ll l, ll r) { | |
l += n; | |
r += n; | |
ll ans = 0; | |
while (l <= r) { | |
if (l % 2 == 1) { | |
ans = ans + tree[l]; | |
l++; | |
} | |
if (r % 2 == 0) { | |
ans = ans + tree[r]; | |
r--; | |
} | |
l /= 2; | |
r /= 2; | |
} | |
return ans; | |
} | |
}; | |
int main() { | |
vector<ll> v = {1, 3, 2, 4}; | |
segment_tree tree(v); | |
cout << tree.query(0, 3) << '\n'; // 4 | |
tree.update(0, 5); | |
cout << tree.query(0, 3) << '\n'; // 5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment