2019.02.07
First of all, I want to thank lecturers Alexander Antonenko (asantonenko@gmail.com), Arthur Maximov and Igor Mazurok. I guess, if not their advices and lectures, and also excellent exposition of educational material, the universal segment tree I’ve made would either have less comfortable usage, or simply not exist.
Note: in order this article to have the maximal use for the reader, he/she must have the basic cognition of C++ programming language and certain idea of asymptotics and mathematical notations.
Notation of function \(f\) such as relation between cartesian product of sets and a certain other set, for example \(f: A \times B \to C\) means, that function \(f = f \left( x, y \right)\) takes two arguments \(x\) and \(y\), where \(x \in A\) (verbally: \(x\) from set \(A\)), \(y \in B\), and result is element of the \(C\) set, i.e. \(f \left( a, b \right) \in C\). In other words, under notations, such as \(f: A \times B \to C\) the reader may understand the following: function \(f\) defined so that for element \(a\) from set \(A\) and for element \(b\) from set \(B\) exists such an element \(c\) from set \(C\), that \(f \left( a, b \right) = c\).
Supporting materials
Definition: Suppose \(G\) – non-empty set. Binary operation \(\circ\) on this set (\(\circ: G \times G \to G\)) is called associative, if for any elements \(a\), \(b\) and \(c\) from the set \(G\) the following condition is satisfied:
\(\left( a \circ b \right)\) \(\circ\) \(c\) \(=\) \(a\) \(\circ\) \(\left( b \circ c \right)\)
\({\mathbb{N}}_0 = \mathbb{N} \cup \{ 0 \}\), where \(\mathbb{N}\) – set of natural numbers.
The task of multiple results and modifications on a segment
In programming tasks of the form below are met:
Suppose a \(G\) – given certain non-empty set of observed operands, \(\circ:\) \(G\) \(\times\) \(G\) \(\to\) \(G\) – certain associative binary operation on the set \(G\) and \(M\) – non-empty set of modifiers, \(f: G \times M \to G\) – function-modifier of elements of the set \(G\). Let in the input stream be given: numbers \(n, m \in \mathbb{N}\); array of \(n\) elements \(a_{i}\), \(a_{i} \in G\), \(i = \overline{0, n-1}\) \(\left( a_{0}, a_{1}, \ldots, a_{n-2}, a_{n-1} \right)\).
After the array follow \(m\) queries of two types:
- Query of result calculation: in the input stream two numbers \(l\), \(r\) are given, \(0 \le l \le r \le n-1\), \(l, r \in {\mathbb{N}}_0\). Calculate result of operation \(\circ\) on the segment \(\left[ l, r \right]\) – \(A_{\left[ l, r \right]}\), where \(A_{\left[ l, r \right]} = a_l \circ a_{l+1} \circ \ldots \circ a_{r-1} \circ a_r\), and put it into the output stream;
- Query of segment modification: in the input stream are given two numbers \(l\), \(r\), \(0 \le l \le r \le n-1\), \(l, r \in {\mathbb{N}}_0\) and a certain value \(y\), \(y \in M\). Modify the segment \(\left[ l, r \right]\), by replacing values of elements \(a_i\) to \(f \left( a_i, y \right)\), \(i = \overline{l, r}\).
Often tasks of such type are reduced to the solvable with usage of segment tree for the multiple modification (further – STMM). Possibly, later I’ll try to expound in detail the basic principles of its work. In the main they are based on the following two ideas:
- Modify not the segment, but only vertexes, which are responsible for the result of operation \(\circ\) on it.
- Modifications are accumulated, and are being applied on the lesser segments only then, when there are given requests for the segments, which were affected by these modifications.
I’ll explain, why exactly STMM is being used.
Often beginner programmers begin to solve tasks of such type with so called “naive method”: modifications and calculations of the given result of operation \(\circ\) are being made with a cycle, directly.
Pseudocode of such solution:
|
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 |
read n; a := array of n elements; for i from 0 to n-1: read a[i]; read m; for j from 0 to m-1; { read L, R; if (query_type is modification): { read Y; for i from L to R (inclusive): a[i] := f(a[i], Y); } else // query_type is request of operation_result { operation_result = a[L]; for i from L+1 to R (inclusive): operation_result = (operation_result) o (a[i]); print(operation_result); } } |
Asymptotical complexity of modification of segment at this implementation makes itin the worst cases up to \(O \left( n \cdot c_{f} \right)\), and complexity of calculation of result on the segment of operation – \(O \left( n \cdot c_{\circ} \right)\), where \(c_{f}\) – complexity of perfomance of the modification of elements of array by the function \(f\), \(c_{\circ}\) – complexity of performance of a single operation \(\circ\). The general asymptotical complexity of the program wherein will be \(O \left( m \cdot n \cdot \left(c_{f}+c_{\circ}\right) \right)\), because the task gives \(m\) queries.
Segments tree for the multiple modification allows to shorten the time consumption and noticeably improve the general asymptotics of the program up to \(O \left( \left( n + m \right) \cdot \log_{2}{n} \cdot \left( c_{f}+c_{\circ} \right) \right)\).
Unconditionally, for every task there is its own solution. However, the most of tasks contain regularities, which allow one way or another to simplify their solution. In assumption of such reasonings, I decided to realize the universal segment tree for the multiple modification, since it’s much more simpler to use the ready solution for the most of varieties of the tasks, than rewriting it for every new task from the beginning, but with little differences. It may be imperfect for solution of every task of the form, which was noticed in the beginning of this article (in addition there may exist varieties of this task, which are solvable without this tree at all), however the quickest solution of the task in the moment of its setting (what is the most often met in Olympiad programming) compensates that. In addition, in the future universal segment tree may be used as a template and be slightly modified or optimized specifically specially for the concrete task.
This way or another, I’ll give the code of universal STMM, and also additional conditions, which are being applied on the task for application of this data structure and a manual of its usage. Pay attention, that it’s not necessary (though useful) for You to know principles of STMM’s operation or to try to get the written below code completely, in order to solve task with usage of universal STMM.
The code of the universal STMM (on C++ language)
STMM: version 1.2.0 (recursive)
In this version of the tree recursion is being used. The testing has shown, that it works (approximately) 26% quicker, than the version of the tree, which uses std::stack for preventing system stack’s overload. Personally I recommend to use exactly this version, however for the tasks with excessively (which is unlikely to happen) big amount \(n\) of elements of array it may cause errors.
|
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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
// Copyright (c) http://vgworld.name/the-universal-segment-tree #include <algorithm> // std::min, size_t template <typename TYPE> TYPE highest_bit_of(const TYPE& Num) { TYPE answer; (answer = 1) <<= (sizeof(TYPE)*8 - 1); while((answer&Num) != answer) answer >>= 1; return answer; } template <typename TYPE, typename MODIFIER_TYPE, typename INDEX = size_t> class segment_tree { TYPE (*operation)(const TYPE&, const TYPE&); TYPE (*modify_)(const TYPE&, const MODIFIER_TYPE&, const INDEX&); MODIFIER_TYPE (*combine)(const MODIFIER_TYPE&, const MODIFIER_TYPE&); MODIFIER_TYPE neutral_modifier; bool defined; struct binary_segment_tree { segment_tree *Parent; TYPE *SegmentTree; MODIFIER_TYPE *ModifierList; INDEX amount_in_array; bool defined; void force_deletion() { delete[] SegmentTree; if (amount_in_array > 1) delete[] ModifierList; defined = false; } void safe_deletion() { if (defined) // if defined == true force_deletion(); } void set_results_on_segments() { if (amount_in_array > 1) { ModifierList = new MODIFIER_TYPE[amount_in_array-1]; for(INDEX i = amount_in_array-1; i;) { --i; SegmentTree[i] = Parent->operation( SegmentTree[2*i+1], SegmentTree[2*i+2] ); ModifierList[i] = Parent->neutral_modifier; } } } void build_tree_from_preprocessor(TYPE preprocessor()) { SegmentTree = new TYPE[2*amount_in_array-1]; const INDEX right_limit_ = 2*amount_in_array-1; for(INDEX i = amount_in_array-1; i < right_limit_; ++i) SegmentTree[i] = preprocessor(); set_results_on_segments(); defined = true; } void build_tree_from_array(TYPE *array) { SegmentTree = new TYPE[2*amount_in_array-1]; const INDEX right_limit_ = 2*amount_in_array-1; for(INDEX i = amount_in_array-1; i < right_limit_; ++i) SegmentTree[i] = *(array++); set_results_on_segments(); defined = true; } void try_push(const INDEX& vertex, const INDEX& left, const INDEX& right) { if (vertex < amount_in_array-1) if (ModifierList[vertex] != Parent->neutral_modifier) { INDEX i = 2*vertex+1, amount_of_elements=(right-left+1)/2; SegmentTree[i] = Parent->modify_(SegmentTree[i], ModifierList[vertex], amount_of_elements); SegmentTree[i+1] = Parent->modify_(SegmentTree[i+1], ModifierList[vertex], amount_of_elements); if (i+1 < amount_in_array-1) { ModifierList[i] = Parent->combine(ModifierList[i], ModifierList[vertex]); ModifierList[i+1] = Parent->combine(ModifierList[i+1], ModifierList[vertex]); } ModifierList[vertex] = Parent->neutral_modifier; } } TYPE result_on_segment_in( const INDEX& vertex, const INDEX& viewed_left, const INDEX& viewed_right, const INDEX& required_left, const INDEX& required_right ) { if ((viewed_left==required_left) && (viewed_right==required_right)) return SegmentTree[vertex]; else { try_push(vertex, viewed_left, viewed_right); INDEX left_middle = (viewed_right+viewed_left)/2, right_middle = left_middle+1; if (required_right <= left_middle) { return result_on_segment_in( 2*vertex+1, viewed_left, left_middle, required_left, required_right ); } else if (required_left >= right_middle) { return result_on_segment_in( 2*vertex+2, right_middle, viewed_right, required_left, required_right ); } else { return Parent->operation( result_on_segment_in( 2*vertex+1, viewed_left, left_middle, required_left, left_middle ), result_on_segment_in( 2*vertex+2, right_middle, viewed_right, right_middle, required_right ) ); } } } void modify_in( const INDEX& vertex, const INDEX& viewed_left, const INDEX& viewed_right, const INDEX& required_left, const INDEX& required_right, const MODIFIER_TYPE& modifier ) { if ((viewed_left==required_left) && (viewed_right==required_right)) { SegmentTree[vertex] = Parent->modify_( SegmentTree[vertex], modifier, viewed_right-viewed_left+1 ); if (vertex < amount_in_array-1) ModifierList[vertex] = Parent->combine(ModifierList[vertex], modifier); } else { try_push(vertex, viewed_left, viewed_right); INDEX left_middle = (viewed_right+viewed_left)/2, right_middle = left_middle+1; if (required_right <= left_middle) { modify_in( 2*vertex+1, viewed_left, left_middle, required_left, required_right, modifier ); } else if (right_middle <= required_left) { modify_in( 2*vertex+2, right_middle, viewed_right, required_left, required_right, modifier ); } else { modify_in( 2*vertex+1, viewed_left, left_middle, required_left, left_middle, modifier ); modify_in( 2*vertex+2, right_middle, viewed_right, right_middle, required_right, modifier ); } SegmentTree[vertex] = Parent->operation( SegmentTree[2*vertex+1], SegmentTree[2*vertex+2] ); } } public: binary_segment_tree() : defined(false) {} ~binary_segment_tree() { safe_deletion(); } void construct( TYPE *begin, TYPE *end, segment_tree *NewParent ) { safe_deletion(); this->Parent = NewParent; amount_in_array = end-begin; build_tree_from_array(begin); } void read( const INDEX& amount_of_elements, TYPE preprocessing_function(), segment_tree *NewParent ) { safe_deletion(); this->Parent = NewParent; amount_in_array = amount_of_elements; build_tree_from_preprocessor(preprocessing_function); } TYPE result(const INDEX& left, const INDEX& right) { return result_on_segment_in(0, 0, amount_in_array-1, left, right); } void modify(const INDEX& left, const INDEX& right, const MODIFIER_TYPE& modifier) { modify_in(0, 0, amount_in_array-1, left, right, modifier); } }; struct node { binary_segment_tree Left; node *Right; node() : Right(NULL) {} ~node() { Left.safe_deletion(); if (Right != NULL) delete Right; } INDEX LeftLimit, RightLimit; }; node Root; void set_variables( TYPE new_operation(const TYPE&, const TYPE&), TYPE new_modify_(const TYPE&, const MODIFIER_TYPE&, const INDEX&), MODIFIER_TYPE new_combine(const MODIFIER_TYPE&, const MODIFIER_TYPE&), const MODIFIER_TYPE& new_neutral_modifier ) { operation = new_operation; modify_ = new_modify_; combine = new_combine; neutral_modifier = new_neutral_modifier; } INDEX innode(node *C, const INDEX& Limit) { return Limit-C->LeftLimit; } void force_deletion() { Root.Left.safe_deletion(); if (Root.Right != NULL) { delete Root.Right; Root.Right = NULL; } } void safe_deletion() { if (defined) force_deletion(); } public: segment_tree() : defined(false) {} ~segment_tree() { safe_deletion(); } void construct( TYPE *begin, TYPE *end, TYPE new_operation(const TYPE&, const TYPE&), TYPE new_modify_(const TYPE&, const MODIFIER_TYPE&, const INDEX&), MODIFIER_TYPE new_combine(const MODIFIER_TYPE&, const MODIFIER_TYPE&), const MODIFIER_TYPE& new_neutral_modifier ) { set_variables( new_operation, new_modify_, new_combine, new_neutral_modifier ); INDEX amount_to_process = end-begin, current = highest_bit_of(amount_to_process), newright = 0; node *Subtree = &Root; while(amount_to_process != current) { Subtree->Left.construct(begin, begin+current, this); begin += current; Subtree->LeftLimit = newright; newright = Subtree->LeftLimit+current; Subtree->RightLimit = newright-1; amount_to_process ^= current; // equivalent to amount_to_process -=... current = highest_bit_of(amount_to_process); Subtree->Right = new node; Subtree = Subtree->Right; } Subtree->Left.construct(begin, begin+current, this); Subtree->LeftLimit = newright; Subtree->RightLimit = newright+current-1; defined = true; } void read( const INDEX& amount_of_elements, TYPE preprocessor(), TYPE new_operation(const TYPE&, const TYPE&), TYPE new_modify_(const TYPE&, const MODIFIER_TYPE&, const INDEX&), MODIFIER_TYPE new_combine(const MODIFIER_TYPE&, const MODIFIER_TYPE&), const MODIFIER_TYPE& new_neutral_modifier ) { set_variables( new_operation, new_modify_, new_combine, new_neutral_modifier ); INDEX amount_to_process = amount_of_elements, current = highest_bit_of(amount_to_process), newright = 0; node *Subtree = &Root; while(amount_to_process != current) { Subtree->Left.read(current, preprocessor, this); Subtree->LeftLimit = newright; newright = Subtree->LeftLimit+current; Subtree->RightLimit = newright-1; amount_to_process ^= current; // equivalent to amount_to_process -=... current = highest_bit_of(amount_to_process); Subtree->Right = new node; Subtree = Subtree->Right; } Subtree->Left.read(current, preprocessor, this); Subtree->LeftLimit = newright; Subtree->RightLimit = newright+current-1; defined = true; } TYPE result(const INDEX& first_required_left, const INDEX& required_right) { TYPE answer; node *C = &Root; INDEX required_left = first_required_left; while(C->RightLimit < required_left) C = C->Right; INDEX current_right = std::min(C->RightLimit, required_right); answer = C->Left.result( innode(C, required_left), innode(C, current_right) ); required_left = C->RightLimit+1; C = C->Right; while(required_left <= required_right) { current_right = std::min(C->RightLimit, required_right); answer = operation( answer, C->Left.result( innode(C, required_left), innode(C, current_right) ) ); required_left = C->RightLimit+1; C = C->Right; } return answer; } void modify(const INDEX& first_required_left, const INDEX& required_right, const MODIFIER_TYPE& modifier) { node *C = &Root; INDEX required_left = first_required_left; while(C->RightLimit < required_left) C = C->Right; while(required_left <= required_right) { INDEX current_right = std::min(C->RightLimit, required_right); C->Left.modify( innode(C, required_left), innode(C, current_right), modifier ); required_left = C->RightLimit+1; C = C->Right; } } void modify(const INDEX& index, const MODIFIER_TYPE& modifier) { modify(index, index, modifier); } }; |
STMM: version 1.2.0 (stack-using)
In this version of the tree data structure std::stack is being used. Recommended to use only to prevent system stack’s overload (in the tasks with excessively big amount \(n\) of elements of array), because recursive realization of the tree works (approximately) 26% quicker, than this one.
|
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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 |
// Copyright (c) http://vgworld.name/the-universal-segment-tree #include <algorithm> // std::min, size_t #include <stack> // std::stack template <typename TYPE> TYPE highest_bit_of(const TYPE& Num) { TYPE answer; (answer = 1) <<= (sizeof(TYPE)*8 - 1); while((answer&Num) != answer) answer >>= 1; return answer; } template <typename TYPE, typename MODIFIER_TYPE, typename INDEX = size_t> class segment_tree { TYPE (*operation)(const TYPE&, const TYPE&); TYPE (*modify_)(const TYPE&, const MODIFIER_TYPE&, const INDEX&); MODIFIER_TYPE (*combine)(const MODIFIER_TYPE&, const MODIFIER_TYPE&); MODIFIER_TYPE neutral_modifier; bool defined; struct plan_element { INDEX vertex, viewed_left, viewed_right, required_left, required_right; plan_element( const INDEX& vertex, const INDEX& viewed_left, const INDEX& viewed_right, const INDEX& required_left, const INDEX& required_right ) { this->vertex = vertex; this->viewed_left = viewed_left; this->viewed_right = viewed_right; this->required_left = required_left; this->required_right = required_right; } plan_element(const plan_element& Other) { this->vertex = Other.vertex; this->viewed_left = Other.viewed_left; this->viewed_right = Other.viewed_right; this->required_left = Other.required_left; this->required_right = Other.required_right; } }; struct binary_segment_tree { segment_tree *Parent; TYPE *SegmentTree; MODIFIER_TYPE *ModifierList; INDEX amount_in_array; bool defined; void force_deletion() { delete[] SegmentTree; if (amount_in_array > 1) delete[] ModifierList; defined = false; } void safe_deletion() { if (defined) // if defined == true force_deletion(); } void set_results_on_segments() { if (amount_in_array > 1) { ModifierList = new MODIFIER_TYPE[amount_in_array-1]; for(INDEX i = amount_in_array-1; i;) { --i; SegmentTree[i] = Parent->operation( SegmentTree[2*i+1], SegmentTree[2*i+2] ); ModifierList[i] = Parent->neutral_modifier; } } defined = true; } void build_tree_from_preprocessor(TYPE preprocessor()) { SegmentTree = new TYPE[2*amount_in_array-1]; const INDEX right_limit_ = 2*amount_in_array-1; for(INDEX i = amount_in_array-1; i < right_limit_; ++i) SegmentTree[i] = preprocessor(); set_results_on_segments(); } void build_tree_from_array(TYPE *array) { SegmentTree = new TYPE[2*amount_in_array-1]; const INDEX right_limit_ = 2*amount_in_array-1; for(INDEX i = amount_in_array-1; i < right_limit_; ++i) SegmentTree[i] = *(array++); set_results_on_segments(); } void try_push(const INDEX& vertex, const INDEX& left, const INDEX& right) { if (vertex < amount_in_array-1) if (ModifierList[vertex] != Parent->neutral_modifier) { INDEX i = 2*vertex+1, amount_of_elements=(right-left+1)/2; SegmentTree[i] = Parent->modify_(SegmentTree[i], ModifierList[vertex], amount_of_elements); SegmentTree[i+1] = Parent->modify_(SegmentTree[i+1], ModifierList[vertex], amount_of_elements); if (i+1 < amount_in_array-1) { ModifierList[i] = Parent->combine(ModifierList[i], ModifierList[vertex]); ModifierList[i+1] = Parent->combine(ModifierList[i+1], ModifierList[vertex]); } ModifierList[vertex] = Parent->neutral_modifier; } } void update_plan(std::stack<plan_element> &Plan, plan_element& C) { try_push(C.vertex, C.viewed_left, C.viewed_right); INDEX left_middle = (C.viewed_left+C.viewed_right)/2, right_middle = left_middle+1; if (C.required_right <= left_middle) Plan.push(plan_element( 2*C.vertex+1, C.viewed_left, left_middle, C.required_left, C.required_right )); else if (right_middle <= C.required_left) Plan.push(plan_element( 2*C.vertex+2, right_middle, C.viewed_right, C.required_left, C.required_right )); else { Plan.push(plan_element( 2*C.vertex+2, right_middle, C.viewed_right, right_middle, C.required_right )); Plan.push(plan_element( 2*C.vertex+1, C.viewed_left, left_middle, C.required_left, left_middle )); } } public: binary_segment_tree() : defined(false) {} ~binary_segment_tree() { safe_deletion(); } const INDEX& amount() const { return amount_in_array; } void destroy() { if (defined) // defined == true force_deletion(); else throw("ERROR in binary_segment_tree: trying to delete undefined tree."); } void construct( TYPE *begin, TYPE *end, segment_tree *NewParent ) { Parent=NewParent; safe_deletion(); amount_in_array = end-begin, build_tree_from_array(begin); } void read( const INDEX& amount_of_elements, TYPE preprocessing_function(), segment_tree *NewParent ) { Parent=NewParent; safe_deletion(); amount_in_array = amount_of_elements; build_tree_from_preprocessor(preprocessing_function); } const TYPE& result(const INDEX& left, const INDEX& right) { std::stack <plan_element> Plan; Plan.push(plan_element(0, 0, amount_in_array-1, left, right)); TYPE answer; for(bool not_assigned = true; not_assigned; ) { plan_element C = Plan.top(); // C = Current Plan.pop(); if ((C.viewed_left==C.required_left) && (C.viewed_right==C.required_right)) { answer = SegmentTree[C.vertex]; not_assigned = false; } else update_plan(Plan, C); } while(!Plan.empty()) { plan_element C = Plan.top(); // C = Current Plan.pop(); if ((C.viewed_left==C.required_left) && (C.viewed_right==C.required_right)) answer = Parent->operation(answer, SegmentTree[C.vertex]); else update_plan(Plan, C); } return answer; } void modify(const INDEX& left, const INDEX& right, const MODIFIER_TYPE& modifier) { std::stack <plan_element> Modify; std::stack <INDEX> Update; Modify.push(plan_element(0, 0, amount_in_array-1, left, right)); while(!Modify.empty()) { plan_element C(Modify.top()); // C = Current Modify.pop(); if ((C.viewed_left==C.required_left) && (C.viewed_right==C.required_right)) { SegmentTree[C.vertex] = Parent->modify_( SegmentTree[C.vertex], modifier, C.viewed_right-C.viewed_left+1 ); if (C.vertex < amount_in_array-1) ModifierList[C.vertex] = Parent->combine( ModifierList[C.vertex], modifier ); } else { Update.push(C.vertex); update_plan(Modify, C); } } while(!Update.empty()) { INDEX vertex = Update.top(); Update.pop(); SegmentTree[vertex] = Parent->operation( SegmentTree[2*vertex+1], SegmentTree[2*vertex+2] ); } } }; struct node { binary_segment_tree Left; node *Right; node() : Right(NULL) {} ~node() { Left.safe_deletion(); if (Right != NULL) delete Right; } INDEX LeftLimit, RightLimit; }; node Root; void set_variables( TYPE new_operation(const TYPE&, const TYPE&), TYPE new_modify_(const TYPE&, const MODIFIER_TYPE&, const INDEX&), MODIFIER_TYPE new_combine(const MODIFIER_TYPE&, const MODIFIER_TYPE&), const MODIFIER_TYPE& new_neutral_modifier ) { operation = new_operation; modify_ = new_modify_; combine = new_combine; neutral_modifier = new_neutral_modifier; } INDEX innode(node *C, const INDEX& Limit) { return Limit-C->LeftLimit; } void force_deletion() { Root.Left.safe_deletion(); if (Root.Right != NULL) { delete Root.Right; Root.Right = NULL; } } void safe_deletion() { if (defined) force_deletion(); } public: segment_tree() : defined(false) {} ~segment_tree() { safe_deletion(); } void construct( TYPE *begin, TYPE *end, TYPE new_operation(const TYPE&, const TYPE&), TYPE new_modify_(const TYPE&, const MODIFIER_TYPE&, const INDEX&), MODIFIER_TYPE new_combine(const MODIFIER_TYPE&, const MODIFIER_TYPE&), const MODIFIER_TYPE& new_neutral_modifier ) { set_variables( new_operation, new_modify_, new_combine, new_neutral_modifier ); INDEX amount_to_process = end-begin, current = highest_bit_of(amount_to_process), newright = 0; node *Subtree = &Root; while(amount_to_process != current) { Subtree->Left.construct(begin, begin+current, this); begin += current; Subtree->LeftLimit = newright; newright = Subtree->LeftLimit+current; Subtree->RightLimit = newright-1; amount_to_process ^= current; // equivalent to amount_to_process -=... current = highest_bit_of(amount_to_process); Subtree->Right = new node; Subtree = Subtree->Right; } Subtree->Left.construct(begin, begin+current, this); Subtree->LeftLimit = newright; Subtree->RightLimit = newright+current-1; defined = true; } void read( const INDEX& amount_of_elements, TYPE preprocessor(), TYPE new_operation(const TYPE&, const TYPE&), TYPE new_modify_(const TYPE&, const MODIFIER_TYPE&, const INDEX&), MODIFIER_TYPE new_combine(const MODIFIER_TYPE&, const MODIFIER_TYPE&), const MODIFIER_TYPE& new_neutral_modifier ) { set_variables( new_operation, new_modify_, new_combine, new_neutral_modifier ); INDEX amount_to_process = amount_of_elements, current = highest_bit_of(amount_to_process), newright = 0; node *Subtree = &Root; while(amount_to_process != current) { Subtree->Left.read(current, preprocessor, this); Subtree->LeftLimit = newright; newright = Subtree->LeftLimit+current; Subtree->RightLimit = newright-1; amount_to_process ^= current; // equivalent to amount_to_process -=... current = highest_bit_of(amount_to_process); Subtree->Right = new node; Subtree = Subtree->Right; } Subtree->Left.read(current, preprocessor, this); Subtree->LeftLimit = newright; Subtree->RightLimit = newright+current-1; defined = true; } TYPE result(const INDEX& first_required_left, const INDEX& required_right) { TYPE answer; node *C = &Root; INDEX required_left = first_required_left; while(C->RightLimit < required_left) C = C->Right; INDEX current_right = std::min(C->RightLimit, required_right); answer = C->Left.result( innode(C, required_left), innode(C, current_right) ); required_left = C->RightLimit+1; C = C->Right; while(required_left <= required_right) { current_right = std::min(C->RightLimit, required_right); answer = operation( answer, C->Left.result( innode(C, required_left), innode(C, current_right) ) ); required_left = C->RightLimit+1; C = C->Right; } return answer; } void modify(const INDEX& first_required_left, const INDEX& required_right, const MODIFIER_TYPE& modifier) { node *C = &Root; INDEX required_left = first_required_left; while(C->RightLimit < required_left) C = C->Right; while(required_left <= required_right) { INDEX current_right = std::min(C->RightLimit, required_right); C->Left.modify( innode(C, required_left), innode(C, current_right), modifier ); required_left = C->RightLimit+1; C = C->Right; } } void modify(const INDEX& index, const MODIFIER_TYPE& modifier) { modify(index, index, modifier); } }; |
Conditions of the STMM’s applicability
Must be defined extended set of modifiers \(M_{2}\), which satisfies condition:
- if exists certain neutral modifier \(e_{M} \in M\), which satisfies condition \(\forall a \in G:\) \(f \left( a, e_{M} \right)\) \(=\) \(a\), then \(M_{2}\) \(=\) \(M\),
- else must be defined an element \(e_{M}\), which is a neutral marker (i. e. formal neutral modifier) and which satisfies condition \(e_{M} \notin M\), and then \(M_{2}\) \(=\) \(M \cup \{ e_{M} \}\).
For the function-modifier \(f\):
- must exist combining function \(C: M_{2} \times M \to M\), which combines accumulated modifiers, and satisfies conditions:
- condition of unification: \(\forall a \in G\), \(\forall m_{1}, m_{2} \in M\): \(f \left( a, {C \left( m_{1}, m_{2} \right)} \right)\) \(=\) \(f \left( {f \left( a, m_{1} \right)}, m_{2} \right)\);
- condition of the neutral modifier/marker: \(\forall m \in M\): \(C \left( e_{M}, m \right)\) \(=\) \(m\)
- must exist distributing function \(K: M \times \mathbb{N} \to M\), which distributes modifier, applied to the whole segment of certain length, and which for the segment \(\left[ l, r \right]\), which is being modified by modifier \(m \in M\), where \(a_{l}\), \(a_{l+1}\), \(\ldots\), \(a_{r-1}\), \(a_{r}\) – modified elements of this segment, and \(\delta = r – l + 1 \ge 1\) – amount of these elements, satisfies condition:
\(f \left( {a_{l} \circ a_{l+1} \circ \ldots \circ a_{r-1} \circ a_{r}}, {K \left( m, \delta \right)} \right)\) \(=\) \(f \left( a_{l}, m \right) \circ f \left( a_{l+1}, m \right) \circ \ldots \circ f \left( a_{r-1}, m \right) \circ f \left( a_{r}, m \right)\) - according to the distributing function \(K\) must be defined an extended function-modifier \(F: G \times M \times \mathbb{N} \to G\), which modifies result on segment \(\left[ l, r \right]\) with amount of elements \(\delta = r – l + 1\):
\(F \left( {a_{l} \circ a_{l+1} \circ \ldots \circ a_{r-1} \circ a_{r}}, m, \delta \right)\) \(=\) \(f \left( {a_{l} \circ a_{l+1} \circ \ldots \circ a_{r-1} \circ a_{r}}, {K \left( m, \delta \right)} \right)\).Note
I want to note, that for the case, when only one element with the number \(i\) is modified, i.e. then, when left and right limits of modified segment are equal \(l = r = i\), and \(\delta = 1\), extended function-modifier \(F\) by its definition equals to the initial \(f\):
\(F \left( a_{i}, m, \delta \right)\) \(=\) \(F \left( a_{i}, m, 1 \right)\) \(=\) \(f \left( a_i, m \right)\). This makes STMM applicable even for the tasks, in which not the segments, but separate elements of the array are modified (so called tasks of single modifications).
Documentation of the universal STMM
Manual of usage
- Copy the code of universal STMM into the program, where its usage is planned, or include it from an independent library.
- Define the data structures with public constructors without arguments, which satisfy the role of observed operands from the set \(G\) and the role of modifiers from the set \(M_{2}\):
1234567891011121314151617181920212223242526272829class element_G {... ... ...... ... ...... ... ...public:element_G() {... ... ...... ... ...... ... ...}... ... ...... ... ...... ... ...};class element_M2 {... ... ...... ... ...... ... ...public:element_M2() {... ... ...... ... ...... ... ...}... ... ...... ... ...... ... ...};
Note: depending on the task, the used data structures/types may be already defined. For example, the role of observed elements and modifiers may be played by the standard data type int. That’s why this item of the list may be unnecessary, depending on the task.
- Describe the given on the set \(G\) operation \(\circ\), extended modifier-function \(F\) and combining function \(C\):
1234567891011121314151617181920element_G operation(const element_G& argument1, const element_G& argument2){... ... ...... ... ...... ... ...}element_G F(const element_G& value, const element_M2 modifier, const size_t& amount_of_elements){... ... ...... ... ...... ... ...}element_M2 C(const element_M2& old_modification, const element_M2& new_modification){... ... ...... ... ...... ... ...}
- Define object of “segment tree” type, by giving it as parameters for the template types of operands and modifiers:
1segment_tree <element_G, element_M2> Tree;
- Construct the segment tree with one of methods:
- method
read:
Describe the function-preprocessor (which, for example, reads the data directly from the input stream, processes them and using them builds elements of array from the statement), which will create elements of the array from the task one-by-one from the element with number \(0\) and to the element with number \(n-1\).123456element_G preprocessing_function(){... ... ...... ... ...... ... ...}With function-preprocessor and known amount of the elements \(n\) build the segment tree, with calling method read, by giving it as an arguments respectively amount of elements \(n\), function-preprocessor, operation \(\circ\), extended function-modifier \(F\), combining function \(C\) and neutral modifier/marker \(e_{M}\):
123unsigned int n;cin >> n;Tree.read(n, preprocessing_function, operation, neutral_element, F, C, neutral_modifier); - method
construct:
Define certain non-empty array of elements \(G\) with address of the beginning begin and address of the end end (i. e. all the elements \(a_{i}\) must be in the interval \(\left[ {begin}, {end} \right)\), and if array has length \(n\), then end \(=\) begin+n)
Build the segment tree, by calling method construct, giving it as an arguments respectively address of the beginning of the array, address of the end of the array, operation \(\circ\), extended modifier-function \(F\), combine function \(C\) and neutral modifier/marker \(e_{M}\):1Tree.construct(begin, end, operation, F, C, neutral_modifier);First the data structure will copy the initial array, and then basing it builds the segment tree. This method is useful, when there is a need to save the initial array, and use it in the future.
- method
read:
- Perform the query of result and modification according to the following:
- Define left and right limits of the observed segment:
12unsigned int left, right;...
- Define the type of query to the segment tree, and call the method of the tree the corresponding to this query:
- for the requests of segment modification:
define certain modifier m:12element_M2 m;...and call the segment tree’s method modify, with giving it as an arguments left limit of modified segment, right limit of modified segment and modifier m:
1Tree.modify(left, right, m); - for queries of the result of operation \(\circ\) on a segment call method
result, by giving it as an arguments the left and the right limits of modified segment:
1Tree.result(left, right);
- for the requests of segment modification:
- Define left and right limits of the observed segment:
Methods of class
Denotations:
- \(n\) – amount of elements in the initial array.
- \(m_{G}\) – amount of memory, taken by the element of set \(G\)
- \(m_{M}\) – amount of memory, taken by the modifier from set \(M_{2}\)
- \(c_{F}\) – complexity of modification of element of set \(G\) with extended modifier-function \(F\).
- \(c_{C}\) – complexity of combining function \(C\).
- \(c_{\circ}\) – complexity of perfomance of a single operation \(\circ\).
- TYPE – type of operands of set \(G\).
- MODIFIER_TYPE – type of modifiers from set \(M_{2}\).
| Name of method | Description of method |
|---|---|
| construct |
Type of returned value:
void
Arguments
Time usage: \(O \left( {c_{\circ}} \cdot n \right)\); \(2 \cdot n + {\log_{2}{n}} + n \cdot {c_{\circ}}\) in the worst case, \(2 \cdot n + n \cdot c_{\circ}\) in the best. |
| read |
Type of returned value:
void
Arguments
Time usage: \(O \left( {c_{\circ}} \cdot n \right)\); \(2 \cdot n + {\log_{2}{n}} + n \cdot {c_{\circ}}\) in the worst case, \(2 \cdot n + n \cdot c_{\circ}\) in the best. |
| modify |
Type of returned value:
void
Arguments
Time usage: \(O \left( \left( c_{F} + c_{C} + c_{\circ} \right) \cdot \log_{2}{n} \right)\); \(\left( c_{F} + c_{C} + c_{\circ} \right) \cdot 2 \cdot \log_{2}{n}\) in the worst case, \(\left( c_{F} + c_{C} + c_{\circ} \right) \cdot \log_{2}{n}\) in the best. |
| modify |
Type of returned value:
void
Arguments
Time usage: \(O \left( \left( c_{F} + c_{C} + c_{\circ} \right) \cdot \log_{2}{n} \right)\); \(\left( c_{F} + c_{C} + c_{\circ} \right) \cdot 2 \cdot \log_{2}{n}\) in the worst case, \(\left( c_{F} + c_{C} + c_{\circ} \right) \cdot \log_{2}{n}\) in the best. |
| result |
Type of returned value:
TYPE
Arguments
Time usage: \(O \left( \left( c_{F} + c_{C} + c_{\circ} \right) \cdot \log_{2}{n} \right)\); \(\left( c_{F} + c_{C} + c_{\circ} \right) \cdot 2 \cdot \log_{2}{n}\) in the worst case, \(\left( c_{F} + c_{C} + c_{\circ} \right) \cdot \log_{2}{n}\) in the best. |