-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersistent segtree.sublime-snippet
105 lines (85 loc) · 2.9 KB
/
persistent segtree.sublime-snippet
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<snippet>
<content><![CDATA[
struct Node {
int val;
Node* left, * right;
Node(int v = 0, Node* l = nullptr, Node* r = nullptr) : val(v), left(l), right(r) {}
};
constexpr int MAX_SIZE = 10000000;
Node nodes[MAX_SIZE];
int nodeCounter = 0;
class PersistentSegmentTree {
public:
vector<Node*> versions;
vector<int> arr; // Store the array here
Node* garbage = getNode(0);
Node* getNode(int val, Node* l = nullptr, Node* r = nullptr) {
if (nodeCounter < MAX_SIZE) {
nodes[nodeCounter].val = val;
nodes[nodeCounter].left = l;
nodes[nodeCounter].right = r;
return &nodes[nodeCounter++];
}
return nullptr;
}
Node* unite(Node* leftNode, Node* rightNode) {
return getNode(leftNode->val + rightNode->val, leftNode, rightNode);
}
template<typename T>
Node* initNode(T val) {
return getNode(val);
}
template<typename T>
Node* upd(Node* prev, int low, int high, int idx, T val) {
if (low == high) {
return initNode(val);
}
int mid = (low + high) / 2;
if (idx <= mid) {
return unite(upd(prev->left, low, mid, idx, val), prev->right);
} else {
return unite(prev->left, upd(prev->right, mid + 1, high, idx, val));
}
}
Node* get(Node* node, int low, int high, int qlow, int qhigh) {
// debug(low, high, qlow, qhigh);
if (node == nullptr || qlow > high || qhigh < low) {
return garbage;
}
if (qlow <= low && qhigh >= high) {
return node;
}
int mid = (low + high) / 2;
return unite(get(node->left, low, mid, qlow, qhigh), get(node->right, mid + 1, high, qlow, qhigh));
}
PersistentSegmentTree(vector<int>& input_arr) : arr(input_arr) {
versions.push_back(build(0, arr.size() - 1, arr));
}
template<typename T>
void upd(int version, int idx, T val) {
versions.push_back(upd(versions[version], 0, (int)arr.size() - 1, idx, val));
}
template<typename T>
void upd(int idx, T val) {
upd(versions.size() - 1, idx, val);
}
Node* get(int version, int qlow, int qhigh) {
return get(versions[version], 0, (int)arr.size() - 1, qlow, qhigh);
}
Node* get(int qlow, int qhigh) {
return get(versions.back(), 0, (int)arr.size() - 1, qlow, qhigh);
}
Node* build(int low, int high, vector<int>& input_arr) {
if (low == high) {
return initNode(input_arr[low]);
}
int mid = (low + high) / 2;
return unite(build(low, mid, input_arr), build(mid + 1, high, input_arr));
}
};
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>persistent segtree</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<!-- <scope>source.python</scope> -->
</snippet>