Skip to content

Instantly share code, notes, and snippets.

@NamPE286
Last active October 31, 2024 00:33
Show Gist options
  • Save NamPE286/34e7b0b1a8ac439fe67eaebed27f56ae to your computer and use it in GitHub Desktop.
Save NamPE286/34e7b0b1a8ac439fe67eaebed27f56ae to your computer and use it in GitHub Desktop.
Segment tree implementation with pointer in C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
class SegmentTree {
private:
struct Node {
Node* _left;
Node* _right;
pair<ll, ll> range;
ll value = 0;
Node(ll l, ll r) {
_left = _right = nullptr;
range = {l, r};
}
~Node() {
delete _left;
delete _right;
}
Node* left() {
auto [l, r] = range;
if (l == r) {
return nullptr;
}
return _left = (_left == nullptr ? new Node(l, (l + r) / 2) : _left);
}
Node* right() {
auto [l, r] = range;
if (l == r) {
return nullptr;
}
return _right = (_right == nullptr ? new Node((l + r) / 2 + 1, r) : _right);
}
};
Node* root = nullptr;
void _update(Node* cur, ll i, ll x) {
auto [l, r] = cur->range;
if (!(l <= i && i <= r)) {
return;
}
if (l == r) {
cur->value = x;
return;
}
_update(cur->left(), i, x);
_update(cur->right(), i, x);
cur->value = cur->left()->value + cur->right()->value;
}
ll _query(Node* cur, ll a, ll b) {
if (cur == nullptr) {
return 0;
}
auto [l, r] = cur->range;
if (r < a || b < l) {
return 0;
}
if (a <= l && r <= b) {
return cur->value;
}
return _query(cur->left(), a, b) + _query(cur->right(), a, b);
}
public:
SegmentTree(ll n) {
root = new Node(0, n - 1);
}
~SegmentTree() {
delete root;
}
void update(ll i, ll x) {
_update(root, i, x);
}
ll query(ll l, ll r) {
return _query(root, l, r);
}
};
int main() {
SegmentTree tree(8);
for(ll i = 0; i < 8; i++) {
tree.update(i, i + 1);
}
cout << tree.query(0, 3) << '\n'; // 10
cout << tree.query(1, 5) << '\n'; // 20
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment