-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathadvanced-ds.html
More file actions
1528 lines (1321 loc) · 92.2 KB
/
advanced-ds.html
File metadata and controls
1528 lines (1321 loc) · 92.2 KB
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Advanced Data Structures - Better Dev</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group"><a href="index.html">Home</a></div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / Advanced Data Structures</div>
<h1>Advanced Data Structures</h1>
<p>The data structures that separate Div 2 solvers from Div 1 solvers. Fenwick trees, segment trees with lazy propagation, sparse tables, HLD, centroid decomposition, treaps, and more -- with full implementations in Python and C++.</p>
</div>
<div class="toc">
<h4>Table of Contents</h4>
<a href="#fenwick">1. Fenwick Tree (BIT)</a>
<a href="#segtree">2. Segment Tree Deep Dive</a>
<a href="#sparse-table">3. Sparse Table</a>
<a href="#dsu">4. DSU Advanced</a>
<a href="#hld">5. Heavy-Light Decomposition</a>
<a href="#centroid">6. Centroid Decomposition</a>
<a href="#treap">7. Treap / Implicit Treap</a>
<a href="#lichao">8. Li Chao Tree</a>
<a href="#sqrt">9. Sqrt Decomposition / Mo's Algorithm</a>
<a href="#persistent">10. Persistent Data Structures</a>
<a href="#practice">11. Practice Problems</a>
</div>
<!-- ========== 1. FENWICK TREE ========== -->
<section id="fenwick" class="section">
<h2>1. Fenwick Tree (Binary Indexed Tree)</h2>
<p>A Fenwick tree (BIT) supports <strong>point updates</strong> and <strong>prefix queries</strong> in O(log n) with minimal memory. The key insight: every index i is responsible for a range of elements determined by the lowest set bit of i.</p>
<div class="formula-box">
<div class="label">Core Operations</div>
<p><strong>lowbit(x)</strong> = x & (-x) -- isolates the lowest set bit</p>
<p><strong>Update(i, delta)</strong>: add delta to index i, then i += lowbit(i) until i > n</p>
<p><strong>Query(i)</strong>: sum from [1..i], subtract lowbit(i) from i until i == 0</p>
<p>Both operations: <strong>O(log n)</strong> time, <strong>O(n)</strong> space</p>
</div>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">BIT</span> {
<span class="keyword">int</span> n;
vector<<span class="keyword">long long</span>> tree;
<span class="function">BIT</span>(<span class="keyword">int</span> n) : n(n), tree(n + <span class="number">1</span>, <span class="number">0</span>) {}
<span class="keyword">void</span> <span class="function">update</span>(<span class="keyword">int</span> i, <span class="keyword">long long</span> delta) {
<span class="keyword">for</span> (; i <= n; i += i & (-i))
tree[i] += delta;
}
<span class="keyword">long long</span> <span class="function">query</span>(<span class="keyword">int</span> i) {
<span class="keyword">long long</span> s = <span class="number">0</span>;
<span class="keyword">for</span> (; i > <span class="number">0</span>; i -= i & (-i))
s += tree[i];
<span class="keyword">return</span> s;
}
<span class="keyword">long long</span> <span class="function">query</span>(<span class="keyword">int</span> l, <span class="keyword">int</span> r) {
<span class="keyword">return</span> <span class="function">query</span>(r) - <span class="function">query</span>(l - <span class="number">1</span>);
}
};
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">BIT</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, n):
self.n = n
self.tree = [<span class="number">0</span>] * (n + <span class="number">1</span>)
<span class="keyword">def</span> <span class="function">update</span>(self, i, delta):
<span class="keyword">while</span> i <= self.n:
self.tree[i] += delta
i += i & (-i)
<span class="keyword">def</span> <span class="function">query</span>(self, i):
s = <span class="number">0</span>
<span class="keyword">while</span> i > <span class="number">0</span>:
s += self.tree[i]
i -= i & (-i)
<span class="keyword">return</span> s
<span class="keyword">def</span> <span class="function">range_query</span>(self, l, r):
<span class="keyword">return</span> self.<span class="function">query</span>(r) - self.<span class="function">query</span>(l - <span class="number">1</span>)
</code></pre>
<div class="tip-box">
<div class="label">Why Fenwick over Segment Tree?</div>
<p>Fenwick trees use half the memory (n+1 vs 4n), have smaller constants, and the code is much shorter. Use them whenever you only need prefix sums + point updates. Switch to a segment tree when you need lazy propagation or non-invertible operations (like min/max).</p>
</div>
<h3>Range Update + Point Query BIT</h3>
<p>To support range updates [l, r] += val and point queries, use a difference array approach: update(l, val) and update(r+1, -val). Then query(i) gives the value at index i.</p>
<pre><code><span class="lang-label">C++</span>
<span class="comment">// Range update [l, r] += val, point query at i</span>
<span class="keyword">void</span> <span class="function">range_update</span>(BIT& bit, <span class="keyword">int</span> l, <span class="keyword">int</span> r, <span class="keyword">long long</span> val) {
bit.<span class="function">update</span>(l, val);
bit.<span class="function">update</span>(r + <span class="number">1</span>, -val);
}
<span class="comment">// query(i) now returns the actual value at position i</span>
</code></pre>
<h3>Range Update + Range Query (Two BITs)</h3>
<p>Maintain two BITs: B1 and B2. For range update [l, r] += val:</p>
<div class="formula-box">
<div class="label">Two-BIT Range Update/Query</div>
<p>B1.update(l, val), B1.update(r+1, -val)</p>
<p>B2.update(l, val*(l-1)), B2.update(r+1, -val*r)</p>
<p>prefix_sum(i) = B1.query(i) * i - B2.query(i)</p>
</div>
<h3>2D Fenwick Tree</h3>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">BIT2D</span> {
<span class="keyword">int</span> N, M;
vector<vector<<span class="keyword">long long</span>>> tree;
<span class="function">BIT2D</span>(<span class="keyword">int</span> n, <span class="keyword">int</span> m) : N(n), M(m), tree(n + <span class="number">1</span>, vector<<span class="keyword">long long</span>>(m + <span class="number">1</span>, <span class="number">0</span>)) {}
<span class="keyword">void</span> <span class="function">update</span>(<span class="keyword">int</span> x, <span class="keyword">int</span> y, <span class="keyword">long long</span> val) {
<span class="keyword">for</span> (<span class="keyword">int</span> i = x; i <= N; i += i & (-i))
<span class="keyword">for</span> (<span class="keyword">int</span> j = y; j <= M; j += j & (-j))
tree[i][j] += val;
}
<span class="keyword">long long</span> <span class="function">query</span>(<span class="keyword">int</span> x, <span class="keyword">int</span> y) {
<span class="keyword">long long</span> s = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> i = x; i > <span class="number">0</span>; i -= i & (-i))
<span class="keyword">for</span> (<span class="keyword">int</span> j = y; j > <span class="number">0</span>; j -= j & (-j))
s += tree[i][j];
<span class="keyword">return</span> s;
}
<span class="keyword">long long</span> <span class="function">query</span>(<span class="keyword">int</span> x1, <span class="keyword">int</span> y1, <span class="keyword">int</span> x2, <span class="keyword">int</span> y2) {
<span class="keyword">return</span> <span class="function">query</span>(x2, y2) - <span class="function">query</span>(x1 - <span class="number">1</span>, y2)
- <span class="function">query</span>(x2, y1 - <span class="number">1</span>) + <span class="function">query</span>(x1 - <span class="number">1</span>, y1 - <span class="number">1</span>);
}
};
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">BIT2D</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, n, m):
self.N, self.M = n, m
self.tree = [[<span class="number">0</span>] * (m + <span class="number">1</span>) <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="builtin">range</span>(n + <span class="number">1</span>)]
<span class="keyword">def</span> <span class="function">update</span>(self, x, y, val):
i = x
<span class="keyword">while</span> i <= self.N:
j = y
<span class="keyword">while</span> j <= self.M:
self.tree[i][j] += val
j += j & (-j)
i += i & (-i)
<span class="keyword">def</span> <span class="function">query</span>(self, x, y):
s = <span class="number">0</span>
i = x
<span class="keyword">while</span> i > <span class="number">0</span>:
j = y
<span class="keyword">while</span> j > <span class="number">0</span>:
s += self.tree[i][j]
j -= j & (-j)
i -= i & (-i)
<span class="keyword">return</span> s
</code></pre>
<div class="example-box">
<div class="label">ASCII: BIT Structure (n=8)</div>
<pre>
Index: 1 2 3 4 5 6 7 8
lowbit: 1 2 1 4 1 2 1 8
Responsibility ranges:
tree[1] = a[1]
tree[2] = a[1..2]
tree[3] = a[3]
tree[4] = a[1..4]
tree[5] = a[5]
tree[6] = a[5..6]
tree[7] = a[7]
tree[8] = a[1..8]
query(7) = tree[7] + tree[6] + tree[4]
= a[7] + a[5..6] + a[1..4]
= a[1..7] (remove lowest bit each step: 7->6->4->0)
</pre>
</div>
</section>
<!-- ========== 2. SEGMENT TREE ========== -->
<section id="segtree" class="section">
<h2>2. Segment Tree Deep Dive</h2>
<p>The most versatile range query data structure in competitive programming. Supports arbitrary associative operations, range updates with lazy propagation, and can be made persistent.</p>
<div class="formula-box">
<div class="label">Complexity</div>
<p><strong>Build</strong>: O(n) | <strong>Update</strong>: O(log n) | <strong>Query</strong>: O(log n) | <strong>Space</strong>: O(4n)</p>
</div>
<h3>Build, Update, Query (Sum)</h3>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">SegTree</span> {
<span class="keyword">int</span> n;
vector<<span class="keyword">long long</span>> tree;
<span class="function">SegTree</span>(<span class="keyword">int</span> n) : n(n), tree(<span class="number">4</span> * n, <span class="number">0</span>) {}
<span class="keyword">void</span> <span class="function">build</span>(vector<<span class="keyword">int</span>>& a, <span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr) {
<span class="keyword">if</span> (tl == tr) {
tree[v] = a[tl];
<span class="keyword">return</span>;
}
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="function">build</span>(a, <span class="number">2</span>*v, tl, tm);
<span class="function">build</span>(a, <span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr);
tree[v] = tree[<span class="number">2</span>*v] + tree[<span class="number">2</span>*v+<span class="number">1</span>];
}
<span class="keyword">void</span> <span class="function">update</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr, <span class="keyword">int</span> pos, <span class="keyword">int</span> val) {
<span class="keyword">if</span> (tl == tr) {
tree[v] = val;
<span class="keyword">return</span>;
}
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="keyword">if</span> (pos <= tm)
<span class="function">update</span>(<span class="number">2</span>*v, tl, tm, pos, val);
<span class="keyword">else</span>
<span class="function">update</span>(<span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr, pos, val);
tree[v] = tree[<span class="number">2</span>*v] + tree[<span class="number">2</span>*v+<span class="number">1</span>];
}
<span class="keyword">long long</span> <span class="function">query</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr, <span class="keyword">int</span> l, <span class="keyword">int</span> r) {
<span class="keyword">if</span> (l > r) <span class="keyword">return</span> <span class="number">0</span>;
<span class="keyword">if</span> (l == tl && r == tr) <span class="keyword">return</span> tree[v];
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="keyword">return</span> <span class="function">query</span>(<span class="number">2</span>*v, tl, tm, l, <span class="builtin">min</span>(r, tm))
+ <span class="function">query</span>(<span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr, <span class="builtin">max</span>(l, tm+<span class="number">1</span>), r);
}
};
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">SegTree</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, n):
self.n = n
self.tree = [<span class="number">0</span>] * (<span class="number">4</span> * n)
<span class="keyword">def</span> <span class="function">build</span>(self, a, v, tl, tr):
<span class="keyword">if</span> tl == tr:
self.tree[v] = a[tl]
<span class="keyword">return</span>
tm = (tl + tr) // <span class="number">2</span>
self.<span class="function">build</span>(a, <span class="number">2</span>*v, tl, tm)
self.<span class="function">build</span>(a, <span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr)
self.tree[v] = self.tree[<span class="number">2</span>*v] + self.tree[<span class="number">2</span>*v+<span class="number">1</span>]
<span class="keyword">def</span> <span class="function">update</span>(self, v, tl, tr, pos, val):
<span class="keyword">if</span> tl == tr:
self.tree[v] = val
<span class="keyword">return</span>
tm = (tl + tr) // <span class="number">2</span>
<span class="keyword">if</span> pos <= tm:
self.<span class="function">update</span>(<span class="number">2</span>*v, tl, tm, pos, val)
<span class="keyword">else</span>:
self.<span class="function">update</span>(<span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr, pos, val)
self.tree[v] = self.tree[<span class="number">2</span>*v] + self.tree[<span class="number">2</span>*v+<span class="number">1</span>]
<span class="keyword">def</span> <span class="function">query</span>(self, v, tl, tr, l, r):
<span class="keyword">if</span> l > r:
<span class="keyword">return</span> <span class="number">0</span>
<span class="keyword">if</span> l == tl <span class="keyword">and</span> r == tr:
<span class="keyword">return</span> self.tree[v]
tm = (tl + tr) // <span class="number">2</span>
<span class="keyword">return</span> (self.<span class="function">query</span>(<span class="number">2</span>*v, tl, tm, l, <span class="builtin">min</span>(r, tm))
+ self.<span class="function">query</span>(<span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr, <span class="builtin">max</span>(l, tm+<span class="number">1</span>), r))
</code></pre>
<div class="example-box">
<div class="label">ASCII: Segment Tree for [2, 1, 5, 3] (sum)</div>
<pre>
[11] node 1: sum(0..3)
/ \
[3] [8] node 2: sum(0..1), node 3: sum(2..3)
/ \ / \
[2] [1] [5] [3] leaves: a[0], a[1], a[2], a[3]
query(1, 2) = go left child right + go right child left
= tree[5]=1 + tree[6]=5 = 6
</pre>
</div>
<h3>Lazy Propagation (Range Add + Range Sum)</h3>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">LazySegTree</span> {
<span class="keyword">int</span> n;
vector<<span class="keyword">long long</span>> tree, lazy;
<span class="function">LazySegTree</span>(<span class="keyword">int</span> n) : n(n), tree(<span class="number">4</span>*n, <span class="number">0</span>), lazy(<span class="number">4</span>*n, <span class="number">0</span>) {}
<span class="keyword">void</span> <span class="function">push</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr) {
<span class="keyword">if</span> (lazy[v]) {
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="function">apply</span>(<span class="number">2</span>*v, tl, tm, lazy[v]);
<span class="function">apply</span>(<span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr, lazy[v]);
lazy[v] = <span class="number">0</span>;
}
}
<span class="keyword">void</span> <span class="function">apply</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr, <span class="keyword">long long</span> val) {
tree[v] += val * (tr - tl + <span class="number">1</span>);
lazy[v] += val;
}
<span class="keyword">void</span> <span class="function">update</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr, <span class="keyword">int</span> l, <span class="keyword">int</span> r, <span class="keyword">long long</span> val) {
<span class="keyword">if</span> (l > r) <span class="keyword">return</span>;
<span class="keyword">if</span> (l == tl && r == tr) {
<span class="function">apply</span>(v, tl, tr, val);
<span class="keyword">return</span>;
}
<span class="function">push</span>(v, tl, tr);
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="function">update</span>(<span class="number">2</span>*v, tl, tm, l, <span class="builtin">min</span>(r, tm), val);
<span class="function">update</span>(<span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr, <span class="builtin">max</span>(l, tm+<span class="number">1</span>), r, val);
tree[v] = tree[<span class="number">2</span>*v] + tree[<span class="number">2</span>*v+<span class="number">1</span>];
}
<span class="keyword">long long</span> <span class="function">query</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr, <span class="keyword">int</span> l, <span class="keyword">int</span> r) {
<span class="keyword">if</span> (l > r) <span class="keyword">return</span> <span class="number">0</span>;
<span class="keyword">if</span> (l == tl && r == tr) <span class="keyword">return</span> tree[v];
<span class="function">push</span>(v, tl, tr);
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="keyword">return</span> <span class="function">query</span>(<span class="number">2</span>*v, tl, tm, l, <span class="builtin">min</span>(r, tm))
+ <span class="function">query</span>(<span class="number">2</span>*v+<span class="number">1</span>, tm+<span class="number">1</span>, tr, <span class="builtin">max</span>(l, tm+<span class="number">1</span>), r);
}
};
</code></pre>
<div class="warning-box">
<div class="label">Lazy Propagation Pitfall</div>
<p>Always push lazy values BEFORE recursing into children during both update and query. Forgetting to push is the #1 bug. Also make sure your apply function updates BOTH the tree node AND the lazy tag.</p>
</div>
<h3>Persistent Segment Tree</h3>
<p>Create a new version of the tree on each update by only copying the O(log n) nodes on the path from root to the updated leaf. All other nodes are shared between versions.</p>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">Node</span> {
<span class="keyword">int</span> left, right;
<span class="keyword">long long</span> val;
};
<span class="keyword">const</span> <span class="keyword">int</span> MAXNODES = <span class="number">20000000</span>;
Node nodes[MAXNODES];
<span class="keyword">int</span> cnt = <span class="number">0</span>;
<span class="keyword">int</span> <span class="function">newNode</span>(<span class="keyword">long long</span> v = <span class="number">0</span>, <span class="keyword">int</span> l = <span class="number">0</span>, <span class="keyword">int</span> r = <span class="number">0</span>) {
nodes[cnt] = {l, r, v};
<span class="keyword">return</span> cnt++;
}
<span class="keyword">int</span> <span class="function">build</span>(<span class="keyword">int</span> tl, <span class="keyword">int</span> tr) {
<span class="keyword">if</span> (tl == tr) <span class="keyword">return</span> <span class="function">newNode</span>(<span class="number">0</span>);
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="keyword">int</span> l = <span class="function">build</span>(tl, tm);
<span class="keyword">int</span> r = <span class="function">build</span>(tm + <span class="number">1</span>, tr);
<span class="keyword">return</span> <span class="function">newNode</span>(nodes[l].val + nodes[r].val, l, r);
}
<span class="keyword">int</span> <span class="function">update</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr, <span class="keyword">int</span> pos, <span class="keyword">long long</span> val) {
<span class="keyword">if</span> (tl == tr) <span class="keyword">return</span> <span class="function">newNode</span>(nodes[v].val + val);
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="keyword">int</span> l = nodes[v].left, r = nodes[v].right;
<span class="keyword">if</span> (pos <= tm)
l = <span class="function">update</span>(l, tl, tm, pos, val);
<span class="keyword">else</span>
r = <span class="function">update</span>(r, tm + <span class="number">1</span>, tr, pos, val);
<span class="keyword">return</span> <span class="function">newNode</span>(nodes[l].val + nodes[r].val, l, r);
}
<span class="keyword">long long</span> <span class="function">query</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> tl, <span class="keyword">int</span> tr, <span class="keyword">int</span> l, <span class="keyword">int</span> r) {
<span class="keyword">if</span> (l > r) <span class="keyword">return</span> <span class="number">0</span>;
<span class="keyword">if</span> (l == tl && r == tr) <span class="keyword">return</span> nodes[v].val;
<span class="keyword">int</span> tm = (tl + tr) / <span class="number">2</span>;
<span class="keyword">return</span> <span class="function">query</span>(nodes[v].left, tl, tm, l, <span class="builtin">min</span>(r, tm))
+ <span class="function">query</span>(nodes[v].right, tm+<span class="number">1</span>, tr, <span class="builtin">max</span>(l, tm+<span class="number">1</span>), r);
}
</code></pre>
</section>
<!-- ========== 3. SPARSE TABLE ========== -->
<section id="sparse-table" class="section">
<h2>3. Sparse Table</h2>
<p>A static data structure for answering range minimum/maximum/GCD queries in O(1) after O(n log n) preprocessing. Works for any <strong>idempotent</strong> operation (where f(a, a) = a).</p>
<div class="formula-box">
<div class="label">Key Idea</div>
<p>sparse[k][i] = answer for the range [i, i + 2^k - 1]</p>
<p>sparse[k][i] = op(sparse[k-1][i], sparse[k-1][i + 2^(k-1)])</p>
<p>Query [l, r]: k = floor(log2(r - l + 1)), answer = op(sparse[k][l], sparse[k][r - 2^k + 1])</p>
<p>The two ranges overlap, but for idempotent ops that is fine.</p>
</div>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">SparseTable</span> {
<span class="keyword">int</span> n, LOG;
vector<vector<<span class="keyword">int</span>>> table;
vector<<span class="keyword">int</span>> lg;
<span class="function">SparseTable</span>(vector<<span class="keyword">int</span>>& a) {
n = a.<span class="function">size</span>();
LOG = <span class="number">__lg</span>(n) + <span class="number">1</span>;
table.<span class="function">assign</span>(LOG, vector<<span class="keyword">int</span>>(n));
lg.<span class="function">assign</span>(n + <span class="number">1</span>, <span class="number">0</span>);
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">2</span>; i <= n; i++)
lg[i] = lg[i / <span class="number">2</span>] + <span class="number">1</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i < n; i++)
table[<span class="number">0</span>][i] = a[i];
<span class="keyword">for</span> (<span class="keyword">int</span> k = <span class="number">1</span>; k < LOG; k++)
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i + (<span class="number">1</span> << k) <= n; i++)
table[k][i] = <span class="builtin">min</span>(table[k-<span class="number">1</span>][i],
table[k-<span class="number">1</span>][i + (<span class="number">1</span> << (k-<span class="number">1</span>))]);
}
<span class="keyword">int</span> <span class="function">query</span>(<span class="keyword">int</span> l, <span class="keyword">int</span> r) {
<span class="keyword">int</span> k = lg[r - l + <span class="number">1</span>];
<span class="keyword">return</span> <span class="builtin">min</span>(table[k][l], table[k][r - (<span class="number">1</span> << k) + <span class="number">1</span>]);
}
};
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> math
<span class="keyword">class</span> <span class="function">SparseTable</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, a):
self.n = <span class="builtin">len</span>(a)
self.LOG = self.n.<span class="function">bit_length</span>()
self.table = [<span class="builtin">list</span>(a)]
<span class="keyword">for</span> k <span class="keyword">in</span> <span class="builtin">range</span>(<span class="number">1</span>, self.LOG):
prev = self.table[k - <span class="number">1</span>]
half = <span class="number">1</span> << (k - <span class="number">1</span>)
row = []
<span class="keyword">for</span> i <span class="keyword">in</span> <span class="builtin">range</span>(self.n - (<span class="number">1</span> << k) + <span class="number">1</span>):
row.<span class="function">append</span>(<span class="builtin">min</span>(prev[i], prev[i + half]))
self.table.<span class="function">append</span>(row)
<span class="keyword">def</span> <span class="function">query</span>(self, l, r):
k = (r - l + <span class="number">1</span>).<span class="function">bit_length</span>() - <span class="number">1</span>
<span class="keyword">return</span> <span class="builtin">min</span>(self.table[k][l], self.table[k][r - (<span class="number">1</span> << k) + <span class="number">1</span>])
</code></pre>
<div class="example-box">
<div class="label">ASCII: Sparse Table for [3, 1, 4, 1, 5, 9, 2, 6] (min)</div>
<pre>
k=0: [3] [1] [4] [1] [5] [9] [2] [6] (individual elements)
k=1: [1] [1] [1] [1] [5] [2] [2] -- (min of pairs)
k=2: [1] [1] [1] [1] [2] [2] -- -- (min of quads)
k=3: [1] [1] [1] [1] -- -- -- -- (min of octets)
query(2, 6): k = floor(log2(5)) = 2
= min(table[2][2], table[2][6 - 4 + 1])
= min(table[2][2], table[2][3])
= min(1, 1) = 1
</pre>
</div>
<div class="tip-box">
<div class="label">When NOT to Use Sparse Table</div>
<p>Sparse table only works for static arrays (no updates). If you need updates, use a segment tree instead. Also, for non-idempotent operations like sum, the overlapping ranges trick does not work -- you would need a different query strategy (Disjoint Sparse Table) or just use a segment tree.</p>
</div>
</section>
<!-- ========== 4. DSU ADVANCED ========== -->
<section id="dsu" class="section">
<h2>4. DSU Advanced (Disjoint Set Union)</h2>
<p>Union-Find with path compression + union by rank gives near O(1) amortized per operation (technically O(alpha(n)) where alpha is the inverse Ackermann function). Advanced variants add rollback and weighted edges.</p>
<div class="formula-box">
<div class="label">Complexity</div>
<p><strong>Union by rank + path compression</strong>: O(alpha(n)) per operation (effectively O(1))</p>
<p><strong>Union by rank only (no path compression)</strong>: O(log n) per operation -- but supports rollback</p>
</div>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">DSU</span> {
vector<<span class="keyword">int</span>> parent, rank_;
<span class="function">DSU</span>(<span class="keyword">int</span> n) : parent(n), rank_(n, <span class="number">0</span>) {
<span class="builtin">iota</span>(parent.<span class="function">begin</span>(), parent.<span class="function">end</span>(), <span class="number">0</span>);
}
<span class="keyword">int</span> <span class="function">find</span>(<span class="keyword">int</span> x) {
<span class="keyword">while</span> (x != parent[x])
x = parent[x] = parent[parent[x]]; <span class="comment">// path compression (halving)</span>
<span class="keyword">return</span> x;
}
<span class="keyword">bool</span> <span class="function">unite</span>(<span class="keyword">int</span> a, <span class="keyword">int</span> b) {
a = <span class="function">find</span>(a); b = <span class="function">find</span>(b);
<span class="keyword">if</span> (a == b) <span class="keyword">return</span> <span class="keyword">false</span>;
<span class="keyword">if</span> (rank_[a] < rank_[b]) <span class="builtin">swap</span>(a, b);
parent[b] = a;
<span class="keyword">if</span> (rank_[a] == rank_[b]) rank_[a]++;
<span class="keyword">return</span> <span class="keyword">true</span>;
}
};
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">class</span> <span class="function">DSU</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, n):
self.parent = <span class="builtin">list</span>(<span class="builtin">range</span>(n))
self.rank = [<span class="number">0</span>] * n
<span class="keyword">def</span> <span class="function">find</span>(self, x):
<span class="keyword">while</span> self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
<span class="keyword">return</span> x
<span class="keyword">def</span> <span class="function">unite</span>(self, a, b):
a, b = self.<span class="function">find</span>(a), self.<span class="function">find</span>(b)
<span class="keyword">if</span> a == b:
<span class="keyword">return</span> <span class="keyword">False</span>
<span class="keyword">if</span> self.rank[a] < self.rank[b]:
a, b = b, a
self.parent[b] = a
<span class="keyword">if</span> self.rank[a] == self.rank[b]:
self.rank[a] += <span class="number">1</span>
<span class="keyword">return</span> <span class="keyword">True</span>
</code></pre>
<h3>DSU with Rollback</h3>
<p>For problems that require undoing unions (e.g., offline divide and conquer), use union by rank WITHOUT path compression and maintain a stack of changes.</p>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">RollbackDSU</span> {
vector<<span class="keyword">int</span>> parent, rank_;
vector<pair<<span class="keyword">int</span>,<span class="keyword">int</span>>> history; <span class="comment">// (node, old_parent_or_rank)</span>
<span class="function">RollbackDSU</span>(<span class="keyword">int</span> n) : parent(n), rank_(n, <span class="number">0</span>) {
<span class="builtin">iota</span>(parent.<span class="function">begin</span>(), parent.<span class="function">end</span>(), <span class="number">0</span>);
}
<span class="keyword">int</span> <span class="function">find</span>(<span class="keyword">int</span> x) {
<span class="keyword">while</span> (x != parent[x]) x = parent[x]; <span class="comment">// NO path compression</span>
<span class="keyword">return</span> x;
}
<span class="keyword">int</span> <span class="function">snapshot</span>() { <span class="keyword">return</span> history.<span class="function">size</span>(); }
<span class="keyword">bool</span> <span class="function">unite</span>(<span class="keyword">int</span> a, <span class="keyword">int</span> b) {
a = <span class="function">find</span>(a); b = <span class="function">find</span>(b);
<span class="keyword">if</span> (a == b) <span class="keyword">return</span> <span class="keyword">false</span>;
<span class="keyword">if</span> (rank_[a] < rank_[b]) <span class="builtin">swap</span>(a, b);
history.<span class="function">push_back</span>({b, parent[b]});
history.<span class="function">push_back</span>({~a, rank_[a]}); <span class="comment">// ~a marks rank entry</span>
parent[b] = a;
<span class="keyword">if</span> (rank_[a] == rank_[b]) rank_[a]++;
<span class="keyword">return</span> <span class="keyword">true</span>;
}
<span class="keyword">void</span> <span class="function">rollback</span>(<span class="keyword">int</span> snap) {
<span class="keyword">while</span> ((<span class="keyword">int</span>)history.<span class="function">size</span>() > snap) {
<span class="keyword">auto</span> [node, val] = history.<span class="function">back</span>();
history.<span class="function">pop_back</span>();
<span class="keyword">if</span> (node < <span class="number">0</span>) rank_[~node] = val;
<span class="keyword">else</span> parent[node] = val;
}
}
};
</code></pre>
<h3>Weighted DSU</h3>
<p>Each node stores a weight/distance relative to its parent. Useful for problems like "is the distance between a and b consistent with given constraints?"</p>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">WeightedDSU</span> {
vector<<span class="keyword">int</span>> parent, rank_;
vector<<span class="keyword">long long</span>> diff; <span class="comment">// diff[x] = weight(x) - weight(parent[x])</span>
<span class="function">WeightedDSU</span>(<span class="keyword">int</span> n) : parent(n), rank_(n, <span class="number">0</span>), diff(n, <span class="number">0</span>) {
<span class="builtin">iota</span>(parent.<span class="function">begin</span>(), parent.<span class="function">end</span>(), <span class="number">0</span>);
}
pair<<span class="keyword">int</span>, <span class="keyword">long long</span>> <span class="function">find</span>(<span class="keyword">int</span> x) {
<span class="keyword">if</span> (x == parent[x]) <span class="keyword">return</span> {x, <span class="number">0</span>};
<span class="keyword">auto</span> [root, d] = <span class="function">find</span>(parent[x]);
parent[x] = root;
diff[x] += d;
<span class="keyword">return</span> {root, diff[x]};
}
<span class="comment">// unite with constraint: weight(a) - weight(b) = w</span>
<span class="keyword">bool</span> <span class="function">unite</span>(<span class="keyword">int</span> a, <span class="keyword">int</span> b, <span class="keyword">long long</span> w) {
<span class="keyword">auto</span> [ra, da] = <span class="function">find</span>(a);
<span class="keyword">auto</span> [rb, db] = <span class="function">find</span>(b);
<span class="keyword">if</span> (ra == rb) <span class="keyword">return</span> (da - db) == w; <span class="comment">// check consistency</span>
<span class="keyword">if</span> (rank_[ra] < rank_[rb]) {
<span class="builtin">swap</span>(ra, rb); <span class="builtin">swap</span>(da, db); w = -w;
}
parent[rb] = ra;
diff[rb] = da - db - w;
<span class="keyword">if</span> (rank_[ra] == rank_[rb]) rank_[ra]++;
<span class="keyword">return</span> <span class="keyword">true</span>;
}
};
</code></pre>
</section>
<!-- ========== 5. HEAVY-LIGHT DECOMPOSITION ========== -->
<section id="hld" class="section">
<h2>5. Heavy-Light Decomposition (HLD)</h2>
<p>Decomposes a tree into chains so that any root-to-leaf path crosses at most O(log n) chains. Combined with a segment tree on the flattened array, this gives O(log^2 n) path queries and updates.</p>
<div class="formula-box">
<div class="label">Core Idea</div>
<p>For each node, the <strong>heavy child</strong> is the child with the largest subtree. The edge to the heavy child is a <strong>heavy edge</strong>; all others are <strong>light edges</strong>.</p>
<p>Any path from root to leaf has at most O(log n) light edges, so at most O(log n) chain switches.</p>
<p>Path query: O(log^2 n) -- O(log n) chains, each queried in O(log n) on the segment tree.</p>
</div>
<div class="example-box">
<div class="label">ASCII: HLD Chain Decomposition</div>
<pre>
Tree: 1 Heavy edges: 1-2, 2-4, 4-7
/ \ Light edges: 1-3, 2-5, 3-6
2 3
/ \ \ Chains (heavy paths):
4 5 6 Chain 0: [1, 2, 4, 7]
| Chain 1: [3, 6]
7 Chain 2: [5]
Euler tour (HLD order): 1 2 4 7 5 3 6
positions: 0 1 2 3 4 5 6
path_query(5, 6):
5 is in chain [5], head=5 -> query pos[5]=4, climb to parent(5)=2
6 is in chain [3,6], head=3 -> query pos[3..6]=[5,6], climb to parent(3)=1
Now 2 and 1 are in same chain [1,2,4,7] -> query pos[1..2]=[0,1]
Merge all three segment tree queries.
</pre>
</div>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">HLD</span> {
<span class="keyword">int</span> n, timer = <span class="number">0</span>;
vector<vector<<span class="keyword">int</span>>> adj;
vector<<span class="keyword">int</span>> parent, depth, heavy, head, pos, sz;
<span class="function">HLD</span>(<span class="keyword">int</span> n) : n(n), adj(n), parent(n), depth(n),
heavy(n, -<span class="number">1</span>), head(n), pos(n), sz(n) {}
<span class="keyword">void</span> <span class="function">addEdge</span>(<span class="keyword">int</span> u, <span class="keyword">int</span> v) {
adj[u].<span class="function">push_back</span>(v);
adj[v].<span class="function">push_back</span>(u);
}
<span class="keyword">void</span> <span class="function">dfs_sz</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> p, <span class="keyword">int</span> d) {
parent[v] = p; depth[v] = d; sz[v] = <span class="number">1</span>;
<span class="keyword">int</span> maxSz = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> u : adj[v]) {
<span class="keyword">if</span> (u == p) <span class="keyword">continue</span>;
<span class="function">dfs_sz</span>(u, v, d + <span class="number">1</span>);
sz[v] += sz[u];
<span class="keyword">if</span> (sz[u] > maxSz) { maxSz = sz[u]; heavy[v] = u; }
}
}
<span class="keyword">void</span> <span class="function">dfs_hld</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> h) {
head[v] = h; pos[v] = timer++;
<span class="keyword">if</span> (heavy[v] != -<span class="number">1</span>) <span class="function">dfs_hld</span>(heavy[v], h);
<span class="keyword">for</span> (<span class="keyword">int</span> u : adj[v]) {
<span class="keyword">if</span> (u == parent[v] || u == heavy[v]) <span class="keyword">continue</span>;
<span class="function">dfs_hld</span>(u, u); <span class="comment">// new chain starts</span>
}
}
<span class="keyword">void</span> <span class="function">init</span>(<span class="keyword">int</span> root = <span class="number">0</span>) {
<span class="function">dfs_sz</span>(root, root, <span class="number">0</span>);
<span class="function">dfs_hld</span>(root, root);
}
<span class="comment">// Query path (u, v) using a segment tree</span>
<span class="keyword">template</span><<span class="keyword">typename</span> F>
<span class="keyword">void</span> <span class="function">path</span>(<span class="keyword">int</span> u, <span class="keyword">int</span> v, F&& f) {
<span class="keyword">while</span> (head[u] != head[v]) {
<span class="keyword">if</span> (depth[head[u]] < depth[head[v]]) <span class="builtin">swap</span>(u, v);
f(pos[head[u]], pos[u]); <span class="comment">// query segment [pos[head[u]], pos[u]]</span>
u = parent[head[u]];
}
<span class="keyword">if</span> (depth[u] > depth[v]) <span class="builtin">swap</span>(u, v);
f(pos[u], pos[v]); <span class="comment">// query segment within same chain</span>
}
};
</code></pre>
<div class="warning-box">
<div class="label">HLD Pitfall: Recursion Depth</div>
<p>For trees with up to 2*10^5 nodes, recursive DFS may cause a stack overflow (especially on Codeforces with its default stack size). Use iterative DFS or increase the stack size with a pragma/thread trick in C++.</p>
</div>
</section>
<!-- ========== 6. CENTROID DECOMPOSITION ========== -->
<section id="centroid" class="section">
<h2>6. Centroid Decomposition</h2>
<p>Recursively find the centroid of the tree, remove it, and recurse on each remaining subtree. This creates a "centroid tree" of depth O(log n). Any path in the original tree passes through the LCA in the centroid tree.</p>
<div class="formula-box">
<div class="label">Properties</div>
<p>The centroid of a tree is a node whose removal splits the tree into components each of size at most n/2.</p>
<p>The centroid tree has depth O(log n).</p>
<p>Every path u-v in the original tree passes through either u's or v's ancestor in the centroid tree.</p>
</div>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> <span class="function">CentroidDecomp</span> {
<span class="keyword">int</span> n;
vector<vector<<span class="keyword">int</span>>> adj;
vector<<span class="keyword">int</span>> sz, par;
vector<<span class="keyword">bool</span>> removed;
<span class="function">CentroidDecomp</span>(<span class="keyword">int</span> n) : n(n), adj(n), sz(n), par(n, -<span class="number">1</span>), removed(n, <span class="keyword">false</span>) {}
<span class="keyword">void</span> <span class="function">addEdge</span>(<span class="keyword">int</span> u, <span class="keyword">int</span> v) {
adj[u].<span class="function">push_back</span>(v);
adj[v].<span class="function">push_back</span>(u);
}
<span class="keyword">void</span> <span class="function">calc_sz</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> p) {
sz[v] = <span class="number">1</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> u : adj[v])
<span class="keyword">if</span> (u != p && !removed[u]) {
<span class="function">calc_sz</span>(u, v);
sz[v] += sz[u];
}
}
<span class="keyword">int</span> <span class="function">centroid</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> p, <span class="keyword">int</span> tree_sz) {
<span class="keyword">for</span> (<span class="keyword">int</span> u : adj[v])
<span class="keyword">if</span> (u != p && !removed[u] && sz[u] > tree_sz / <span class="number">2</span>)
<span class="keyword">return</span> <span class="function">centroid</span>(u, v, tree_sz);
<span class="keyword">return</span> v;
}
<span class="keyword">void</span> <span class="function">build</span>(<span class="keyword">int</span> v, <span class="keyword">int</span> p) {
<span class="function">calc_sz</span>(v, -<span class="number">1</span>);
<span class="keyword">int</span> c = <span class="function">centroid</span>(v, -<span class="number">1</span>, sz[v]);
par[c] = p;
removed[c] = <span class="keyword">true</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> u : adj[c])
<span class="keyword">if</span> (!removed[u])
<span class="function">build</span>(u, c);
}
<span class="keyword">void</span> <span class="function">init</span>() { <span class="function">build</span>(<span class="number">0</span>, -<span class="number">1</span>); }
};
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> sys
sys.<span class="function">setrecursionlimit</span>(<span class="number">300000</span>)
<span class="keyword">class</span> <span class="function">CentroidDecomp</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, n):
self.n = n
self.adj = [[] <span class="keyword">for</span> _ <span class="keyword">in</span> <span class="builtin">range</span>(n)]
self.sz = [<span class="number">0</span>] * n
self.par = [-<span class="number">1</span>] * n
self.removed = [<span class="keyword">False</span>] * n
<span class="keyword">def</span> <span class="function">add_edge</span>(self, u, v):
self.adj[u].<span class="function">append</span>(v)
self.adj[v].<span class="function">append</span>(u)
<span class="keyword">def</span> <span class="function">calc_sz</span>(self, v, p):
self.sz[v] = <span class="number">1</span>
<span class="keyword">for</span> u <span class="keyword">in</span> self.adj[v]:
<span class="keyword">if</span> u != p <span class="keyword">and</span> <span class="keyword">not</span> self.removed[u]:
self.<span class="function">calc_sz</span>(u, v)
self.sz[v] += self.sz[u]
<span class="keyword">def</span> <span class="function">centroid</span>(self, v, p, tree_sz):
<span class="keyword">for</span> u <span class="keyword">in</span> self.adj[v]:
<span class="keyword">if</span> u != p <span class="keyword">and</span> <span class="keyword">not</span> self.removed[u] <span class="keyword">and</span> self.sz[u] > tree_sz // <span class="number">2</span>:
<span class="keyword">return</span> self.<span class="function">centroid</span>(u, v, tree_sz)
<span class="keyword">return</span> v
<span class="keyword">def</span> <span class="function">build</span>(self, v, p):
self.<span class="function">calc_sz</span>(v, -<span class="number">1</span>)
c = self.<span class="function">centroid</span>(v, -<span class="number">1</span>, self.sz[v])
self.par[c] = p
self.removed[c] = <span class="keyword">True</span>
<span class="keyword">for</span> u <span class="keyword">in</span> self.adj[c]:
<span class="keyword">if</span> <span class="keyword">not</span> self.removed[u]:
self.<span class="function">build</span>(u, c)
<span class="keyword">def</span> <span class="function">init</span>(self):
self.<span class="function">build</span>(<span class="number">0</span>, -<span class="number">1</span>)
</code></pre>
<div class="tip-box">
<div class="label">Centroid Decomposition Use Cases</div>
<p>Use centroid decomposition for path queries on trees where you need to aggregate over all paths through a node: closest marked node, count of paths with given property, distance queries. For path updates/queries on edges (like "update all edges on path u-v"), HLD is usually a better fit.</p>
</div>
</section>
<!-- ========== 7. TREAP / IMPLICIT TREAP ========== -->
<section id="treap" class="section">
<h2>7. Treap / Implicit Treap</h2>
<p>A treap is a BST where each node also has a random priority, maintaining heap order on priorities. This ensures O(log n) expected height. An <strong>implicit treap</strong> uses the position (subtree size) as the implicit key, enabling array-like operations (insert at index, delete at index, reverse a subarray) in O(log n).</p>
<div class="formula-box">
<div class="label">Operations</div>
<p><strong>Split(t, k)</strong>: split treap t into two treaps: one with first k elements, one with the rest.</p>
<p><strong>Merge(l, r)</strong>: merge two treaps where all keys in l < all keys in r.</p>
<p>All operations (insert, delete, reverse, query) are built from split + merge.</p>
</div>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">mt19937</span> rng(<span class="function">chrono::steady_clock::now</span>().<span class="function">time_since_epoch</span>().<span class="function">count</span>());
<span class="keyword">struct</span> <span class="function">Node</span> {
<span class="keyword">int</span> val, pri, sz;
<span class="keyword">bool</span> rev;
Node *l, *r;
<span class="function">Node</span>(<span class="keyword">int</span> v) : val(v), pri(rng()), sz(<span class="number">1</span>), rev(<span class="keyword">false</span>), l(<span class="keyword">nullptr</span>), r(<span class="keyword">nullptr</span>) {}
};
<span class="keyword">int</span> <span class="function">sz</span>(Node* t) { <span class="keyword">return</span> t ? t->sz : <span class="number">0</span>; }
<span class="keyword">void</span> <span class="function">pull</span>(Node* t) {
<span class="keyword">if</span> (t) t->sz = <span class="number">1</span> + <span class="function">sz</span>(t->l) + <span class="function">sz</span>(t->r);
}
<span class="keyword">void</span> <span class="function">push</span>(Node* t) {
<span class="keyword">if</span> (t && t->rev) {
<span class="builtin">swap</span>(t->l, t->r);
<span class="keyword">if</span> (t->l) t->l->rev ^= <span class="number">1</span>;
<span class="keyword">if</span> (t->r) t->r->rev ^= <span class="number">1</span>;
t->rev = <span class="keyword">false</span>;
}
}
<span class="keyword">void</span> <span class="function">split</span>(Node* t, <span class="keyword">int</span> k, Node*& l, Node*& r) {
<span class="keyword">if</span> (!t) { l = r = <span class="keyword">nullptr</span>; <span class="keyword">return</span>; }
<span class="function">push</span>(t);
<span class="keyword">int</span> cur = <span class="function">sz</span>(t->l) + <span class="number">1</span>;
<span class="keyword">if</span> (k < cur) {
<span class="function">split</span>(t->l, k, l, t->l);
r = t;
} <span class="keyword">else</span> {
<span class="function">split</span>(t->r, k - cur, t->r, r);
l = t;
}
<span class="function">pull</span>(t);
}
<span class="keyword">void</span> <span class="function">merge</span>(Node*& t, Node* l, Node* r) {
<span class="keyword">if</span> (!l || !r) { t = l ? l : r; <span class="keyword">return</span>; }
<span class="function">push</span>(l); <span class="function">push</span>(r);
<span class="keyword">if</span> (l->pri > r->pri) {
<span class="function">merge</span>(l->r, l->r, r);
t = l;
} <span class="keyword">else</span> {
<span class="function">merge</span>(r->l, l, r->l);
t = r;
}
<span class="function">pull</span>(t);
}
<span class="comment">// Reverse subarray [l, r] (0-indexed)</span>
<span class="keyword">void</span> <span class="function">reverse</span>(Node*& root, <span class="keyword">int</span> l, <span class="keyword">int</span> r) {
Node *a, *b, *c;
<span class="function">split</span>(root, l, a, b);
<span class="function">split</span>(b, r - l + <span class="number">1</span>, b, c);
b->rev ^= <span class="number">1</span>;
<span class="function">merge</span>(root, a, b);
<span class="function">merge</span>(root, root, c);
}
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> random
<span class="keyword">class</span> <span class="function">TreapNode</span>:
__slots__ = [<span class="string">'val'</span>, <span class="string">'pri'</span>, <span class="string">'sz'</span>, <span class="string">'rev'</span>, <span class="string">'l'</span>, <span class="string">'r'</span>]
<span class="keyword">def</span> <span class="function">__init__</span>(self, val):
self.val = val
self.pri = random.<span class="function">randint</span>(<span class="number">0</span>, (<span class="number">1</span> << <span class="number">62</span>) - <span class="number">1</span>)
self.sz = <span class="number">1</span>
self.rev = <span class="keyword">False</span>
self.l = self.r = <span class="keyword">None</span>
<span class="keyword">def</span> <span class="function">sz</span>(t):
<span class="keyword">return</span> t.sz <span class="keyword">if</span> t <span class="keyword">else</span> <span class="number">0</span>
<span class="keyword">def</span> <span class="function">pull</span>(t):
<span class="keyword">if</span> t: