forked from tkaneko/icpcseminar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopics.tex
3731 lines (3087 loc) · 149 KB
/
topics.tex
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
\chapter{Plane Geometry}
\section{Overview: Representation and Operations of Points}
\begin{itembox}[l]{Overview}
We encounter opportunities to handle geometric problems with computers in various situations. Here, I would like to introduce the basics of dealing with geometric problems (please take a specialized course to learn more). For example, let's try to represent familiar concepts such as parallelism and inside/outside of a figure using the tool of "signed area of a triangle." Even for simple geometric concepts for humans, there are cases where non-intuitive methods are suitable when describing them as programs. Also, since we are dealing with floating-point numbers (\texttt{double}, etc.), it is necessary to pay attention to errors.
\end{itembox}
When representing points on a plane in C or C++, for example, there is a method using structures (\pcaojbook[pp.~365--(Chapter 16)]). In this material, to make it a little easier, we will represent them as complex numbers as follows.
\subsection{Representation of Points Using Complex Numbers}
\paragraph{Representation Using Complex Numbers in C++}
In C++, the \eindex{complex} type in the standard library is used. (The real part \texttt{real()} corresponds to \texttt{x}, and the imaginary part \texttt{imag()} corresponds to \texttt{y}):
\begin{center}
\begin{tikzpicture}
\coordinate (O) at (0,0);
\coordinate (P) at (-2,1);
\coordinate (Q) at (3,-1);
\draw [step=1cm,dotted] (-4.2,-1.2) grid (4.2,1.9);
\draw [->,ultra thick] (-4.5,0) -- (4.9,0);
\draw [->,ultra thick] (0,-1.3) -- (0,2.0);
\node [above] at (4.5,0) {X};
\node [right] at (0,1.8) {Y};
\draw [fill=black] (O) circle (2pt);
\node [below left] at (0,0) {O};
\draw [fill=black] (P) circle (3pt);
\node [above left] at (P) {P (-2,1)};
\draw [fill=black] (Q) circle (3pt);
\node [above right] at (Q) {Q};
\draw [->,thick,dashed] (P) -- (2.9,-0.9);
\end{tikzpicture}
\end{center}
\begin{cbox}[emph={complex,real,imag}]
#include <complex>
#include <cmath>
typedef complex<double> xy_t;
xy_t P(-2, 1), Q; // Initialization
cout << P << endl; // (for debug) display
cout << P.real() << endl; // x coordinate
cout << P.imag() << endl; // y coordinate
Q = P + xy_t(5, -2); // Point Q is the position of point P translated by (5,-2)
Q *= xy_t(cos(a), sin(a)); // Rotate point Q around the origin by a (radians)
cout << abs(P) << endl; // Length of vector OP
cout << norm(P) << endl; // \texttt{norm(P) = abs(P)}${}^2$
\end{cbox}
\paragraph{Representation Using Complex Numbers in C} Although the use of C is not recommended in this material, it is included here for the sake of the notes mentioned later.
In the case of C (gcc or C99):
\begin{purecbox}[emph={complex,creal,cimag}]
#include <complex.h>
#include <math.h>
complex a = 0.0 + 1.0I; // Initialization
complex b = cos(3.14/4) + sin(3.14/4)*I;
printf("
a *= b; // Multiplication
printf("
\end{purecbox}
\begin{debugbox}{Caution about Forgetting Multiplication Symbols}
When calculating the product of the number \texttt{5} and the variable \texttt{k}, write \texttt{5*k}; writing \texttt{5k} will result in a compilation error. However, for the characters \texttt{i,j,I,J}, notations such as \texttt{5j} are interpreted as the imaginary unit above and do not cause a compilation error. When displayed with \texttt{cout}, it is cast to \texttt{bool} and displayed as \texttt{1}. This can be difficult to find if you are not aware of it.
\end{debugbox}
\medskip
\paragraph{Representation Using Complex Numbers in Python} In Python3, complex numbers \texttt{complex} can be used in almost the same way. For details, please check \texttt{help(complex)} or \texttt{help(cmath)}.
\begin{pybox}[emph={real,imag,complex}]
import cmath
import math
P = complex(-2,1) # \texttt{(-2+1j)} is also acceptable
print(P)
print(P.real) # Real part
print(P.imag) # Imaginary part
Q = P + complex(5,-2) # Translation
Q *= complex(math.cos(a), math.sin(a)) # Rotation
print(abs(P)) # Length
\end{pybox}
\subsection{Frequently Used Operations}
\begin{center}
\begin{tabular}{c@{\hspace{5em}}c}
\begin{tikzpicture}
\coordinate (O) at (0,0);
\coordinate (A) at (3,1);
\coordinate (B) at (1,2);
\coordinate (BcosT) at (1.45,0.5);
\draw [step=1cm,dotted] (-0.5,-0.5) grid (3.9,3.9);
\draw [->,ultra thick] (-0.5,0) -- (4,0);
\draw [->,ultra thick] (0,-0.5) -- (0,4);
\node [above] at (4,0) {X};
\node [right] at (0,4) {Y};
\draw [fill=black] (A) circle (3pt);
\node [above right] at (A) {$a$};
\draw [fill=black] (B) circle (3pt);
\node [above left] at (B) {$b$};
\draw [] (BcosT) circle (3pt);
\node [below right] at (BcosT) {$b\cos\theta$};
\draw [->,thick] (O) -- (2.9,0.9);
\draw [->,thick] (O) -- (0.9,1.9);
\draw [->,thick] (0.6,0.25) arc (30:60:0.8);
\draw [thick,dashed] (B) -- (BcosT);
\node at (0.7,0.7) {$\theta$};
\end{tikzpicture}
&
\begin{tikzpicture}
\coordinate (O) at (0,0);
\coordinate (A) at (2,1);
\coordinate (B) at (1,2);
\coordinate (AB) at (3,3);
\draw [color=white,fill=gray!25!] (O) -- (A) -- (AB) -- (B) -- cycle;
\draw [step=1cm,dotted] (-0.5,-0.5) grid (3.9,3.9);
\draw [->,ultra thick] (-0.5,0) -- (4,0);
\draw [->,ultra thick] (0,-0.5) -- (0,4);
\node [above] at (4,0) {X};
\node [right] at (0,4) {Y};
\draw [fill=black] (A) circle (3pt);
\node [right] at (A) {$a$};
\draw [fill=black] (B) circle (3pt);
\node [above left] at (B) {$b$};
\draw [] (AB) circle (3pt);
\node [above right] at (AB) {$a+b$};
\draw [->,thick] (O) -- (1.9,0.9);
\draw [->,thick] (O) -- (0.9,1.9);
\draw [->,thick] (1.5,0.75) arc (30:60:1.9);
\draw [->,thick,dashed] (A) -- (2.9,2.8);
\draw [->,thick,dashed] (B) -- (2.8,2.9);
\end{tikzpicture}
\\
(1) Dot product: $|a||b|\cos\theta$ & (2) Cross product: Signed area of the shaded part
\end{tabular}
\end{center}
\begin{cbox}[emph={cross_product,dot_product,projection}]
// Figure (1) Dot product: a.x*b.x +a.y*b.y
double dot_product(xy_t a, xy_t b) { return (conj(a)*b).real(); }
// Figure (2) Cross product, twice the \textcolor{ired}{signed area of the triangle} formed by vectors a and b: a.x*b.y - b.x*a.y
double cross_product(xy_t a, xy_t b) { return (conj(a)*b).imag(); }
// (No corresponding figure) Projection: Project point p onto the line connecting the origin and b
xy_t projection(xy_t p, xy_t b) { return b*dot_product(p,b)/norm(b); }
\end{cbox}
The introduction of the \eindex{signed area}{signed area} of a triangle is the main theme of the first half of this chapter. This calculates the area of the triangle formed by the origin and points a and b, with a sign. The sign is positive if the origin and points a and b are in a counter-clockwise positional relationship in this order, and negative if they are in a clockwise relationship. It is used not only for area but also for determining orientation, as we will see later.
The dot product is useful when projecting points onto a line.
\begin{pybox}[emph={cross_product,dot_product,projection,norm}]
def norm(c):
a = abs(c)
return a*a
def dot_product(a, b):
return (a.conjugate()*b).real
def cross_product(a,b):
return (a.conjugate()*b).imag
def projection(p, b):
return b*dot_product(p,b)/norm(b)
\end{pybox}
\section{Using the Signed Area of a Triangle}
\subsection{Area of a Polygon}
\begin{psbox}{Area of Polygon}{PC Koshien 2005}
Find the area of a convex polygon.
Note 1: Although Heron's formula is written in the problem statement, solve it using the signed area of a triangle below. (To apply it to the area of non-convex polygons later)
Note 2: The vertex sequence is given in order, but since it is not specified whether it is clockwise or counterclockwise, take the absolute value at the end.
\aojid{0079}
\end{psbox}
\begin{center}
\begin{tikzpicture}
\coordinate (O) at (0,0);
\coordinate (A) at (2,1);
\coordinate (B) at (1,2);
\coordinate (P0) at (5,1);
\coordinate (P1) at (7,2);
\coordinate (P2) at (6,3);
\draw [color=white,fill=gray!20!] (P0) -- (P1) -- (P2) -- cycle;
\draw [] (P0) -- (P1) -- (P2) -- (5,3) -- (4,2) -- cycle;
\draw [step=1cm,dotted] (-0.5,-0.5) grid (7.9,3.9);
\draw [->,ultra thick] (-0.5,0) -- (8,0);
\draw [->,ultra thick] (0,-0.5) -- (0,4);
\node [above] at (8,0) {X};
\node [right] at (0,4) {Y};
\node [above right] at (A) {$a=p_1-p_0$};
\node [above] at (B) {$b=p_2-p_0$};
\draw [->,thick] (O) -- (1.9,0.9);
\draw [->,thick] (O) -- (0.9,1.9);
\draw [->,thick] (1.5,0.75) arc (30:60:1.9);
\draw [thick,dashed] (5,1) -- (6,3);
\draw [thick,dashed] (5,1) -- (5,3);
\node [below] at (P0) {$p_0$};
\node [right] at (P1) {$p_1$};
\node [above] at (P2) {$p_2$};
\draw [dotted] (A) -- (P1);
\draw [dotted] (B) -- (P2);
\draw [dotted] (O) -- (P0);
\end{tikzpicture}
\end{center}
Since a (simple) polygon can be decomposed into triangles, if the area of a triangle can be calculated, the area of a polygon can be calculated. Especially in the case of a convex polygon, it can be neatly divided by triangles formed by one vertex and the edges that do not include that vertex.
\begin{cbox}
xy_t P[110];
int main() {
// Input example: Let N be the number of points read
int N=0;
double x, y;
while (~scanf("%lf,%lf", &x, &y)) {
P[N++] = xy_t(x,y);
}
// Area calculation
double sum = 0.0;
for (int i=0; i+2<N; ++i) {
xy_t a=P[0], b=P[i+1], c=P[i+2];
sum += ... // Add the area of triangle abc
}
printf("%.10f\n", abs(sum/2.0));
}
\end{cbox}
\begin{tipsbox}{How to read as long as input continues with scanf}
In order to read input lines as long as they can be read, the sample code adopts a loop of \texttt{while (\~{}scanf("\%lf,\%lf", \&x, \&y))}. This is a short (but not very versatile) way and can only be used in an environment where \texttt{\~{}EOF} becomes 0.
\end{tipsbox}
\begin{pybox}
P = [] # Vertex sequence
try:
while True:
x,y = map(float,input().split(','))
P.append(complex(x,y))
except EOFError:
pass
N = len(P) # Number of vertices
total = 0.0
for i in range(1,N-1):
a,b,c = P[0],P[i],P[i+1]
total += cross_product(b-a,c-a) # Add the area of triangle abc
print("{:.10f}".format(abs(total/2.0)))
\end{pybox}
\begin{tipsbox}{How to read as long as input continues with Python3}
If \texttt{input()} is attempted and the input is finished, Python raises an exception called \texttt{EOFError}, so it is surrounded by \texttt{try} in advance and detected by \texttt{except}. When an exception occurs, the \texttt{while} loop where \texttt{input()} was written is exited, and the outer \texttt{except} block is executed (in this case, \texttt{pass}, which does nothing and moves to the next line).
\end{tipsbox}
\begin{psbox}{Polygon - Area}{AOJ}
Calculate the area of a polygon. It is not necessarily convex, but the vertices are given in counterclockwise order.
\aojid{CGL_3_A}
(Similar problem: Area of Polygons (Domestic Preliminary 1998) \aojid{1100} Only the direction in which the vertices are given is different)
\end{psbox}
For a non-convex simple polygon, if the same division as before is performed, triangles will overlap, but if the sum is taken including the sign of the signed area, the correct area can be obtained (surprisingly). The vertices of the polygon must be given in counterclockwise order. Although $p_0$ was used as the center of the division, it is also possible to consider triangles formed by any point (for example, the origin) and each side.
\begin{center}
\begin{tabular}{ccc}
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2.5,1.5);
\coordinate (P1) at (5,1);
\coordinate (P2) at (3,3);
\coordinate (P3) at (6,3);
\coordinate (P4) at (2,4);
\draw [color=iblue,fill=gray!20!,thick,dashed] (P0) -- (P1) -- (P2) -- cycle;
\draw [] (P0) -- (P1) -- (P2) -- (P3) -- (P4) -- cycle;
\node [below] at (P0) {$p_0$};
\node [right] at (P1) {$p_1$};
\node [above] at (P2) {$p_2$};
\node [right] at (P3) {$p_3$};
\node [left] at (P4) {$p_4$};
\draw [->,ultra thick,dotted,color=iblue] ($(P0)+(1.0,0.6)$) ++(-60:0.5) arc (-60:210:0.5);
\end{tikzpicture}
&
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2.5,1.5);
\coordinate (P1) at (5,1);
\coordinate (P2) at (3,3);
\coordinate (P3) at (6,3);
\coordinate (P4) at (2,4);
\draw [color=iblue,fill=gray!20!,thick,dashed] (P0) -- (P2) -- (P3) -- cycle;
\draw [] (P0) -- (P1) -- (P2) -- (P3) -- (P4) -- cycle;
\node [below] at (P0) {$p_0$};
\node [right] at (P1) {$p_1$};
\node [above] at (P2) {$p_2$};
\node [right] at (P3) {$p_3$};
\node [left] at (P4) {$p_4$};
\draw [->,ultra thick,dotted,color=ired] ($(P0)+(1.6,0.7)$) ++(235:0.5) arc (235:-30:0.5);
\end{tikzpicture}
&
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2.5,1.5);
\coordinate (P1) at (5,1);
\coordinate (P2) at (3,3);
\coordinate (P3) at (6,3);
\coordinate (P4) at (2,4);
\draw [color=iblue,fill=gray!20!,thick,dashed] (P0) -- (P3) -- (P4) -- cycle;
\draw [] (P0) -- (P1) -- (P2) -- (P3) -- (P4) -- cycle;
\node [below] at (P0) {$p_0$};
\node [right] at (P1) {$p_1$};
\node [right] at (P3) {$p_3$};
\node [left] at (P4) {$p_4$};
\draw [->,ultra thick,dotted,color=iblue] ($(P0)+(0.6,1.3)$) ++(-60:0.5) arc (-60:210:0.5);
\end{tikzpicture}
\\
$p_0p_1p_2$ (sgn: +)
&
$p_0p_2p_3$ (sgn: -)
&
$p_0p_3p_4$ (sgn: +)
\end{tabular}
\end{center}
\subsection{Determining Parallelism}
\begin{psbox}{Parallelism}{PC Koshien 2003}
Overview: Given four distinct coordinate points A = (x1, y1), B = (x2, y2), C = (x3, y3), and D = (x4, y4), determine whether the lines AB and CD are parallel.
The coordinates of the points are given as real numbers with up to 5 decimal places (use this information to estimate numerical errors).
\aojid{0021}
\end{psbox}
Solution Strategy: Determine whether the triangle formed by vectors AB and CD has an area.
\begin{cbox}[emph={eps}]
const double eps = 1e-11;
double x[4], y[4];
int N;
int main() {
cin >> N; // Number of problems
for (int t=0; t<N; ++t) {
for (int i=0; i<4; ++i)
cin >> x[i] >> y[i]; // x0,y0..x3,y3
xy_t a[2] = {
xy_t(x[0],y[0]) - xy_t(x[1],y[1]),
xy_t(x[2],y[2]) - xy_t(x[3],y[3])
};
bool p = abs(cross_product(a[0], a[1])) < eps;
cout << (p ? "YES" : "NO") << endl;
}
}
\end{cbox}
Note: For determining direction and angle, library functions such as \texttt{sin} and \texttt{arg} can be used, but from the viewpoint of calculation errors, it is better to calculate using the signed area as much as possible. For example, Taylor expansion is used in general implementations of trigonometric functions.
\footnote{Reference: FreeBSD implementation \url{https://svnweb.freebsd.org/base/release/10.1.0/lib/msun/src/k_cos.c?view=markup}}
\begin{pybox}
N = int(input())
for _ in range(N):
P = list(map(float,input().split()))
a, b, c, d = [complex(P[i*2],P[i*2+1]) for i in range(4)]
parallel = abs(cross_product(b-a,d-c)) < 1e-11 # Calculate the boolean value indicating whether ab and cd are parallel
print("YES" if parallel else "NO")
\end{pybox}
\begin{debugbox}{Operation Check}
This problem has few sample input/output examples, and the judge data is also not public. Therefore, it is good to try your own test data. For example, long lines, short lines, and the positive/negative sign of the area are examples to check.
For example, the following examples are all ``NO''.
\begin{terminal}
-0.00001 0 0.00001 0 -0.0001 0 0.00001 0.00001
-100 100 100 100 -100 100 100 99.99999
\end{terminal}
\end{debugbox}
\medskip
\paragraph{Handling Numerical Errors $\star$}
When using floating-point numbers such as \texttt{double}, numbers that are not represented as the sum of powers of $\frac{1}{2}$ inevitably contain errors (see also Section \ref{section:floating-point-numbers}). In this problem, the input is explicitly stated to have an absolute value of 100 or less, and each value has a maximum of 5 decimal places. Therefore, the effect of errors can be avoided by multiplying by $10^5$ and handling them as integers (\texttt{long long}).
Alternatively, there is a method of predicting the range of errors, such as \texttt{eps} in the sample code.
When errors are added to each element of two vectors $(a,b)$ and $(c,d)$, compare (1) the maximum value of $|ad-bc|$ when they are parallel (0 if there is no error) and (2) the minimum value of $|ad-bc|$ when they are not parallel, and set the threshold so that (1)$<$threshold$<$ (2).
Roughly estimating, (1) is at most
$(4\cdot100)\cdot(100\cdot2^{-54})\approx2.2\cdot10^{-12}$
($100\cdot2^{-54}$ is the representation error when a number up to 100 is represented by \texttt{double}, 400 is
an estimate of the coefficient of $\varepsilon$ when expanding
$|(a+\varepsilon)(d+\varepsilon)-(b+\varepsilon)(c+\varepsilon)|$),
and (2) is about $10^{-10}$ (from the square of the $10^{-5}$ value that can be represented by the input).
Note that, depending on the environment, if you use a relatively new Intel or AMD CPU and a relatively new gcc, you can also perform calculations with better precision of 80-bit or 128-bit by using \texttt{long double} or \texttt{\_\_float128}. There are points to note for each, so please investigate the literature if you use them.
\subsection{Inside/Outside Determination}
\begin{psbox}{A Point in a Triangle}{PC Koshien 2003}
Given a triangle with vertices (x1, y1), (x2, y2), and (x3, y3) on a plane, and a point P(xp, yp), determine whether point P is inside the triangle (excluding the vertices and edges of the triangle).
\aojid{0012}
\end{psbox}
Example Solution: Let the vertices of the triangle be a, b, and c. Consider the signed areas of the three triangles pab, pbc, and pca. If p is inside abc, the signs will match; if it is outside, they will not match.
\begin{tabular}{c@{\hspace{3em}}c}
\begin{tikzpicture}[x=2mm,y=2mm]
\fill[ired] (10,10) circle (0.5);
\node[above right] at (10,10) {$p$};
\node[right] at (20,0) {$a$};
\node[above] at (10,20) {$b$};
\node[left] at (0,5) {$c$};
\draw[->, thick] (20,0) edge node [left] {\small Left} (10,20);
\draw[->, thick] (10,20) edge node [right] {\small Left} (0,5);
\draw[->, thick] (0,5) edge node [above] {\small Left} (20,0);
\draw[dotted] (20,0) -- (10,10);
\draw[dotted] (10,20) -- (10,10);
\draw[dotted] (0,5) -- (10,10);
\begin{scope}[xshift=57,yshift=57,rotate=20]
\draw [->,ultra thick,dotted,color=iblue] (0,0) ++(-30:2.5) arc (-30:90:2.5);
\draw [->,ultra thick,dotted,color=iblue] (0,0) ++(90:2.5) arc (90:210:2.5);
\draw [->,ultra thick,dotted,color=iblue] (0,0) ++(210:2.5) arc (210:330:2.5);
\end{scope}
\end{tikzpicture}
&
\begin{tikzpicture}[x=2mm,y=2mm]
\fill[ired] (18,15) circle (0.5);
\node[above right] at (18,15) {$p$};
\node[right] at (20,0) {$a$};
\node[above] at (10,20) {$b$};
\node[left] at (0,5) {$c$};
\draw[->] (20,0) edge node [right] {\small Right} (10,20);
\draw[->] (10,20) edge node [right] {\small Left} (0,5);
\draw[->] (0,5) edge node [above] {\small Left} (20,0);
\draw[dotted] (20,0) -- (18,15);
\draw[dotted] (10,20)-- (18,15);
\draw[dotted] (0,5) -- (18,15);
\begin{scope}[xshift=57,yshift=57,rotate=20]
\draw [->,ultra thick,dotted,color=ired] (0,0) ++(90:2.5) arc (90:-30:2.5);
\draw [->,ultra thick,dotted,color=iblue] (0,0) ++(90:2.5) arc (90:210:2.5);
\draw [->,ultra thick,dotted,color=iblue] (0,0) ++(210:2.5) arc (210:330:2.5);
\end{scope}
\end{tikzpicture}\\
Point inside the figure & Point outside the figure
\end{tabular}
\begin{cbox}
double x[4], y[4];
int main() {
while (true) {
for (int i=0; i<4; ++i) cin >> x[i] >> y[i];
if (!cin) break;
xy_t a(x[0],y[0]), b(x[1],y[1]), c(x[2],y[2]), p(x[3],y[3]);
// Twice the signed area of pab is \texttt{cross\_product(a-p,b-p)}
// Twice the signed area of pbc is \texttt{cross\_product(b-p,c-p)}
// Twice the signed area of pca is \texttt{cross\_product(c-p,a-p)}
bool ok = signs are the same
cout << (ok ? "YES" : "NO") << endl;
}
}
\end{cbox}
For inside/outside determination of polygons that are not necessarily convex, see the next section.
\subsection{Convex Hull}
\begin{pbox}{Convex Polygon - Convex Hull$\star$}{AOJ}
Find the convex hull of a given set of points. Refer to the diagram in the similar problem for what a convex hull is.
(Note: This is a slightly special setting that requires outputting points on the edges.)
\aojid{CGL_4_A}
(Similar problem: Enclose Pins with a Rubber Band (PC Koshien 2004) \aojid{0068} This one has a more straightforward setting)
\end{pbox}
Example Solution: Sort the points by their X-coordinates, and starting from the minimum value (the leftmost point), go right, first constructing the lower half of the outer perimeter.
If, during the process, the direction changes to the right of the current direction of travel (which means that a point that is not originally part of the convex hull has been included), remove all the points that caused this. Perform the same process for the upper half, starting from the rightmost point.
If the number of points is $N$, the above procedure for finding half of the perimeter can be done in $O(N)$, so the total computation time, including the time required for sorting, is $O(N\log N)$.
\begin{center}
\begin{tabular}{c@{\hspace{3em}}c@{\hspace{3em}}c}
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2,4);
\coordinate (P1) at (2.5,1.5);
\coordinate (P2) at (3,3);
\coordinate (P3) at (5,1);
\coordinate (P4) at (6,3);
\draw [] (P0) circle (2.5pt);
\draw [] (P1) circle (2.5pt);
\draw [] (P2) circle (2.5pt);
\draw [] (P3) circle (2.5pt);
\draw [] (P4) circle (2.5pt);
\draw (P0) -- (P1);
\end{tikzpicture}
&
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2,4);
\coordinate (P1) at (2.5,1.5);
\coordinate (P2) at (3,3);
\coordinate (P3) at (5,1);
\coordinate (P4) at (6,3);
\draw [] (P0) circle (2.5pt);
\draw [] (P1) circle (2.5pt);
\draw [] (P2) circle (2.5pt);
\draw [] (P3) circle (2.5pt);
\draw [] (P4) circle (2.5pt);
\draw (P0) -- (P1) -- (P2);
\end{tikzpicture}
&
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2,4);
\coordinate (P1) at (2.5,1.5);
\coordinate (P2) at (3,3);
\coordinate (P3) at (5,1);
\coordinate (P4) at (6,3);
\draw [] (P0) circle (2.5pt);
\draw [] (P1) circle (2.5pt);
\draw [] (P2) circle (2.5pt);
\draw [] (P3) circle (2.5pt);
\draw [] (P4) circle (2.5pt);
\draw (P0) -- (P1) -- (P2);
\draw[thick,dashed] (P2) -- (P3);
\end{tikzpicture}
\\
t=0: From the leftmost (minimum x-coordinate)
&
t=1: Connect the lines in order
&
t=2: If it turns right
\\
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2,4);
\coordinate (P1) at (2.5,1.5);
\coordinate (P2) at (3,3);
\coordinate (P3) at (5,1);
\coordinate (P4) at (6,3);
\draw [] (P0) circle (2.5pt);
\draw [] (P1) circle (2.5pt);
\draw [] (P2) circle (2.5pt);
\draw [] (P3) circle (2.5pt);
\draw [] (P4) circle (2.5pt);
\draw (P0) -- (P1) -- (P3);
\end{tikzpicture}
&
\begin{tikzpicture}[scale=0.8]
\coordinate (P0) at (2,4);
\coordinate (P1) at (2.5,1.5);
\coordinate (P2) at (3,3);
\coordinate (P3) at (5,1);
\coordinate (P4) at (6,3);
\draw [] (P0) circle (2.5pt);
\draw [] (P1) circle (2.5pt);
\draw [] (P2) circle (2.5pt);
\draw [] (P3) circle (2.5pt);
\draw [] (P4) circle (2.5pt);
\draw (P0) -- (P1) -- (P3) -- (P4);
\end{tikzpicture}
\\
t=4: Delete unnecessary points and reconnect
&
t=5: Lower side complete
\end{tabular}
\end{center}
\paragraph{Sorting Points}
Since the C++ complex number type (complex) does not have comparison operators defined, it is necessary to define them yourself. If you define \texttt{operator<} in the \texttt{std} namespace as in the example below, it will be automatically used by \texttt{sort}.
As a comparison criterion, use something such that \texttt{a==b} if \texttt{!(a<b)} and \texttt{!(b<a)} are both true.\footnote{\url{https://en.cppreference.com/w/cpp/named_req/Compare}}
\begin{cbox}[emph={std}]
namespace std {
bool operator<(xy_t l, xy_t r) {
return (l.real()!=r.real()) ? l.real()<r.real() : l.imag()<r.imag();
}
// Alternative: When aligning with std::pair
bool operator<(xy_t l, xy_t r) {
return make_pair(l.real(), l.imag()) < make_pair(r.real(), r.imag());
}
}
\end{cbox}
\section{Various Topics}
\begin{psbox}{A Symmetric Point}{PC Koshien 2005}
Output the point that is symmetrical to point Q with respect to a line.
\aojid{0081}
\end{psbox}
Example Solution: Let S be the point where Q is projected onto the line. Then, the desired point R is at the position where S is translated by the vector QS. For processing comma-separated input and controlling the number of decimal places in the output, it is convenient to use \texttt{scanf} and \texttt{printf} after \texttt{\#include<cstdio>} as follows.
\begin{cbox}
#include <cstdio>
double X1,Y1,X2,Y2,XQ,YQ;
int main() {
while (~scanf("%lf,%lf,%lf,%lf,%lf,%lf",
&X1, &Y1, &X2, &Y2, &XQ, &YQ)) {
xy_t P1(X1,Y1), P2(X2,Y2), Q(XQ,YQ);
xy_t R = ...; // Calculate the point of line symmetry
printf("%.10f,%.10f\n", R.real(), R.imag());
}
}
\end{cbox}
\begin{pbox}{Polygon - Polygon-Point Containment}{AOJ}
Determine whether a point is inside or outside a polygon that is not necessarily convex.
\aojid{CGL_3_C}
\end{pbox}
(Note: Normally, it is difficult to determine whether a point is on an edge, but it is possible in this case because the coordinates are integers.)
Example Solution: Extend a half-line from the point you want to check in any direction and count the number of edges it crosses. If it is even, it is outside; if it is odd, it is inside. It is necessary to prepare functions in advance, such as whether a line segment has an intersection with a line. If the half-line passes very close to a vertex, it is safer to change the angle to avoid worrying about the effects of errors.
\begin{pbox}{Point Set - Closest Pair$\star$}{AOJ}
Find the closest pair of points.
\aojid{CGL_5_A}
\end{pbox}
If the number of points is $N$, trying all pairs of points requires $O(N^2)$ time, but it is possible in $O(N\log N)$ using divide and conquer. There also exists a randomized algorithm with $O(N)$.
Divide and Conquer Strategy: Sort the points by X-coordinate and Y-coordinate, respectively. Divide the points in half by the X-coordinate, and recursively find the closest pair in the left and right halves. Let $d$ be the smaller of the two minimum distances found. The closest pair of the whole is either the closest pair of the left half, the closest pair of the right half, or the closest pair of a point in the left half and a point in the right half. For the latter, when the points within a distance $d$ from the dividing line between the left and right halves are sorted by Y-coordinate, it can be determined in a linear number of calculation steps with respect to the number of points by using the property that only pairs within a constant number (e.g., 8) are candidates. The proof is based on the fact that points cannot exist too densely with the restriction of $d$ when considering an appropriate square grid around the dividing line. In the implementation, it is not possible to achieve $O(N\log N)$ if the points are sorted by Y-coordinate every time. It is better to sort the whole set once at the beginning and then distribute them during the division. Also, when dividing, it may be necessary to pay attention to the case where multiple points have the same Y-coordinate. In practice, this can be avoided by rotating the whole set randomly at the beginning.
\section{Applied Problems}
\begin{pbox}{ConvexCut}{Summer Camp 2012}
Determine if there exists a point in a given figure such that it can be cut into two equal areas regardless of the cutting angle.
\aojid{2442}
\end{pbox}
It can be proven that this is only possible when the polygon has an even number of vertices and all pairs of edges that should be paired are parallel, or when the midpoints of the paired vertices are equal.
Example Answer (Input/Output)
\begin{cbox}
#include <complex>
#include <iostream>
#include <cstdio>
using namespace std;
int N, x, y;
typedef complex<double> xy_t;
xy_t P[60];
void solve() {
...
}
int main() {
while (cin >> N) {
for (int i=0; i<N; ++i) {
cin >> x >> y;
P[i] = xy_t(x,y);
}
solve();
}
}
\end{cbox}
Example Answer (Midpoint Calculation)
\begin{cbox}
void solve() {
// If it's odd, there is no such point
...
xy_t a = (P[0]+P[N/2])*0.5; // Midpoint of P[0] and P[N/2]
for (int i=1; i<N/2; ++i) {
xy_t b = ... // Midpoint of P[i] and P[i+N/2]
// If a and b do not match even with error considered, abs(a-b) > eps, there is no such point
}
printf("YES\n");
}
\end{cbox}
\begin{pbox}{Circle and Points$\star$}{National Preliminary 2004}
N points are given on the xy-plane. Move a circle of radius 1 on the xy-plane to enclose as many of these points as possible. At this time, answer the maximum number of points that can be enclosed simultaneously. Here, a circle "encloses" a point if the point is inside or on the circumference of the circle. (This problem statement has sufficient descriptions regarding errors)
\aojid{1132}
\end{pbox}
Since there are an infinite number of candidate circle positions, narrow down the candidates.
("Consider the limit" \pccbook[p.~229])
\begin{tipsbox}{Way of Thinking}
Let n be the maximum number of points that can be enclosed simultaneously, and assume there is a circle that encloses n points. If no point is touching the circle, even if you move it until one of the points inside touches, the number of points enclosed will not change.
That is, it is sufficient to consider only circles that touch one of the points (even if you consider the remaining circles, the answer will not change). However, there are still an infinite number of such circles.
Assume there is a circle that encloses n points, and one point is on the circle. If you rotate the circle around that point \textcolor{white}{as the center, the number of points enclosed will not change until a new point inside touches the circle.
That is, it is sufficient to consider only circles that pass through two points (even if you consider the remaining circles, the answer will not change). There are only about $2N^2$ such circles.}
\end{tipsbox}
\begin{debugbox}{Caution for Exceptional Cases}
The above idea is generally correct, but there are exceptional cases. That is, \textcolor{white}{when the answer is 1, the circle that gives the maximum does not have} the above property.
\end{debugbox}
\begin{debugbox}{How to Count Points}
Suppose you want to set the position of a circle that exactly covers a certain point p and check the number of points included in it. For that purpose, if you calculate the distance to the center of the circle for all points, you can generally determine it. However, for the point p itself, since it is located on the circle, it may be determined to be outside due to numerical errors. If you increase the tolerance here, there is a risk of determining points that are truly outside as inside. Therefore, the determination of point p should be treated specially, and \textcolor{white}{it is better to use the identity of the id (what number it is if the points are managed in an array) without calculating the distance.}
\end{debugbox}
Example Answer:
\begin{cbox}
int main() {
// Initialize the maximum value
for (/*point p*/) {
for (/*point q*/) { // p!=q
if (/*if there is a circle passing through pq*/) { // There can be 0, 1, or 2 cases
/*Count the number of points inside while checking all points*/
/*Update if it exceeds the maximum value*/
}
}
}
}
\end{cbox}
\begin{pbox}{Roll-A-Big-Ball}{National Preliminary 2008}
Find the maximum size of a large ball that satisfies the conditions.
\aojid{1157}
\end{pbox}
\begin{pbox}{Space Golf}{Asian Tournament 2014}
\aojid{1348}
\end{pbox}
\begin{pbox}{Chain-Confined Path$\star$}{National Preliminary 2012}
Find the shortest path through a ring.
\aojid{1183}
\end{pbox}
Hint: Consider the shape of the shortest path.
Solution: \textcolor{white}{Let the start point, end point, and the intersection points of each circle be vertices, find if it is possible to move in a straight line between each point to create edges, and solve the shortest path problem.}
\begin{pbox}{Neko's Treasure$\star$}{Mock Regional Preliminary 2009}
Find how many walls to overcome (refer to the problem statement).
\aojid{2181}
\end{pbox}
\begin{pbox}{Area of Polygons$\star$}{Asian Tournament 2003}
Find the area of the shaded part.
\aojid{1242}
\end{pbox}
Way of thinking: It's just a matter of slicing and summing, but there are quite a few points to note, such as when multiple lines pass through the same square.
Reference: \url{http://www.ipsj.or.jp/07editj/promenade/4501.pdf}
\begin{pbox}{Treasure Hunt$\star$}{Summer Camp 2012}
Count the treasures in the area (efficiently).
\aojid{2426}
\end{pbox}
If you count naively, it will take too much time, so perform preprocessing when the points are given and prepare to answer the questions.
As a data structure for efficiently answering questions, for example, a quad tree can be used.
\begin{pbox}{Altars$\star\star$}{6th Polish Olympiad in Informatics}
A pillow that says that in China, evil spirits are believed to travel in straight lines.
There is a rectangular temple with an altar in the center. The walls of the temple are either east-west or north-south. The entrance to the temple is in the middle of one side. Check if there is a line of sight from the outside to the altar.
\url{http://main.edu.pl/en/archive/oi/6/olt}
\end{pbox}
\begin{pbox}{Fish$\star\star$}{Algorithmic Engagements 2009}
There are fish that wake up/go to sleep at the same time every day. When they wake up, they may be shifted by one square due to ocean currents. They swim so that they can see their position at the same time yesterday. They can accelerate and decelerate freely. There are many records of the fish's movements for one day, but the dates are unknown. What is the minimum number of fish that can be said to be observed?
\url{http://main.edu.pl/en/archive/pa/2009/ryb}
\end{pbox}
\chapter{Simple Parsing}\label{chapter:parsing}
\begin{itembox}[l]{Example Problems}
Let's make a computer understand a string written in a specific grammar:
\begin{itemize}
\setlength{\itemsep}{0pt}
\item $( V | V ) \& F \& ( F| V)$ \dingright $F$ (Boolean calculation)
\item 35=1?((2*(3*4))+(5+6)) \dingright '+' (Operator estimation)
\item 4*x+2=19 \dingright x=4.25 (Solving equations)
\item C2H5OH+3O2+3(SiO2) == 2CO2+3H2O+3SiO2 (Calculation of molecular weight)
\end{itemize}
\end{itembox}
\section{Creating Arithmetic Operations}
\subsection{Let's Try Making Addition}
\paragraph{Global Variables}:
\begin{cbox}
const string S = "12+3";
size_t cur = 0; // Abbreviation for cursor, the parsing start position
int parse();
\end{cbox}
Execution Example: (We will create something that works as follows)
\begin{cbox}
int main() {
int a = parse();
assert(a == 15);
assert(cur == S.size());
}
\end{cbox}
\begin{pybox}
S = "0"
cur = 0
a = parse()
assert a == 15
assert cur == len(S)
\end{pybox}
\paragraph{Preparing a Function to Read One Character}
\begin{cbox}[emph={readchar,peek}]
// Reads one character and advances cur
char readchar() {
assert(cur < S.size());
char ret = S[cur];
cur += 1;
return ret;
// It can also be written in one line as return S[cur++];
}
// Reads one character but does not advance cur
char peek() {
assert(cur < S.size());
return S[cur];
}
\end{cbox}
In Python, to change a global variable within a function, specify it with \tindex{global}.
\begin{pybox}[emph=global]
def readchar():
global cur
c = S[cur]
cur += 1
return c
def peek():
return S[cur]
\end{pybox}
\paragraph{What is assert?}
(Re-posted)
\begin{cbox}[emph={cassert,assert}]
#include <cassert>
int factorial(int n) {
assert(n > 0); // (*)
if (n == 1) return 1;
return n * factorial(n-1);
}
\end{cbox}
Execution Example
\begin{cbox}
cout << factorial(3) << endl; // Displays 6
cout << factorial(-3) << endl; // Stops by displaying the line number of (*)
\end{cbox}
\subsubsection{First Addition}
\begin{itembox}[l]{(Rough) Grammar of Addition}
\begin{alltt}
Expression := Number '+' Number
Number := Repetition of Digit
Digit := '0' | '1' | ... | '9'\end{alltt}
\end{itembox}
How to read: (Reference: (Extended) BNF)
\begin{itemize}
\setlength{\itemsep}{0pt}
\item \texttt{P := Q} \dingright Definition of a grammar rule named P
\item \texttt{A B} \dingright B follows A
\item \texttt{'a'} \dingright Character a
\item \texttt{x | y} \dingright x or y
\end{itemize}
\subsubsection{Implementing According to the Grammar (Digit)}
\texttt{\textcolor{ired}{Digit := '0' | '1' | ... | '9'}}
\begin{cbox}[emph={digit,peek,readchar}]
#include <cctype>
int digit() {
assert(isdigit(peek())); // Check that S[cur] is a digit
int n = readchar() - '0'; // Convert '0' to 0
return n;
}
\end{cbox}
Conversion of characters to numbers: In C and C++, characters are managed by numbers representing those characters. Although the character code is not specified in the language standard, it can be considered as the \eindex{ASCII} code in the environment we currently use. In it, using the fact that characters such as '0', '1', '2', ..., 'a', 'b', 'c' are assigned codes in order, the above subtraction shows how many characters after '0' it is, which is the numerical value we want. One way to check the ASCII code table is to use the man command, which is convenient. You can type \texttt{man ascii} in the terminal.
\begin{pybox}
def digit():
assert peek().isdigit()
n = int(readchar()) # Read one character and convert it to a number
return n;
\end{pybox}
In the case of Python, it is good to determine with \texttt{isdigit()} as above and convert with \texttt{int}.
\subsubsection{Implementing According to the Grammar (Number)}
\texttt{\textcolor{ired}{Number := Repetition of Digit}}
\begin{cbox}[emph={number},emph={[2]digit}]
int number() {
int n = digit();
while (cur < S.size() && isdigit(peek())) // Look ahead one character to see if the next is also a digit
n = n*10 + digit();
return n;
}
\end{cbox}
\begin{pybox}[emph={number},emph={[2]digit}]
def number():
n = digit()
while cur < len(S) and peek().isdigit():
n = n*10+digit()
return n
\end{pybox}
\subsubsection{Implementing According to the Grammar (Expression)}
\texttt{\textcolor{ired}{Expression := Number '+' Number}}
\begin{cbox}[emph={expression},emph={[2]number}]
int expression() {
int a = number();
char op = readchar();
int b = number();
assert(op == '+');
return a + b;
}
\end{cbox}
This should work if it's just addition:
\begin{cbox}
const string S = "12+3";
size_t cur = 0; // Parsing start position
..
int parse() { return expression(); }
int main() {
int a = parse();
cout << a << endl; // 15 should be output;
}
\end{cbox}
\paragraph{Test}
Try not only ``12+5'' but also ``1023+888'', etc.
\subsubsection{Extension: Add Subtraction}
Let's try ``12-5'' instead of ``12+5''
Method: Determine if op is '+' or '-' in the expression function
\begin{cbox}
if (op == '+') return a + b;
else return a - b;
\end{cbox}
(Also rewrite assert appropriately)
\subsubsection{Extension: Add Three or More}
Let's try ``1+2+3+4'' instead of ``12+5''
Rewrite expression to allow multiple additions
\begin{cbox}[emph={sum,while}]
int expression() {
int sum = number();
while (cur < S.size() && (peek() == '+' || peek() == '-')) {
// While addition or subtraction continues
char op = readchar();
int b = number();
if (op == '+') add b to sum;
else subtract b from sum;
}
return sum;
}
\end{cbox}
\subsubsection{Next Extensions}
\begin{itemize}
\setlength{\itemsep}{0pt}
\item Support multiplication and division: \\
Create new rules because the precedence of operators changes
\item Support (multiple) parentheses: \\
Create new rules and recurse
\end{itemize}
\subsection{Arithmetic Operations Without Parentheses (Rough) Grammar}
\begin{itembox}[l]{(Rough) Grammar of Arithmetic Operations}
\begin{alltt}
Expression := Term \{ ('+'|'-') Term \}
Term := Number \{ ('*'|'/') Number \}
Number := Digit \{ Digit \}
\end{alltt}
\end{itembox}
How to read: (Reference: (Extended) BNF)
\begin{itemize}
\setlength{\itemsep}{0pt}
\item \texttt{A B} \dingright B follows A
\item \texttt{\{C\}} \dingright Zero or more repetitions of C
\end{itemize}
Example: 5*3-8/4-9
\begin{itemize}
\setlength{\itemsep}{0pt}
\item Term: 5*3, 8/4, 9
\item Number: 5, 3, 8, 4, 9
\end{itemize}
\subsubsection{Implementation of Arithmetic Operations (Term)}
\texttt{\textcolor{ired}{Term := Number \{ ('*'|'/') Number \}}}
\begin{cbox}[emph={term},emph={[2]number,*,/}]
int term() {
int a = number();
while (cur < S.size()
&& (peek() == '*' || peek() == '/')) {
char op = readchar();