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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
use Monoid;
use IntoIndex;
use FromIterator;
use ptr;
/// A segment tree that supports range query.
///
/// A segment tree is used when you want to query on properties of interval. For instance, you have
/// a list of numbers and you want to get a minimum value of certain interval. If you compute it on
/// the fly, it would require (m - 1) comparisons for the length m interval. We can use a segment tree
/// to efficiently compute the minimum element.
///
/// Each node of a segment tree represents a union of intervals of their child nodes and each leaf
/// node means an interval containing only one element. Following is an example segment tree of
/// elements [1, 42, 16, 3, 5].
/// <pre>
/// +-----+
/// | 1 |
/// +-----+
/// [0, 8)
/// / \
/// / \
/// +---+ +---+
/// | 1 | | 5 |
/// +---+ +---+
/// [0, 4) [4, 8)
/// / \ / \
/// / \ / \
/// +---+ +---+ +---+ +----+
/// | 1 | | 3 | | 5 | | id |
/// +---+ +---+ +---+ +----+
/// [0, 2) [2, 4) [4, 6) [6, 8)
/// / | | \ / | | \
/// / | | \ / | | \
/// +---+ +----+ +----+ +---+ +---+ +----+ +----+ +----+
/// | 1 | | 42 | | 16 | | 3 | | 5 | | id | | id | | id |
/// +---+ +----+ +----+ +---+ +---+ +----+ +----+ +----+
/// [0, 1) [1, 2) [2, 3) [3, 4) [4, 5) [5, 6) [6, 7) [7, 8)
/// </pre>
///
/// When you update an element, it propagates from the leaf to the top. If we update 16 to 2, then
/// the parent node would be updated to 3 -> 2, but the [0, 4) and root node won't be updated as 1
/// is less than 2.
///
/// When querying, it visits non-overlapping nodes within the inteval and computes the minimum among
/// the nodes. For example if we query minimum element in an interval [1, 4), it first visits [1, 2)
/// node and then it visits [2, 4). Then it computes min(42, 3) which is 3. Note that it only visits
/// two nodes at each height of the tree hence the time complexity O(log(n)).
///
/// # Use a segment tree when:
/// - You want to efficiently query on an interval property.
/// - You only update one element at a time.
///
/// # Requirements
/// Here _the operation_ is how we get an interval property of a parent node from the
/// child nodes. For instance, the minimum element within interval [0, 4) is minimum element of
/// mimima from intervals [0, 2) and [2, 4) so the `min` is the operation.
/// - The interval property has an identity with respect to the operation.
/// - The operation is associative.
/// - The interval property of a union of two disjoint intervals is the result of the performing
/// operation on the interval properties of the two intervals.
///
/// [1]: https://en.wikipedia.org/wiki/Associative_property
///
/// In case of our example, every elements of `i32` is less than or equal to `i32::MAX` so we have an identity.
/// And `min(a, min(b, c)) == min(min(a, b), c)` so it is associative.
/// And if the minima of [a1, a2, ... , an] and [b1, b2, ... , bn] are a and b respectively, then
/// the minimum of [a1, a2, ..., an, b1, b2, ... , bn] is min(a, b).
/// Therefore we can use segment tree to efficiently query the minimum element of an interval.
///
/// To capture the requirements in the Rust programming language,
/// a segment tree requires the elements to implement the [`Monoid`] trait.
///
/// # Performance
/// Given n elements, it computes the interval property in O(log(n)) at the expense of O(log(n))
/// update time.
///
/// If we were to store the elements with `Vec`, it would take O(m) for length m interval query
/// and O(1) to update.
///
/// # Examples
/// ```
/// use libpuri::{Monoid, SegTree};
///
/// // We'll use the segment tree to compute interval sum.
/// #[derive(Clone, Debug, PartialEq, Eq)]
/// struct Sum(i64);
///
/// impl Monoid for Sum {
/// const ID: Self = Sum(0);
/// fn op(&self, rhs: &Self) -> Self { Sum(self.0 + rhs.0) }
/// }
///
/// // Segment tree can be initialized from an iterator of the monoid
/// let mut seg_tree: SegTree<Sum> = [1, 2, 3, 4, 5].iter().map(|&n| Sum(n)).collect();
///
/// // [1, 2, 3, 4]
/// assert_eq!(seg_tree.get(0..4), Sum(10));
///
/// // [1, 2, 42, 4, 5]
/// seg_tree.set(2, Sum(42));
///
/// // [1, 2, 42, 4]
/// assert_eq!(seg_tree.get(0..4), Sum(49));
/// ```
// TODO(yujingaya) remove identity requirement with non-full binary tree?
// Could be a semigroup
// reference: https://codeforces.com/blog/entry/18051
// An identity requirement could be lifted if we implement the tree with complete tree instead
// of perfect tree, making this trait name a semigroup. But for the sake of simplicity, we
// leave it this way for now.
;
/// You can `collect` into a segment tree.