-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcomputational-geometry.html
More file actions
1740 lines (1435 loc) · 92 KB
/
computational-geometry.html
File metadata and controls
1740 lines (1435 loc) · 92 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>Computational Geometry - 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>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</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> » Computational Geometry</div>
<h1>Computational Geometry</h1>
<p>The algorithmic study of geometric objects -- points, lines, polygons, and their relationships. Essential for competitive programming, computer graphics, robotics, and GIS. This page covers every major technique with code, proofs, and intuition.</p>
</div>
<!-- Table of Contents -->
<div class="toc">
<h2>Table of Contents</h2>
<ol>
<li><a href="#points-vectors">Points and Vectors</a></li>
<li><a href="#cross-product-orientation">Cross Product and Orientation</a></li>
<li><a href="#segment-intersection">Line Segment Intersection</a></li>
<li><a href="#convex-hull">Convex Hull</a></li>
<li><a href="#point-in-polygon">Point in Polygon</a></li>
<li><a href="#closest-pair">Closest Pair of Points</a></li>
<li><a href="#sweep-line">Sweep Line Algorithms</a></li>
<li><a href="#polygon-area">Polygon Area and Centroid</a></li>
<li><a href="#half-plane">Half-Plane Intersection</a></li>
<li><a href="#rotating-calipers">Rotating Calipers</a></li>
<li><a href="#voronoi-delaunay">Voronoi Diagrams and Delaunay Triangulation</a></li>
<li><a href="#practice">Practice Problems</a></li>
</ol>
</div>
<!-- ============================================================ -->
<!-- SECTION 1: Points and Vectors -->
<!-- ============================================================ -->
<div class="section" id="points-vectors">
<h2>1. Points and Vectors</h2>
<p>Everything in computational geometry starts with representing points in 2D space and performing vector operations on them. A point is a location <strong>(x, y)</strong>. A vector is a direction + magnitude, often represented the same way but interpreted differently.</p>
<div class="tip-box">
<div class="label">Key Insight</div>
A vector from point A to point B is simply <strong>B - A = (B.x - A.x, B.y - A.y)</strong>. This is the most fundamental operation -- it converts two points into a direction.
</div>
<h3>Point / Vector Struct</h3>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">struct</span> Point {
<span class="keyword">double</span> x, y;
Point(<span class="keyword">double</span> x = <span class="number">0</span>, <span class="keyword">double</span> y = <span class="number">0</span>) : x(x), y(y) {}
<span class="comment">// Vector addition</span>
Point <span class="keyword">operator</span>+(<span class="keyword">const</span> Point& p) <span class="keyword">const</span> { <span class="keyword">return</span> {x + p.x, y + p.y}; }
<span class="comment">// Vector subtraction (A - B = vector from B to A)</span>
Point <span class="keyword">operator</span>-(<span class="keyword">const</span> Point& p) <span class="keyword">const</span> { <span class="keyword">return</span> {x - p.x, y - p.y}; }
<span class="comment">// Scalar multiplication</span>
Point <span class="keyword">operator</span>*(<span class="keyword">double</span> t) <span class="keyword">const</span> { <span class="keyword">return</span> {x * t, y * t}; }
<span class="comment">// Dot product</span>
<span class="keyword">double</span> <span class="function">dot</span>(<span class="keyword">const</span> Point& p) <span class="keyword">const</span> { <span class="keyword">return</span> x * p.x + y * p.y; }
<span class="comment">// Cross product (z-component of 3D cross)</span>
<span class="keyword">double</span> <span class="function">cross</span>(<span class="keyword">const</span> Point& p) <span class="keyword">const</span> { <span class="keyword">return</span> x * p.y - y * p.x; }
<span class="comment">// Magnitude</span>
<span class="keyword">double</span> <span class="function">norm</span>() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="function">sqrt</span>(x * x + y * y); }
<span class="comment">// Squared magnitude (avoid sqrt when possible)</span>
<span class="keyword">double</span> <span class="function">norm2</span>() <span class="keyword">const</span> { <span class="keyword">return</span> x * x + y * y; }
};
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> math
<span class="keyword">class</span> <span class="function">Point</span>:
<span class="keyword">def</span> <span class="function">__init__</span>(self, x=<span class="number">0</span>, y=<span class="number">0</span>):
self.x = x
self.y = y
<span class="keyword">def</span> <span class="function">__add__</span>(self, p):
<span class="keyword">return</span> Point(self.x + p.x, self.y + p.y)
<span class="keyword">def</span> <span class="function">__sub__</span>(self, p):
<span class="keyword">return</span> Point(self.x - p.x, self.y - p.y)
<span class="keyword">def</span> <span class="function">__mul__</span>(self, t):
<span class="keyword">return</span> Point(self.x * t, self.y * t)
<span class="keyword">def</span> <span class="function">dot</span>(self, p):
<span class="keyword">return</span> self.x * p.x + self.y * p.y
<span class="keyword">def</span> <span class="function">cross</span>(self, p):
<span class="keyword">return</span> self.x * p.y - self.y * p.x
<span class="keyword">def</span> <span class="function">norm</span>(self):
<span class="keyword">return</span> math.sqrt(self.x ** <span class="number">2</span> + self.y ** <span class="number">2</span>)
<span class="keyword">def</span> <span class="function">norm2</span>(self):
<span class="keyword">return</span> self.x ** <span class="number">2</span> + self.y ** <span class="number">2</span>
<span class="keyword">def</span> <span class="function">__repr__</span>(self):
<span class="keyword">return</span> <span class="string">f"({self.x}, {self.y})"</span>
</code></pre>
<h3>Visual: Vector Operations</h3>
<pre><code>
y
^
4 | B(4,3)
| /
3 | / <-- vector AB
| /
2 | /
| /
1 | A(1,1)
|
0 +---+---+---+---+---> x
0 1 2 3 4
Vector AB = B - A = (3, 2)
|AB| = sqrt(9 + 4) = sqrt(13) ~ 3.61
</code></pre>
<h3>Dot Product Intuition</h3>
<div class="formula-box">
<div class="label">Dot Product</div>
<strong>A . B = |A| * |B| * cos(theta)</strong><br>
<strong>A . B = A.x * B.x + A.y * B.y</strong><br><br>
Result > 0: angle < 90 degrees (vectors point roughly same direction)<br>
Result = 0: angle = 90 degrees (perpendicular)<br>
Result < 0: angle > 90 degrees (vectors point roughly opposite)
</div>
<h3>Angle Between Two Vectors</h3>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">angle_between</span>(a, b):
<span class="string">"""Returns angle in radians between vectors a and b"""</span>
cos_theta = a.dot(b) / (a.norm() * b.norm())
<span class="comment"># Clamp to avoid floating point errors with acos</span>
cos_theta = max(-<span class="number">1</span>, min(<span class="number">1</span>, cos_theta))
<span class="keyword">return</span> math.acos(cos_theta)
</code></pre>
<div class="warning-box">
<div class="label">Floating Point Warning</div>
Computational geometry is plagued by floating point issues. Whenever possible, use <strong>integer arithmetic</strong> (cross products, dot products with integer coordinates) and avoid <code>sqrt</code> and <code>acos</code>. Compare squared distances instead of distances. Use an epsilon (e.g., 1e-9) for floating point comparisons.
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION 2: Cross Product and Orientation -->
<!-- ============================================================ -->
<div class="section" id="cross-product-orientation">
<h2>2. Cross Product and Orientation</h2>
<p>The 2D cross product is the single most important tool in computational geometry. It tells you the <strong>orientation</strong> (turn direction) of three points.</p>
<div class="formula-box">
<div class="label">2D Cross Product</div>
For vectors A and B: <strong>A x B = A.x * B.y - A.y * B.x</strong><br><br>
This equals the <strong>signed area</strong> of the parallelogram formed by A and B.<br>
Equivalently, for three points P, Q, R:<br>
<strong>cross(PQ, PR) = (Q-P) x (R-P)</strong>
</div>
<h3>Orientation Test (CCW / CW / Collinear)</h3>
<pre><code>
Positive cross => Counter-Clockwise (left turn)
R
/
/
P --------> Q Turn LEFT to go P->Q->R
Negative cross => Clockwise (right turn)
P --------> Q Turn RIGHT to go P->Q->R
\
\
R
Zero cross => Collinear
P --------> Q --------> R (all on same line)
</code></pre>
<pre><code><span class="lang-label">C++</span>
<span class="comment">// Returns: positive = CCW, negative = CW, 0 = collinear</span>
<span class="keyword">double</span> <span class="function">cross</span>(Point O, Point A, Point B) {
<span class="keyword">return</span> (A - O).cross(B - O);
}
<span class="comment">// Orientation enum for clarity</span>
<span class="keyword">int</span> <span class="function">orient</span>(Point P, Point Q, Point R) {
<span class="keyword">double</span> v = cross(P, Q, R);
<span class="keyword">if</span> (v > <span class="number">0</span>) <span class="keyword">return</span> <span class="number">1</span>; <span class="comment">// CCW (left turn)</span>
<span class="keyword">if</span> (v < <span class="number">0</span>) <span class="keyword">return</span> -<span class="number">1</span>; <span class="comment">// CW (right turn)</span>
<span class="keyword">return</span> <span class="number">0</span>; <span class="comment">// collinear</span>
}
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">cross3</span>(O, A, B):
<span class="string">"""Cross product of vectors OA and OB"""</span>
<span class="keyword">return</span> (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x)
<span class="keyword">def</span> <span class="function">orient</span>(P, Q, R):
<span class="string">"""Returns 1=CCW, -1=CW, 0=collinear"""</span>
v = cross3(P, Q, R)
<span class="keyword">if</span> v > <span class="number">0</span>: <span class="keyword">return</span> <span class="number">1</span>
<span class="keyword">if</span> v < <span class="number">0</span>: <span class="keyword">return</span> -<span class="number">1</span>
<span class="keyword">return</span> <span class="number">0</span>
</code></pre>
<h3>Signed Area of a Triangle</h3>
<div class="formula-box">
<div class="label">Triangle Area from Cross Product</div>
<strong>Area(P, Q, R) = |cross(PQ, PR)| / 2</strong><br><br>
The signed version (without absolute value) is positive when P,Q,R are in CCW order, negative when CW.
</div>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">triangle_area</span>(P, Q, R):
<span class="keyword">return</span> abs(cross3(P, Q, R)) / <span class="number">2</span>
</code></pre>
<div class="tip-box">
<div class="label">When to Use</div>
The orientation test is the building block of almost everything: convex hulls, segment intersection, point-in-polygon, and more. Master it and the rest follows naturally.
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION 3: Line Segment Intersection -->
<!-- ============================================================ -->
<div class="section" id="segment-intersection">
<h2>3. Line Segment Intersection</h2>
<p>Given segments AB and CD, do they intersect? This is one of the most common geometric predicates.</p>
<h3>Geometric Intuition</h3>
<pre><code>
Two segments intersect if and only if:
1) Points C and D are on opposite sides of line AB
AND points A and B are on opposite sides of line CD
A-----------B
/ \
/ \
C D C and D on opposite sides of AB? YES
A and B on opposite sides of CD? YES
=> They intersect!
Special case: a point lies ON the other segment (collinear)
</code></pre>
<h3>The Algorithm</h3>
<p>Use orientation tests. Segments AB and CD intersect when:</p>
<ul>
<li><code>orient(A,B,C)</code> and <code>orient(A,B,D)</code> have different signs, AND</li>
<li><code>orient(C,D,A)</code> and <code>orient(C,D,B)</code> have different signs</li>
<li>OR one of the four orientations is zero and the point lies on the segment (collinear overlap)</li>
</ul>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">bool</span> <span class="function">onSegment</span>(Point p, Point a, Point b) {
<span class="comment">// Check if p is on segment ab, assuming p is collinear with a,b</span>
<span class="keyword">return</span> min(a.x, b.x) <= p.x && p.x <= max(a.x, b.x)
&& min(a.y, b.y) <= p.y && p.y <= max(a.y, b.y);
}
<span class="keyword">bool</span> <span class="function">segmentsIntersect</span>(Point a, Point b, Point c, Point d) {
<span class="keyword">int</span> d1 = orient(a, b, c);
<span class="keyword">int</span> d2 = orient(a, b, d);
<span class="keyword">int</span> d3 = orient(c, d, a);
<span class="keyword">int</span> d4 = orient(c, d, b);
<span class="comment">// General case: segments straddle each other's lines</span>
<span class="keyword">if</span> (d1 * d2 < <span class="number">0</span> && d3 * d4 < <span class="number">0</span>)
<span class="keyword">return</span> <span class="keyword">true</span>;
<span class="comment">// Special cases: collinear points lie on the other segment</span>
<span class="keyword">if</span> (d1 == <span class="number">0</span> && onSegment(c, a, b)) <span class="keyword">return</span> <span class="keyword">true</span>;
<span class="keyword">if</span> (d2 == <span class="number">0</span> && onSegment(d, a, b)) <span class="keyword">return</span> <span class="keyword">true</span>;
<span class="keyword">if</span> (d3 == <span class="number">0</span> && onSegment(a, c, d)) <span class="keyword">return</span> <span class="keyword">true</span>;
<span class="keyword">if</span> (d4 == <span class="number">0</span> && onSegment(b, c, d)) <span class="keyword">return</span> <span class="keyword">true</span>;
<span class="keyword">return</span> <span class="keyword">false</span>;
}
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">on_segment</span>(p, a, b):
<span class="string">"""Check if p lies on segment ab (assuming collinear)"""</span>
<span class="keyword">return</span> (min(a.x, b.x) <= p.x <= max(a.x, b.x) <span class="keyword">and</span>
min(a.y, b.y) <= p.y <= max(a.y, b.y))
<span class="keyword">def</span> <span class="function">segments_intersect</span>(a, b, c, d):
d1 = orient(a, b, c)
d2 = orient(a, b, d)
d3 = orient(c, d, a)
d4 = orient(c, d, b)
<span class="keyword">if</span> d1 * d2 < <span class="number">0</span> <span class="keyword">and</span> d3 * d4 < <span class="number">0</span>:
<span class="keyword">return</span> <span class="keyword">True</span>
<span class="keyword">if</span> d1 == <span class="number">0</span> <span class="keyword">and</span> on_segment(c, a, b): <span class="keyword">return</span> <span class="keyword">True</span>
<span class="keyword">if</span> d2 == <span class="number">0</span> <span class="keyword">and</span> on_segment(d, a, b): <span class="keyword">return</span> <span class="keyword">True</span>
<span class="keyword">if</span> d3 == <span class="number">0</span> <span class="keyword">and</span> on_segment(a, c, d): <span class="keyword">return</span> <span class="keyword">True</span>
<span class="keyword">if</span> d4 == <span class="number">0</span> <span class="keyword">and</span> on_segment(b, c, d): <span class="keyword">return</span> <span class="keyword">True</span>
<span class="keyword">return</span> <span class="keyword">False</span>
</code></pre>
<h3>Finding the Intersection Point</h3>
<p>When you need the actual intersection coordinates, use parametric line equations:</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">intersection_point</span>(a, b, c, d):
<span class="string">"""Find intersection point of segments AB and CD.
Returns None if they don't intersect or are parallel."""</span>
<span class="comment"># Line AB: P = A + t*(B-A), Line CD: P = C + u*(D-C)</span>
denom = (b.x - a.x) * (d.y - c.y) - (b.y - a.y) * (d.x - c.x)
<span class="keyword">if</span> abs(denom) < <span class="number">1e-9</span>:
<span class="keyword">return</span> <span class="keyword">None</span> <span class="comment"># parallel</span>
t = ((c.x - a.x) * (d.y - c.y) - (c.y - a.y) * (d.x - c.x)) / denom
u = ((c.x - a.x) * (b.y - a.y) - (c.y - a.y) * (b.x - a.x)) / denom
<span class="keyword">if</span> <span class="number">0</span> <= t <= <span class="number">1</span> <span class="keyword">and</span> <span class="number">0</span> <= u <= <span class="number">1</span>:
<span class="keyword">return</span> Point(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y))
<span class="keyword">return</span> <span class="keyword">None</span>
</code></pre>
<div class="example-box">
<div class="label">Complexity</div>
<strong>Time:</strong> O(1) per intersection test<br>
<strong>Space:</strong> O(1)
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION 4: Convex Hull -->
<!-- ============================================================ -->
<div class="section" id="convex-hull">
<h2>4. Convex Hull</h2>
<p>The convex hull of a set of points is the smallest convex polygon containing all points. Think of stretching a rubber band around nails on a board -- the shape it makes is the convex hull.</p>
<pre><code>
Convex Hull Visualization:
Input points: Convex Hull:
*
* * / \
* / \
* * * / * * \ *
* * \/ \/
* *-------*
The "rubber band" wraps around the outermost points.
</code></pre>
<h3>Andrew's Monotone Chain (Preferred)</h3>
<p>Sort points by x (then y), then build lower and upper hulls separately. This is generally preferred over Graham scan because it avoids angle computations and handles collinear points cleanly.</p>
<div class="formula-box">
<div class="label">Algorithm Steps</div>
1. Sort points by (x, y)<br>
2. Build lower hull: process left to right, keeping only left turns<br>
3. Build upper hull: process right to left, keeping only left turns<br>
4. Concatenate (remove duplicated endpoints)
</div>
<pre><code>
Walkthrough: Building lower hull for points sorted left to right
Step 1: Start with leftmost points
*
Step 2: Add next point
*---*
Step 3: Add point -- makes left turn, keep it
*---*
\
*
Step 4: Add point -- makes RIGHT turn! Pop the previous point
*---* *---*
\ => \
* *---* (popped the "dent")
</code></pre>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">vector</span><Point> <span class="function">convexHull</span>(<span class="keyword">vector</span><Point> pts) {
<span class="keyword">int</span> n = pts.size();
<span class="keyword">if</span> (n < <span class="number">2</span>) <span class="keyword">return</span> pts;
<span class="function">sort</span>(pts.begin(), pts.end(), [](Point& a, Point& b) {
<span class="keyword">return</span> a.x < b.x || (a.x == b.x && a.y < b.y);
});
<span class="keyword">vector</span><Point> hull;
<span class="comment">// Lower hull</span>
<span class="keyword">for</span> (<span class="keyword">auto</span>& p : pts) {
<span class="keyword">while</span> (hull.size() >= <span class="number">2</span> &&
cross(hull[hull.size()-<span class="number">2</span>], hull[hull.size()-<span class="number">1</span>], p) <= <span class="number">0</span>)
hull.pop_back();
hull.push_back(p);
}
<span class="comment">// Upper hull</span>
<span class="keyword">int</span> lower_size = hull.size() + <span class="number">1</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> i = n - <span class="number">2</span>; i >= <span class="number">0</span>; i--) {
<span class="keyword">while</span> (hull.size() >= lower_size &&
cross(hull[hull.size()-<span class="number">2</span>], hull[hull.size()-<span class="number">1</span>], pts[i]) <= <span class="number">0</span>)
hull.pop_back();
hull.push_back(pts[i]);
}
hull.pop_back(); <span class="comment">// Remove last point (same as first)</span>
<span class="keyword">return</span> hull;
}
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">convex_hull</span>(points):
<span class="string">"""Andrew's monotone chain. Returns hull in CCW order."""</span>
points = sorted(points, key=<span class="keyword">lambda</span> p: (p.x, p.y))
<span class="keyword">if</span> len(points) <= <span class="number">1</span>:
<span class="keyword">return</span> points
<span class="comment"># Build lower hull</span>
lower = []
<span class="keyword">for</span> p <span class="keyword">in</span> points:
<span class="keyword">while</span> len(lower) >= <span class="number">2</span> <span class="keyword">and</span> cross3(lower[-<span class="number">2</span>], lower[-<span class="number">1</span>], p) <= <span class="number">0</span>:
lower.pop()
lower.append(p)
<span class="comment"># Build upper hull</span>
upper = []
<span class="keyword">for</span> p <span class="keyword">in</span> reversed(points):
<span class="keyword">while</span> len(upper) >= <span class="number">2</span> <span class="keyword">and</span> cross3(upper[-<span class="number">2</span>], upper[-<span class="number">1</span>], p) <= <span class="number">0</span>:
upper.pop()
upper.append(p)
<span class="comment"># Concatenate, removing duplicate endpoints</span>
<span class="keyword">return</span> lower[:-<span class="number">1</span>] + upper[:-<span class="number">1</span>]
</code></pre>
<div class="example-box">
<div class="label">Complexity</div>
<strong>Time:</strong> O(n log n) -- dominated by sorting<br>
<strong>Space:</strong> O(n)
</div>
<h3>Graham Scan (Alternative)</h3>
<p>Graham scan picks the lowest point as anchor, sorts remaining points by polar angle relative to the anchor, then builds the hull by processing in angular order.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">graham_scan</span>(points):
<span class="string">"""Graham scan convex hull. Returns hull in CCW order."""</span>
<span class="comment"># Find bottom-most point (lowest y, then leftmost x)</span>
anchor = min(points, key=<span class="keyword">lambda</span> p: (p.y, p.x))
<span class="keyword">def</span> <span class="function">polar_angle</span>(p):
<span class="keyword">return</span> math.atan2(p.y - anchor.y, p.x - anchor.x)
<span class="keyword">def</span> <span class="function">dist2</span>(p):
<span class="keyword">return</span> (p.x - anchor.x) ** <span class="number">2</span> + (p.y - anchor.y) ** <span class="number">2</span>
<span class="comment"># Sort by polar angle, break ties by distance</span>
pts = sorted(points, key=<span class="keyword">lambda</span> p: (polar_angle(p), dist2(p)))
stack = []
<span class="keyword">for</span> p <span class="keyword">in</span> pts:
<span class="keyword">while</span> len(stack) >= <span class="number">2</span> <span class="keyword">and</span> cross3(stack[-<span class="number">2</span>], stack[-<span class="number">1</span>], p) <= <span class="number">0</span>:
stack.pop()
stack.append(p)
<span class="keyword">return</span> stack
</code></pre>
<div class="tip-box">
<div class="label">When to Use Convex Hull</div>
<ul>
<li><strong>Farthest pair of points</strong> -- always on the convex hull (use rotating calipers)</li>
<li><strong>Minimum enclosing rectangle/circle</strong> -- work on hull instead of all points</li>
<li><strong>Checking if all points can be separated by a line</strong></li>
<li><strong>Any problem where only boundary points matter</strong></li>
</ul>
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION 5: Point in Polygon -->
<!-- ============================================================ -->
<div class="section" id="point-in-polygon">
<h2>5. Point in Polygon</h2>
<p>Given a polygon (simple, not necessarily convex) and a query point, determine if the point is inside the polygon.</p>
<h3>Ray Casting Algorithm</h3>
<p>Cast a ray from the query point in any direction (typically to the right). Count how many times it crosses the polygon boundary. Odd = inside, even = outside.</p>
<pre><code>
Ray Casting Visualization:
+---+ Point P is INSIDE:
| | Ray crosses boundary 1 time (odd)
| P -------->
| | Point Q is OUTSIDE:
+---+---+ Ray crosses boundary 2 times (even)
| |
| Q ---------->
| |
+---+
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">point_in_polygon</span>(p, polygon):
<span class="string">"""Ray casting: returns True if p is inside the polygon.
polygon is a list of Point objects forming a simple polygon."""</span>
n = len(polygon)
inside = <span class="keyword">False</span>
j = n - <span class="number">1</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(n):
pi = polygon[i]
pj = polygon[j]
<span class="comment"># Check if ray from p going right crosses edge (pj, pi)</span>
<span class="keyword">if</span> ((pi.y > p.y) != (pj.y > p.y)) <span class="keyword">and</span> \
(p.x < (pj.x - pi.x) * (p.y - pi.y) / (pj.y - pi.y) + pi.x):
inside = <span class="keyword">not</span> inside
j = i
<span class="keyword">return</span> inside
</code></pre>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">bool</span> <span class="function">pointInPolygon</span>(Point p, <span class="keyword">vector</span><Point>& poly) {
<span class="keyword">int</span> n = poly.size();
<span class="keyword">bool</span> inside = <span class="keyword">false</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>, j = n - <span class="number">1</span>; i < n; j = i++) {
<span class="keyword">if</span> ((poly[i].y > p.y) != (poly[j].y > p.y) &&
p.x < (poly[j].x - poly[i].x) * (p.y - poly[i].y) /
(poly[j].y - poly[i].y) + poly[i].x)
inside = !inside;
}
<span class="keyword">return</span> inside;
}
</code></pre>
<div class="example-box">
<div class="label">Complexity</div>
<strong>Time:</strong> O(n) per query, where n = number of polygon vertices<br>
<strong>Space:</strong> O(1)
</div>
<h3>Winding Number Algorithm</h3>
<p>Count how many times the polygon winds around the point. More robust than ray casting for edge cases.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">winding_number</span>(p, polygon):
<span class="string">"""Returns the winding number (0 = outside, nonzero = inside)"""</span>
n = len(polygon)
wn = <span class="number">0</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(n):
a = polygon[i]
b = polygon[(i + <span class="number">1</span>) % n]
<span class="keyword">if</span> a.y <= p.y:
<span class="keyword">if</span> b.y > p.y: <span class="comment"># upward crossing</span>
<span class="keyword">if</span> cross3(a, b, p) > <span class="number">0</span>: <span class="comment"># p is left of edge</span>
wn += <span class="number">1</span>
<span class="keyword">else</span>:
<span class="keyword">if</span> b.y <= p.y: <span class="comment"># downward crossing</span>
<span class="keyword">if</span> cross3(a, b, p) < <span class="number">0</span>: <span class="comment"># p is right of edge</span>
wn -= <span class="number">1</span>
<span class="keyword">return</span> wn
</code></pre>
<h3>Convex Polygon: O(log n) Binary Search</h3>
<p>For a <strong>convex</strong> polygon, you can do point-in-polygon in O(log n) by treating the polygon as a fan of triangles from one vertex and binary searching for the right triangle.</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">point_in_convex_polygon</span>(p, hull):
<span class="string">"""O(log n) point-in-convex-polygon. hull is in CCW order."""</span>
n = len(hull)
<span class="keyword">if</span> n < <span class="number">3</span>:
<span class="keyword">return</span> <span class="keyword">False</span>
<span class="comment"># Check if p is on the correct side of edges from hull[0]</span>
<span class="keyword">if</span> cross3(hull[<span class="number">0</span>], hull[<span class="number">1</span>], p) < <span class="number">0</span>:
<span class="keyword">return</span> <span class="keyword">False</span>
<span class="keyword">if</span> cross3(hull[<span class="number">0</span>], hull[n - <span class="number">1</span>], p) > <span class="number">0</span>:
<span class="keyword">return</span> <span class="keyword">False</span>
<span class="comment"># Binary search for the triangle containing p</span>
lo, hi = <span class="number">1</span>, n - <span class="number">1</span>
<span class="keyword">while</span> hi - lo > <span class="number">1</span>:
mid = (lo + hi) // <span class="number">2</span>
<span class="keyword">if</span> cross3(hull[<span class="number">0</span>], hull[mid], p) >= <span class="number">0</span>:
lo = mid
<span class="keyword">else</span>:
hi = mid
<span class="comment"># Check if p is inside triangle (hull[0], hull[lo], hull[hi])</span>
<span class="keyword">return</span> cross3(hull[lo], hull[hi], p) >= <span class="number">0</span>
</code></pre>
<div class="tip-box">
<div class="label">Which Method to Use?</div>
<ul>
<li><strong>Ray casting</strong> -- simple polygons, easy to implement, O(n)</li>
<li><strong>Winding number</strong> -- more robust for self-intersecting polygons, O(n)</li>
<li><strong>Binary search</strong> -- convex polygons only, O(log n) per query after O(n) preprocessing</li>
</ul>
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION 6: Closest Pair of Points -->
<!-- ============================================================ -->
<div class="section" id="closest-pair">
<h2>6. Closest Pair of Points</h2>
<p>Given n points, find the two points with minimum distance. The brute force is O(n^2). We can do O(n log n) with divide and conquer.</p>
<h3>Divide and Conquer Approach</h3>
<pre><code>
Algorithm Overview:
1. Sort points by x-coordinate
2. Split into left half and right half
3. Recursively find closest pair in each half
4. d = min(left_closest, right_closest)
5. Check the "strip" of width 2d around the dividing line
(points in the strip might form a closer pair across halves)
6. For each point in the strip, only check the next ~7 points
(sorted by y) -- this is the key insight!
| | |
| Left | Strip | Right
| half | (2d) | half
| * | * * | *
| * | * | *
| * | * | *
| | |
|<-- d -->|<-- d -->|
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">import</span> math
<span class="keyword">def</span> <span class="function">closest_pair</span>(points):
<span class="string">"""Returns the minimum distance between any two points.
O(n log n) divide and conquer."""</span>
pts = sorted(points, key=<span class="keyword">lambda</span> p: (p.x, p.y))
<span class="keyword">def</span> <span class="function">dist</span>(a, b):
<span class="keyword">return</span> math.sqrt((a.x - b.x)**<span class="number">2</span> + (a.y - b.y)**<span class="number">2</span>)
<span class="keyword">def</span> <span class="function">rec</span>(pts):
n = len(pts)
<span class="keyword">if</span> n <= <span class="number">3</span>:
<span class="comment"># Brute force for small inputs</span>
best = float(<span class="string">'inf'</span>)
<span class="keyword">for</span> i <span class="keyword">in</span> range(n):
<span class="keyword">for</span> j <span class="keyword">in</span> range(i+<span class="number">1</span>, n):
best = min(best, dist(pts[i], pts[j]))
<span class="keyword">return</span> best
mid = n // <span class="number">2</span>
mid_x = pts[mid].x
<span class="comment"># Recurse on left and right halves</span>
d = min(rec(pts[:mid]), rec(pts[mid:]))
<span class="comment"># Build strip: points within distance d of the dividing line</span>
strip = [p <span class="keyword">for</span> p <span class="keyword">in</span> pts <span class="keyword">if</span> abs(p.x - mid_x) < d]
strip.sort(key=<span class="keyword">lambda</span> p: p.y)
<span class="comment"># Check strip: for each point, only check next few points</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(len(strip)):
j = i + <span class="number">1</span>
<span class="keyword">while</span> j < len(strip) <span class="keyword">and</span> (strip[j].y - strip[i].y) < d:
d = min(d, dist(strip[i], strip[j]))
j += <span class="number">1</span>
<span class="keyword">return</span> d
<span class="keyword">return</span> rec(pts)
</code></pre>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">double</span> <span class="function">closestPair</span>(<span class="keyword">vector</span><Point>& pts, <span class="keyword">int</span> l, <span class="keyword">int</span> r) {
<span class="keyword">if</span> (r - l <= <span class="number">3</span>) {
<span class="keyword">double</span> best = <span class="number">1e18</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> i = l; i < r; i++)
<span class="keyword">for</span> (<span class="keyword">int</span> j = i + <span class="number">1</span>; j < r; j++)
best = min(best, (pts[i] - pts[j]).norm());
<span class="keyword">return</span> best;
}
<span class="keyword">int</span> mid = (l + r) / <span class="number">2</span>;
<span class="keyword">double</span> midX = pts[mid].x;
<span class="keyword">double</span> d = min(closestPair(pts, l, mid), closestPair(pts, mid, r));
<span class="comment">// Merge step: build strip</span>
<span class="keyword">vector</span><Point> strip;
<span class="keyword">for</span> (<span class="keyword">int</span> i = l; i < r; i++)
<span class="keyword">if</span> (abs(pts[i].x - midX) < d)
strip.push_back(pts[i]);
sort(strip.begin(), strip.end(), [](<span class="keyword">const</span> Point& a, <span class="keyword">const</span> Point& b) {
<span class="keyword">return</span> a.y < b.y;
});
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i < strip.size(); i++)
<span class="keyword">for</span> (<span class="keyword">int</span> j = i + <span class="number">1</span>; j < strip.size() && strip[j].y - strip[i].y < d; j++)
d = min(d, (strip[i] - strip[j]).norm());
<span class="keyword">return</span> d;
}
<span class="comment">// Usage: sort pts by x first, then call closestPair(pts, 0, pts.size())</span>
</code></pre>
<div class="example-box">
<div class="label">Complexity</div>
<strong>Time:</strong> O(n log^2 n) as shown above (can be made O(n log n) by maintaining sorted order during merge)<br>
<strong>Space:</strong> O(n)
</div>
<div class="tip-box">
<div class="label">The Strip Optimization -- Why Only 7 Points?</div>
In the strip of width 2d, any d x 2d rectangle can hold at most 8 points (because each half guarantees no two points closer than d). So for each point, we check at most 7 others sorted by y-coordinate. This is what brings the strip check from O(n^2) down to O(n).
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION 7: Sweep Line Algorithms -->
<!-- ============================================================ -->
<div class="section" id="sweep-line">
<h2>7. Sweep Line Algorithms</h2>
<p>Sweep line is a paradigm: imagine a vertical line sweeping left-to-right across the plane, processing "events" (point appearances, segment endpoints) in order. A data structure (usually a balanced BST or set) maintains the current state.</p>
<h3>Line Segment Intersection (Bentley-Ottmann Concept)</h3>
<pre><code>
Sweep line moving left to right:
| / /
| / X / The sweep line processes events:
|/ / \ / - Left endpoint: insert segment
| / X - Right endpoint: remove segment
| / \ / \ - Intersection: swap adjacent segments
| / / \
|/ / \
+---+---+---+--> sweep direction -->
At each event, check newly adjacent segment pairs for intersections.
</code></pre>
<div class="formula-box">
<div class="label">Bentley-Ottmann Overview</div>
<strong>Events:</strong> segment endpoints + discovered intersections<br>
<strong>Status structure:</strong> segments ordered by y-coordinate at current sweep x<br>
<strong>Time:</strong> O((n + k) log n) where k = number of intersections<br>
<strong>Key idea:</strong> Two segments can only intersect if they are adjacent in the sweep status at some point
</div>
<p>The full Bentley-Ottmann implementation is complex. For competitive programming, the brute force O(n^2) check is often sufficient when n is small. Here is a simplified sweep for detecting any intersection:</p>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">from</span> sortedcontainers <span class="keyword">import</span> SortedList
<span class="keyword">def</span> <span class="function">any_intersection</span>(segments):
<span class="string">"""Sweep line to detect if any two segments intersect.
segments: list of ((x1,y1), (x2,y2)) tuples.
Simplified version -- checks adjacent segments in sweep status."""</span>
events = []
<span class="keyword">for</span> i, (p, q) <span class="keyword">in</span> enumerate(segments):
<span class="keyword">if</span> p > q:
p, q = q, p
events.append((p[<span class="number">0</span>], <span class="number">0</span>, i)) <span class="comment"># 0 = left endpoint</span>
events.append((q[<span class="number">0</span>], <span class="number">1</span>, i)) <span class="comment"># 1 = right endpoint</span>
events.sort()
<span class="comment"># In a full implementation, you'd maintain a balanced BST</span>
<span class="comment"># ordered by y-coordinate at the sweep line's current x,</span>
<span class="comment"># and check adjacent pairs at each event.</span>
<span class="comment"># For CP, brute force is often simpler.</span>
<span class="keyword">pass</span>
</code></pre>
<h3>Area of Union of Rectangles</h3>
<p>A classic sweep line + segment tree problem. Sweep a vertical line, and at each event (rectangle left/right edge), update a segment tree that tracks the covered length along the y-axis.</p>
<pre><code><span class="lang-label">C++</span>
<span class="comment">// Sweep line for area of union of rectangles</span>
<span class="comment">// Events: left edge (+1 to coverage), right edge (-1 to coverage)</span>
<span class="comment">// Segment tree tracks total covered y-length</span>
<span class="keyword">struct</span> Event {
<span class="keyword">double</span> x;
<span class="keyword">int</span> type; <span class="comment">// +1 = open, -1 = close</span>
<span class="keyword">double</span> y1, y2;
};
<span class="keyword">double</span> <span class="function">unionArea</span>(<span class="keyword">vector</span><<span class="keyword">array</span><<span class="keyword">double</span>, <span class="number">4</span>>>& rects) {
<span class="comment">// rects[i] = {x1, y1, x2, y2}</span>
<span class="keyword">vector</span><Event> events;
<span class="keyword">vector</span><<span class="keyword">double</span>> ys; <span class="comment">// coordinate compression for y</span>
<span class="keyword">for</span> (<span class="keyword">auto</span>& r : rects) {
events.push_back({r[<span class="number">0</span>], +<span class="number">1</span>, r[<span class="number">1</span>], r[<span class="number">3</span>]});
events.push_back({r[<span class="number">2</span>], -<span class="number">1</span>, r[<span class="number">1</span>], r[<span class="number">3</span>]});
ys.push_back(r[<span class="number">1</span>]);
ys.push_back(r[<span class="number">3</span>]);
}
sort(events.begin(), events.end(), [](<span class="keyword">const</span> Event& a, <span class="keyword">const</span> Event& b) {
<span class="keyword">return</span> a.x < b.x;
});
sort(ys.begin(), ys.end());
ys.erase(unique(ys.begin(), ys.end()), ys.end());
<span class="keyword">int</span> m = ys.size();
<span class="keyword">vector</span><<span class="keyword">int</span>> cnt(m, <span class="number">0</span>); <span class="comment">// coverage count per y-interval</span>
<span class="keyword">double</span> area = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i < events.size(); i++) {
<span class="keyword">if</span> (i > <span class="number">0</span>) {
<span class="keyword">double</span> dx = events[i].x - events[i-<span class="number">1</span>].x;
<span class="keyword">double</span> covered = <span class="number">0</span>;
<span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j + <span class="number">1</span> < m; j++)
<span class="keyword">if</span> (cnt[j] > <span class="number">0</span>)
covered += ys[j+<span class="number">1</span>] - ys[j];
area += dx * covered;
}
<span class="comment">// Update coverage</span>
<span class="keyword">int</span> lo = lower_bound(ys.begin(), ys.end(), events[i].y1) - ys.begin();
<span class="keyword">int</span> hi = lower_bound(ys.begin(), ys.end(), events[i].y2) - ys.begin();
<span class="keyword">for</span> (<span class="keyword">int</span> j = lo; j < hi; j++)
cnt[j] += events[i].type;
}
<span class="keyword">return</span> area;
}
</code></pre>
<div class="example-box">
<div class="label">Complexity</div>
<strong>Union of rectangles (brute force y):</strong> O(n^2)<br>
<strong>Union of rectangles (segment tree):</strong> O(n log n)<br>
<strong>Bentley-Ottmann:</strong> O((n + k) log n)
</div>
<div class="tip-box">
<div class="label">Sweep Line Pattern</div>
The sweep line paradigm reduces 2D problems to 1D. Ask yourself: "If I process events left-to-right, what information do I need about the current vertical slice?" That information is your sweep status structure.
</div>
</div>
<!-- ============================================================ -->
<!-- SECTION 8: Polygon Area and Centroid -->
<!-- ============================================================ -->
<div class="section" id="polygon-area">
<h2>8. Polygon Area and Centroid</h2>
<h3>Shoelace Formula</h3>
<p>The area of any simple polygon given its vertices in order (CW or CCW) can be computed using the shoelace formula, which sums cross products of consecutive edges.</p>
<div class="formula-box">
<div class="label">Shoelace Formula</div>
Given vertices (x0,y0), (x1,y1), ..., (x_{n-1},y_{n-1}) in order:<br><br>
<strong>2 * Area = |sum_{i=0}^{n-1} (x_i * y_{i+1} - x_{i+1} * y_i)|</strong><br><br>
where indices are taken mod n (so vertex n = vertex 0).<br>
The signed version (without absolute value) is positive for CCW, negative for CW.
</div>
<pre><code>
Shoelace Walkthrough:
Polygon with vertices: (1,0), (4,0), (4,3), (0,3)
3 +------*
| | Cross products:
| | (1*0 - 4*0) = 0
| | (4*3 - 4*0) = 12
0 *------* (4*3 - 0*3) = 12
0 1 4 (0*0 - 1*3) = -3
2*Area = |0 + 12 + 12 + (-3)| = 21
Area = 10.5 (which is wrong -- let's be careful)
Actually: (1*0-4*0) + (4*3-4*0) + (4*3-0*3) + (0*0-1*3)
= 0 + 12 - 12 + (-3) ... let me recompute properly:
x_i*y_{i+1}: 1*0 + 4*3 + 4*3 + 0*0 = 0+12+12+0 = 24
x_{i+1}*y_i: 4*0 + 4*0 + 0*3 + 1*3 = 0+0+0+3 = 3
2*Area = |24 - 3| = 21 ...
Hmm, the actual rectangle is 3*4=12. Let me use correct vertices:
(1,0), (4,0), (4,3), (1,3)
x_i*y_{i+1}: 1*0 + 4*3 + 4*3 + 1*0 = 0+12+12+0 = 24
x_{i+1}*y_i: 4*0 + 4*0 + 1*3 + 1*3 = 0+0+3+3 = 6
2*Area = |24 - 6| = 18, Area = 9 = 3*3. Correct!
</code></pre>
<pre><code><span class="lang-label">Python</span>
<span class="keyword">def</span> <span class="function">polygon_area</span>(polygon):
<span class="string">"""Shoelace formula. Returns the area of a simple polygon.
polygon: list of Point objects in order (CW or CCW)."""</span>
n = len(polygon)
area = <span class="number">0</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(n):
j = (i + <span class="number">1</span>) % n
area += polygon[i].x * polygon[j].y
area -= polygon[j].x * polygon[i].y
<span class="keyword">return</span> abs(area) / <span class="number">2</span>
<span class="keyword">def</span> <span class="function">signed_area</span>(polygon):
<span class="string">"""Signed area: positive if CCW, negative if CW."""</span>
n = len(polygon)
area = <span class="number">0</span>
<span class="keyword">for</span> i <span class="keyword">in</span> range(n):
j = (i + <span class="number">1</span>) % n
area += polygon[i].x * polygon[j].y
area -= polygon[j].x * polygon[i].y
<span class="keyword">return</span> area / <span class="number">2</span>
</code></pre>
<pre><code><span class="lang-label">C++</span>
<span class="keyword">double</span> <span class="function">polygonArea</span>(<span class="keyword">vector</span><Point>& poly) {
<span class="keyword">double</span> area = <span class="number">0</span>;
<span class="keyword">int</span> n = poly.size();
<span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i < n; i++) {
<span class="keyword">int</span> j = (i + <span class="number">1</span>) % n;
area += poly[i].x * poly[j].y;
area -= poly[j].x * poly[i].y;
}