-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCodeArchive(All).cpp.cpp
More file actions
2814 lines (2759 loc) · 132 KB
/
CodeArchive(All).cpp.cpp
File metadata and controls
2814 lines (2759 loc) · 132 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
/* UBC CODEARCHIVE 2013
Geometry
General 2D geometry ........................................................ ?
Polygon cutting ............................................................ ?
Point in polygon ........................................................... ?
Arbitrary polygon intersection (highly unreliable) ......................... ?
Triangle area from three medians ........................................... ?
Rectangle in rectangle ..................................................... ?
Closest pair ............................................................... ?
General Line Segment Sweep (Bentley-Ottmann algorithm) ..................... ?
Area of intersection of two circles ........................................ ?
Circles tangents ........................................................... ?
Circular Arc Length ........................................................ ?
Circular boundary traversal ................................................ ?
Circular obstacles visibility graph construction ........................... ?
2D Convex hulls (Graham's scan, monotone chain, orthogonal, circles) ....... ?
General 3D geometry (including CCW 3D axis rotation) ....................... ?
3D convex hulls (slow and quick) ........................................... ?
Arbitrary-Dimension Minimum Enclosing Ball ................................. ?
Math and Number Theory
Rational Numbers ........................................................... ?
Extended GCD ............................................................... ?
Extended GCD in canonical form ............................................. ?
Chinese remainder theorem .................................................. ?
Linear Diophantine Equation Solver ......................................... ?
Legendre symbol ............................................................ ?
Modular Exponentiation ..................................................... ?
Discrete Log ............................................................... ?
Polynomial GCD ............................................................. ?
Polynomial root ............................................................ ?
Pythagorean triples ........................................................ ?
Farey sequences ............................................................ ?
Conic section solver ....................................................... ?
Adaptive Simpsons Integrator ............................................... ?
Linear algebra
Simplex ................................................................... ?
Linear algebra (go Matthew!) ............................................... ?
Matrix determinant ......................................................... ?
FFT ........................................................................ ?
Strings
Suffix array ............................................................... ?
Suffix tree ................................................................ ?
Palindrome substrings ...................................................... ?
KMP string matching ........................................................ ?
Z-value string matching .................................................... ?
Aho Corasick ............................................................... ?
Graph theory
Array-based undirected sparse graph ........................................ ?
Maximum flow ............................................................... ?
Maximum bipartite matching ................................................. ?
Maximum weight bipartite matchings ......................................... ?
General matching (entirely almost not completely unbroken) ................. ?
Biconnected components & 2-edge connected components ....................... ?
Euler path ................................................................. ?
Bart's 2-Sat ............................................................... ?
All pairs min cut .......................................................... ?
Minpath-Vertex cover ....................................................... ?
Strongly connected components .............................................. ?
Number of spanning trees ................................................... ?
Bridge detection ........................................................... ?
Articulation vertex ........................................................ ?
Directed MST ............................................................... ?
K-th shortest path ......................................................... ?
Gomory-Hu tree (All pairs max-flow) ........................................ ?
Trees
KD-tree .................................................................... ?
Binary Indexed Tree ........................................................ ?
Range Query Tree (operation = min) ......................................... ?
Splay Tree ................................................................. ?
Link-cut Tree .............................................................. ?
Miscellaneous
MinQueue ................................................................... ?
Poker ...................................................................... ?
Josephus ring survivor ..................................................... ?
Day of week ................................................................ ?
Roman numerals ............................................................. ?
Rubiks cube ................................................................ ?
Reconstruction of a set from its pairwise sums ............................. ?
Calendar ................................................................... ?
Friend/enemy ............................................................... ?
Expression evaluation/Recursive Descent Parser ............................. ?
N-Queens problem (formula) ................................................. ?
IDEAS (aka Bart's guide to solving any ACM problem) .......................... ?
THEOREMS ..................................................................... ?
*/
ios::sync_with_stdio(0); // faster iostream, but unsyncs with cstdio
#include <bits/stdtr1c++.h> // if using g++, this includes ALL headers.
////////////////////////////////////////////////////////////////////////////////
// General 2D geometry, Polygon cutting, Point in polygon
////////////////////////////////////////////////////////////////////////////////
const int INF = 0x3f3f3f3f; const int MINF = 0xc0c0c0c0;
const ld EPS = 1e-9; const ld PI = acos(-1.L);
ld cp(const pt &a, const pt &b) { return a.real()*b.imag() - b.real()*a.imag();}
ld dp(const pt &a, const pt &b) { return a.real()*b.real() + a.imag()*b.imag();}
inline ld sgn(const ld& x) { return abs(x) < EPS ? 0 : x/abs(x); }
inline bool cmp_lex(const pt& a, const pt& b)
{ return a.real() < b.real() || (a.real() == b.real() && a.imag() < b.imag()); }
inline bool cmp_lex_i(const pt &a, const pt &b)
{ return a.imag() < b.imag() || (a.imag() == b.imag() && a.real() < b.real()); }
// handles ALL cases, change occurences of <= to < to exclude endpoints
bool seg_x_seg(pt a1, pt a2, pt b1, pt b2){
//if (a1==a2 || b1==b2) return false; // uncomment to exclude endpoints
int s1 = sgn(cp(a2 - a1, b1 - a1)), s2 = sgn(cp(a2 - a1, b2 - a1));
int s3 = sgn(cp(b2 - b1, a1 - b1)), s4 = sgn(cp(b2 - b1, a2 - b1));
if(!s1 && !s2 && !s3) { // collinear
if (cmp_lex(a2, a1)) swap(a1,a2); if (cmp_lex(b2, b1)) swap(b1, b2);
return !cmp_lex(b2, a1) && !cmp_lex(a2, b1);
//return cmp_lex(a1, b2) && cmp_lex(b1, a2);//uncomment to exclude endpoints
} return s1*s2 <= 0 && s3*s4 <= 0; }
inline pt line_inter(const pt &a, const pt &b, const pt &c, const pt &d){
return a + cp(c - a, d - c)/cp(b - a, d - c) * (b - a); }
// Projection of (a -> p) to vector (a -> b), SIGNED - positive in front
inline ld proj_dist(const pt &a, const pt &b, const pt &p){
return dp(b - a, p - a) / abs(b - a); }
// SIGNED distance. Pt on the right of vector (a -> b) will be NEGATIVE.
inline ld lp_dist(const pt &a, const pt &b, const pt &p){
return cp(b - a, p - a) / abs(b - a); }
// Line segment (a, b) to pt p distance.
inline ld lsp_dist(const pt &a, const pt &b, const pt &p){
return dp(b - a, p - a) > 0 && dp(a - b, p - b) > 0 ?
abs(cp(b - a, p - a) / abs(b - a)) : min(abs(a - p), abs(b - p)); }
// Closest pt on line segment (a, b) to pt p.
inline pt lsp_closest(const pt &a, const pt &b, const pt &p){
if (dp(b - a, p - a) > 0 && dp(a - b, p - b) > 0)
return abs(cp(b - a, p - a))<EPS ? p : line_inter(a, b, p, p+(a-b)*pt(0,1));
return abs(a - p) < abs(b - p) ? a : b; }
// Area of a polygon (convex or concave). Always non-negative.
ld area(pol v){ ld out=0;
for(int i = v.size()-1, j = 0; j < v.size(); i = j++) out += cp(v[i], v[j]);
return abs(out)/2; }
// orientation does not matter
pt centroid(const pol &v) {
pt res; ld A=0; int n = v.size();
for(int i=n-1,j=0;j<n;i=j++) A+=cp(v[i],v[j]), res+=(v[i]+v[j])*cp(v[i],v[j]);
return abs(A) < EPS ? res : res/3.L/A; }
// Left of the vector (a -> b) will be cut off. Convex polygons tested UVa 10117
pol cut_polygon(const pol &v, const pt &a, const pt &b) { pol out;
for(int i = v.size() - 1, j = 0; j < v.size(); i = j++) {
if(cp(b-a, v[i]-a) < EPS) out.push_back(v[i]);
if(sgn(cp(b-a, v[i]-a)) * sgn(cp(b-a, v[j]-a)) < 0) {
pt p = line_inter(a, b, v[i], v[j]);
if(!out.size() || abs(out.back() - p) > EPS) out.push_back(p); } }
while(out.size() && abs(out[0] - out.back()) < EPS) out.pop_back();
return out; }
inline bool on_segment(const pt &a, const pt &b, const pt &p){
return abs(cp(b-a, p-a)) < EPS && dp(b-a, p-a) > 0 && dp(a-b, p-b) > 0; }
// Checks if p lies on the boundary of a polygon v.
inline bool on_boundary(const pol &v, const pt &p){ bool res = false;
for(int i=v.size()-1,j=0;j<v.size();i=j++) res |= on_segment(v[i], v[j], p);
return res; }
// orientation does not matter !!!
bool pt_in_polygon(const pol &v, const pt &p){ if(on_boundary(v,p)) return true;
ld res = 0; for(int i = v.size() - 1, j = 0; j < v.size(); i = j++)
res += atan2(cp(v[i] - p, v[j] - p), dp(v[i] - p, v[j] - p));
return abs(res) > 1; } // will be either 2*PI or 0
////////////////////////////////////////////////////////////////////////////////
// Arbitrary polygon intersection. Returns intersection. O(n^2 log n)
////////////////////////////////////////////////////////////////////////////////
typedef pair<pt, int> ppi; // Tested on convex polygons UVa 137, 10321
vector<pol> pol_inter(pol v1, pol v2){
int n[2] = { v1.size(), v2.size() }, N = n[0] + n[1];
if(n[0] > n[1]) return pol_inter(v2, v1);
vector<pol> out; if(n[0] < 3) return out;
bool same = (n[0] == n[1]);
for (int i=0; i < n[0]; i++) if (v1[i] != v2[i]) same = false;
if (same) { out.push_back(v1); return out; }
vector<ppi> xs[N]; // xs[i] = sorted list of (intersection, j) for each j
int idx[N][N]; // idx[i][j] = index into xs[i] s.t. xs[i][idx].second == j
memset(idx, 0, sizeof idx);
int id, pvnx[N][2];// ids for the current edge, previous edge, and next edge
// Find intersections, break edges into segments that are in both polygons
for (int k=0; k < 2; k++) { // Try both polygons
for (int i=n[k]-1, j=0; j < n[k]; i=j++) { // for each edge
int id = k*n[0]+i; vector<ppi> &p = xs[id];
pvnx[id][0] = k*n[0] + (i+n[k]-1)%n[k], pvnx[id][1] = k*n[0] + (i+1)%n[k];
for (int ii=n[1-k]-1, jj=0; jj < n[1-k]; ii=jj++) // Find intersections
if (abs(cp(v1[i] - v1[j], v2[ii] - v2[jj])) > EPS &&
seg_x_seg(v1[i], v1[j], v2[ii], v2[jj]))
p.push_back(ppi(line_inter(v1[i],v1[j],v2[ii],v2[jj]),(1-k)*n[0]+ii));
// sort along the edge (so pvnx ids make sense)
if (v1[i]<v1[j]) sort(p.begin(),p.end()); else sort(p.rbegin(), p.rend());
// add in "intersections" with pv and nx edges of current polygon
if (!p.size() || abs(p[0].first - v1[i]) > EPS)
p.insert(p.begin(), ppi(v1[i], pvnx[id][0]));
if (abs(p.back().first-v1[j]) > EPS) p.push_back(ppi(v1[j], pvnx[id][1]));
int last = idx[id][p[0].second] = 0; // Fill in idx and remove duplicates
for (int l=1; l < p.size(); l++) {
if (abs(p[l].first - p[last].first) > EPS) p[++last] = p[l];// new point
idx[id][p[l].second] = last; }
p.resize(last+1);
// Make sure we begin and end with a segment that's in the intersection
if(!pt_in_polygon(v2, (p[last-1].first+p[last].first)/2.L)) p.pop_back();
if (p.size() > 1 && !pt_in_polygon(v2, (p[0].first + p[1].first)/2.L)) {
p.erase(p.begin()); for(int l=0; l<N; l++) idx[id][l]--; } }
swap(v1, v2); }
// BFS over all segments that are in both polygons and find closed loops
bool vis[N][N]; memset(vis, 0, sizeof vis);
for (int k=0; k<2; k++) { // Try both polygons
for (int i=0; i < v1.size(); i++) { // for each edge
int id = k*n[0]+i;
// every 2nd segment is in both polygons
for (int l=0; l+1 < xs[id].size(); l+=2) if (!vis[id][l]) {
pol p; int cid = id, cl = l; // id and index for current segment
do { vis[cid][cl] = vis[cid][cl^1] = true;
p.push_back(xs[cid][cl].first);
int nid = xs[cid][cl^=1].second; // id of edge the other endpoint hits
if (xs[nid].size() < 2) {// no segment to follow, stay on this polygon
nid = pvnx[cid][cl!=0];// cl==0->go to previous edge, else next edge
cl = cl==0 ? xs[nid].size()-1 : 0;
} else cl = idx[nid][cid];
cid = nid;
} while (!vis[cid][cl] && xs[cid].size() > 1);
out.push_back(p); } }
swap(v1, v2); }
return out; }
////////////////////////////////////////////////////////////////////////////////
// Triangle area from three medians
////////////////////////////////////////////////////////////////////////////////
ld triAreaFromMedians(ld ma, ld mb, ld mc) { // Tested UVa 10347
ld x = (ma + mb + mc)/2, a = x * (x - ma) * (x - mb) * (x - mc);
return a < 0.0 ? -1.0 : sqrt(a) * 4.0 / 3.0; }
////////////////////////////////////////////////////////////////////////////////
// Rectangle in rectangle
////////////////////////////////////////////////////////////////////////////////
bool contains(ll W, ll H, ll w, ll h) { // tan(t) = (Hw-Wh)/(Ww-Hh)
if ((w <= W && h <= H) || (w <= H && h <= W)) return true;
if ((W <= w && W <= h) || (H <= w && H <= h)) return false;
ll kc = H*w - W*h, km = w*w - h*h, xc = w * kc, yc = W * km - h * kc;
return xc*xc + yc*yc >= km*km * w*w; }
////////////////////////////////////////////////////////////////////////////////
// Closest pair in n*log(n). Returns the pair. Assumes v.size() >= 2.
////////////////////////////////////////////////////////////////////////////////
pair<pt, pt> closest_pair(vector<pt> v) { // Tested UVa 10245, 11378
sort(v.begin(), v.end(), cmp_lex);
ld best = 1e99; int low = 0; pair<pt, pt> bestpair;
set<pt, bool(*)(const pt&,const pt&)> help(cmp_lex_i);
for(int i = 0; i < v.size(); i++){
while(low < i && (v[i] - v[low]).real() > best) help.erase(v[low++]);
for(__typeof(help.end()) it = help.lower_bound(v[i] - pt(1e99, best));
it != help.end() && (*it - v[i]).imag() < best; it++)
if (abs(*it - v[i]) < best)
best = abs(*it - v[i]), bestpair = make_pair(*it, v[i]);
help.insert(v[i]); }
return bestpair; }
////////////////////////////////////////////////////////////////////////////////
// General Line Segment Sweep (Bentley-Ottmann algorithm)
////////////////////////////////////////////////////////////////////////////////
// O((N + K) log N) intersections, O((N + K) N log N) area, perimeter
// Tested: SPOJ NKMARS, VCIRCLES, POJ 1177
// SHOULD HANDLE: - multiple intersections at a point, collinear segments
// WARNING: Assumes no vertical lines exist. Rotate input such that this is true
// WARNING: completely VERTICAL (in z-direction) POLYGONS if doing 3D
// USAGE: SEGS = 0; add_seg(A, B, polygon_id); line_sweep();
int SEGS; // # of segments
struct seg_t { ld m, c, x2; int id;
inline ld gety(const ld& x) const {
if(m > 1e98) return c; // marker segment
return c + m * x;
} } segarr[MAXN + 1];
bool ycmp_post; pt now; // position of sweep line
struct ycmp { bool operator() (const int& a, const int& b) const {
const ld y1 = segarr[a].gety(now.real()), y2 = segarr[b].gety(now.real());
if (abs(y1 - y2) > EPS) return y1 < y2;
if (abs(segarr[a].m - segarr[b].m) > EPS) {
if (ycmp_post) return segarr[a].m + EPS < segarr[b].m;
return segarr[a].m - EPS > segarr[b].m;
} return a < b; } };
typedef set<int, ycmp> line_set; typedef line_set::iterator line_itr;
line_set state; // y-ordered list of current lines
map<pt, vi, bool(*)(const pt&,const pt&)> events(cmp_lex);//list of new segments
// find intersection of 2 line segments if within range
inline bool intersect(int i, int j, pt& I) {
const seg_t &si = segarr[i], &sj = segarr[j];
if (abs(si.m - sj.m) < EPS) return false; // parallel
ld x = (sj.c - si.c) / (si.m - sj.m);
if (x - EPS > si.x2 || x - EPS > sj.x2) return false;
I = pt(x, si.gety(x)); return true; }
inline void seg_add(int i) {
ycmp_post = true; // for insertion // assert(state.find(i) == state.end());
line_itr curr = state.insert(i).first, prev = curr, next = curr;
--prev; ++next; pt I; // assert(i == *curr);
if(next != state.end()) // bottom exist
if(intersect(*curr, *next, I) && I.real() > now.real()) events[I];
if(curr != state.begin()) // top exist
if(intersect(*prev, *curr, I) && I.real() > now.real()) events[I]; }
// delete FIRST segments with (xnow, y), returns segment id or -1 if fail
inline int seg_del() {
ycmp_post = false; // for deletion
segarr[MAXN].m = 1e99; segarr[MAXN].c = now.imag() - EPS;
line_itr curr = state.lower_bound(MAXN);
if (curr == state.end()) return -1;
const int i = *curr;
if (segarr[i].gety(now.real()) - now.imag() > EPS) return -1;
line_itr prev = curr, next = curr; --prev; ++next; pt I;
if (curr != state.begin() && next != state.end())
if (intersect(*prev, *next, I) && I.real() > now.real()) events[I];
state.erase(curr);
return i; }
// USER DEFINED: calculate the area when there are these active polygons
// A, B, C, D is a ccw quadrilateral that is inside each of the active polygons
ld calc_area(const set<int> &active, pt A, pt B, pt C, pt D);
inline ld find_area(const ld& xprev) {
int a = -1, b; set<int> active; ld area = 0;
for(line_itr it = state.begin(); it != state.end(); ++it) { b = *it;
if(a == -1) { active.insert(segarr[b].id); a = b; continue; } // first seg
const seg_t &sa = segarr[a], &sb = segarr[b]; // counter-clockwise
pt A(xprev, sa.gety(xprev)), B(now.real(), sa.gety(now.real())),
C(now.real(), sb.gety(now.real())), D(xprev, sb.gety(xprev));
area += calc_area(active, A, B, C, D);
if (active.count(segarr[b].id)) active.erase(segarr[b].id);
else active.insert(segarr[b].id);
a = b; } return area; }
ld line_sweep() { // O( (N + K) log N ), K = # intersects
pt prev; ld area = 0;
while(!events.empty()) {
now = events.begin()->first; vi U;
swap(U, events.begin()->second); // STL efficient
events.erase(events.begin());
if(abs(prev.real() - now.real()) > EPS) {
// USER-DEFINED: area += find_area(prev.real());
}
while(true) { int i = seg_del(); if(i == -1) break; U.push_back(i); }
// USER-DEFINED: U contains ids of intersecting segments at x=now.real()
// for(int i = 0; i < U.size(); ++i)
// for(int j = i + 1; j < U.size(); ++j)
// report_intersection(U[i], U[j]);
for(vi::iterator it = U.begin(); it != U.end(); ++it)
if(segarr[*it].x2 - EPS > now.real()) seg_add(*it);
prev = now; } // assert(state.empty());
return area; }
// this function is for initialization; id denotes which polygon
void add_seg(pt A, pt B, const int& id) {
if(cmp_lex(B, A)) swap(A, B); events[A].push_back(SEGS); events[B];
segarr[SEGS].m = (A.imag() - B.imag()) / (A.real() - B.real());
segarr[SEGS].c = A.imag() - segarr[SEGS].m * A.real();
segarr[SEGS].x2 = B.real(); segarr[SEGS].id = id; ++SEGS; }
////////////////////////////////////////////////////////////////////////////////
// Circle-circle intersection (TESTED UVa 453)
////////////////////////////////////////////////////////////////////////////////
// Return number of intersections. Circles must not be identical.
int cc_inter(pt p1, ld r1, pt p2, ld r2, pt &i1, pt &i2) {
ld dq=norm(p1-p2), rq=r1*r1-r2*r2; pt c=(p1+p2)*0.5L + (p2-p1)*rq*0.5L/dq;
ld dt=2.0*dq*(r1*r1+r2*r2)-dq*dq-rq*rq;
if(dt < -EPS) return 0; if(dt < EPS) { i1=i2=c; return 1; }
dt=sqrt(dt)*0.5/dq; i1=c+(p2-p1)*pt(0,1)*dt; i2=c-(p2-p1)*pt(0,1)*dt;
return 2; }
////////////////////////////////////////////////////////////////////////////////
// Area of intersection of 2 circles (UNTESTED)
////////////////////////////////////////////////////////////////////////////////
ld cc_area(pt p1, ld r1, pt p2, ld r2) { if(r2 < r1) swap(p1, p2), swap(r1, r2);
ld d = abs(p2 - p1), dA, dB, tx, ty;
if (d + r1 < r2 + EPS) return r1*r1*PI; if (d >= r1 + r2) return 0;
dA = tx = (d*d + r1*r1 - r2*r2)/d/2, dB = d-dA, ty = sqrt(r1*r1-tx*tx);
return r1*r1*acos(dA/r1) - dA*sqrt(r1*r1-dA*dA)
+ r2*r2*acos(dB/r2) - dB*sqrt(r2*r2-dB*dB); }
////////////////////////////////////////////////////////////////////////////////
// Circles tangents
////////////////////////////////////////////////////////////////////////////////
// Given two circles, find all tangent angles.
// returns four angles for the first circle.
inline vector<ld> get_tangents(pt p1, ld r1, pt p2, ld r2) {
pt v = p2 - p1; // vector from p1 to p2
ld d = abs(v); // distance between centers
ld a = acos((r1 - r2)/d); // outer tangent's angle relative to c1 -> c2
ld b = acos((r1 + r2)/d); // inner .......
ld s = atan2(v.imag(), v.real());// basis angle relative to the circle1
vector <ld> out; out.push_back(s + a), out.push_back(s - a);
out.push_back(s + b), out.push_back(s - b); return out; }
ld good_angle(ld a){ return fmod(fmod(a, 2*PI) + 2*PI, 2*PI); }
ld ang_dist(ld a1, ld a2){
ld d = fmod(abs(a1 - a2), 2*PI); return min(d, 2*PI - d); }
pair<pt, pt> circle_tangent(ld r1, ld r2, ld d, int k) { // use the fcn below
ld dr = (k & 2) ? (-r1-r2) : (r2-r1); ld t = asin(dr / d);
pt p1=polar(r1, PI/2+t), p2=polar(r2, PI/2+t); if(k&2) p2*=-1; p2+=pt(d,0);
if(k&1){ p1=pt(p1.real(),-p1.imag()); p2=pt(p2.real(),-p2.imag()); }
return make_pair(p1, p2); }
// tested 2008wf conveyor; tangent of 2 circles; CAUTION: INTERSECTION IS BAD
// k=0 top-top, k=1 bot-bot, k=2 top-bot, k=3 bot-top. Also works for points.
pair<pt, pt> circle_tangent(pt p1, ld r1, pt p2, ld r2, int k) {
// translate/rotate so c1 at (0,0), c2 at x-axis
pt d = p2-p1; pair<pt, pt> p = circle_tangent(r1, r2, abs(d), k); d /= abs(d);
p.first *= d; p.second *= d; p.first += p1; p.second += p1; return p; }
////////////////////////////////////////////////////////////////////////////////
// Circular Arc Length (UNTESTED)
////////////////////////////////////////////////////////////////////////////////
ld arc_length(pt p, ld r, pt p1, pt p2, bool ccw) {
ld a1=arg(p1-p), a2=arg(p2-p); return fmod((ccw?a2-a1:a1-a2)+2*PI, 2*PI)*r; }
////////////////////////////////////////////////////////////////////////////////
// Circular boundary traversal
////////////////////////////////////////////////////////////////////////////////
int vis[128], done[128][128], ind[128][128], sz[128], cnt, n;
pt c[128];
ld out[128][128], in[128][128], r[128], x, y;
void dfs(int now){ if(vis[now]) return;
vis[now] = 1; for(int i = 0; i < n; i++)
if(!vis[i] && abs(c[now] - c[i]) < r[now] + r[i]) dfs(i);}
int main(){
int t; cin >> t;
while(t-- && cin >> n){
for(int i = 0; i < n && cin >> x >> y >> r[i]; i++) c[i] = pt(x, y);
memset(vis, 0, sizeof(vis)), memset(sz, 0, sizeof(sz));
memset(done, 0, sizeof(done));
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
ld d = abs(c[i] - c[j]);
if(i != j && abs(r[i] - r[j]) < d && d < r[i] + r[j]){
pt v = c[j] - c[i];
ld cosa = (r[i]*r[i] + d*d - r[j]*r[j])/(2*r[i]*d);
ld sina = sqrt(1 - cosa*cosa);
v *= pt(cosa, -sina); // v is direction to intersection
v /= abs(v), v *= r[i];
pt inter = v + c[i]; // now inter is the intersection pt;
bool good = true;
for(int k = 0; k < n; k++) good &= (abs(inter - c[k]) + EPS > r[k]);
if(good){ // only if not inside a circle
out[i][sz[i]] = atan2(v.imag(), v.real());
if(out[i][sz[i]] < 0) out[i][sz[i]] += 2*PI;
ind[i][sz[i]] = j;
v = c[i] - c[j];
cosa = (r[j]*r[j] + d*d - r[i]*r[i])/(2*r[j]*d);
sina = sqrt(1 - cosa*cosa);
v *= pt(cosa, sina); // the other turn
in[i][sz[i]++] = atan2(v.imag(), v.real());
if(in[i][sz[i] - 1] < 0) in[i][sz[i] - 1] += 2*PI; } } }
cnt = 1;
for(int i = 0; i < n; i++){
if(sz[i] && !vis[i]) cnt--, dfs(i);
for(int j = 0; j < sz[i]; j++)
if(!done[i][j]){
cnt++;
ld angle = in[i][j] - EPS;
int now = ind[i][j];
while(true){
ld best = 1e99;
int p = -1;
for(int k = 0; k < sz[now]; k++){
ld dif = out[now][k] - angle; if(dif < 0) dif += PI*2;
if(dif < best) best = dif, p = k;
}
if(done[now][p]) break;
done[now][p] = 1;
angle = in[now][p] - EPS;
now = ind[now][p]; } } }
cout << cnt - 1 << endl; } } // number of components??
////////////////////////////////////////////////////////////////////////////////
// Circular obstacles visibility graph construction (N^3 ?)
////////////////////////////////////////////////////////////////////////////////
vector < vector < pair < int, ld > > >
build_graph(const vector < pair < pt, ld > > &data){
vector < ld > angle(4*data.size()*data.size(), 0), temp;
for(int i = 0; i < (int)data.size(); i++)
for(int j = 0; j < (int)data.size(); j++)
if(i != j){
temp = get_tangents(data[i].first, data[i].second,
data[j].first, data[j].second);
for(int k = 0; k < 4; k++)
angle[4*i*data.size() + 4*j + k] = temp[k]; } // i -> j
vector < pt > pnts;
for(int i = 0; i < (int)angle.size(); i++){
pt p = data[i/(4*data.size())].first;
ld r = data[i/(4*data.size())].second;
ld a = angle[i];
pnts.push_back(p + r*pt(cos(a), sin(a))); }
vector < vector < pair < int, ld > > > out(pnts.size());
// do the distances between pts on same circle
for(int i = 0; i < (int)angle.size(); i += 4*data.size()){ // for each circle
int id = i/(4*data.size()); // circle #
vector < pair < ld, int > > help;
for(int j = 0; j < (int)data.size()*4; j++)
help.push_back(make_pair(good_angle(angle[i + j]), i + j));
sort(help.begin(), help.end());
for(int a = help.size() - 1, b = 0; b < (int)help.size(); a = b++)
out[help[a].second].push_back(make_pair(
help[b].second, data[id].second*ang_dist(help[a].first, help[b].first))),
out[help[b].second].push_back(make_pair(
help[a].second,data[id].second*ang_dist(help[a].first, help[b].first)));}
// do the distances between different circles, whenever possible...
for(int i = 0; i < (int)data.size(); i++)
for(int j = i + 1; j < (int)data.size(); j++)
for(int k = 0; k < 4; k++){
int ii = 4*i*data.size() + 4*j + k;
int jj = 4*j*data.size() + 4*i + (k^1^((k&2) >> 1));
bool good = true; // check is line if far enough from each circle
for(int kk = 0; kk < (int)data.size() && good; kk++)
good &= (lsp_dist(pnts[ii], pnts[jj], data[kk].first) + EPS >=
data[kk].second);
if(good){
out[ii].push_back(make_pair(jj, abs(pnts[ii] - pnts[jj])));
out[jj].push_back(make_pair(ii, abs(pnts[ii] - pnts[jj]))); } }
return out; }
////////////////////////////////////////////////////////////////////////////////
// 2D convex hull (TESTED SPOJ BSHEEP, UVA 11096)
////////////////////////////////////////////////////////////////////////////////
// Works with duplicate points but no guarantees on which point will be used
pol chull(pol p) { // change <= 0 to < 0 to find collinear convex hull points
sort(p.begin(), p.end(), cmp_lex_i); int top=0, bot=1; pol ch(2*p.size());
for (int i=0, d=1; i < p.size() && i >= 0; i += d) {
while (top > bot && cp(ch[top-1]-ch[top-2], p[i]-ch[top-2]) <= 0) top--;
ch[top++] = p[i]; if (i == p.size()-1) d = -1, bot = top;
} ch.resize(max(1, top-1)); return ch; }
////////////////////////////////////////////////////////////////////////////////
// Orthogonal Convex Hull (all edges are parallel to x or y axis)
////////////////////////////////////////////////////////////////////////////////
vpii orthinc(const vpii& points, bool up) {
// lexicographical sort
vpii chain; chain.pb(points.front()); int maxy = points.front().second;
for (int i = 1; i < points.size(); ++i) {
if (up) { if(points[i].second <= maxy) continue; }
else { if (points[i].second >= maxy) continue; }
if (points[i].first != chain.back().first)
chain.push_back(pii(points[i].first, maxy));
else chain.pop_back();
chain.push_back(points[i]); maxy = points[i].second; } return chain; }
// runs orthogonal convex hull; point ordering may be modified
vpii orthogonal_convex_hull(vpii& points) {
vpii hull; sort(points.begin(), points.end());
vpii h1 = orthinc(points, true), h2 = orthinc(points, false);
reverse(points.begin(), points.end());
vpii h3 = orthinc(points, true), h4 = orthinc(points, false);
hull.insert(hull.end(), h1.begin(), h1.end()); // use swap
hull.insert(hull.end(), h3.rbegin(), h3.rend());
hull.insert(hull.end(), h4.begin(), h4.end());
hull.insert(hull.end(), h2.rbegin(), h2.rend());
return hull; }
////////////////////////////////////////////////////////////////////////////////
// Convex hull of circles (Tested on UVa)
////////////////////////////////////////////////////////////////////////////////
const ld far = 1e10; // can't be too big or precision error
pt center[MAXN]; ld radius[MAXN]; int V; // # of circles
// true if circle1 is in circle2
bool c_in_c(pt c1, ld r1, pt c2, ld r2) {
ld d = abs(c1 - c2); return r1 - EPS <= r2 && d + r1 - EPS <= r2; }
// convex hull of circles
ld solve() { // find lowest point; and biggest circle
pt lowest(far, far);
// need 2nd point because we may touch the first circle TWICE
int first = -1, second = -1;
for (int i = 0; i < V; ++i) { pt low = center[i] - pt(0, radius[i]);
if (cmp_lex_i(low, lowest)) { lowest = low; first = i; }
else if (abs(low - lowest) < EPS &&
c_in_c(center[first], radius[first], center[i], radius[i])) first=i; }
ld perim = 0; pt left(-far, lowest.imag()), right(far, lowest.imag());
pt A = left, B = lowest; int i = first;
while (true) { // tangents are A-B and C-D, B and C lies on the same circle
pt C = A, D = B; int next = i; ld next_angle = 1e9;
for (int j = 0; j < V; ++j) { if (i == j) continue;
// check if inside current circle
if(c_in_c(center[j], radius[j], center[i], radius[i])) continue;
// bot-bot since we are doing counter clockwise
// tangent.first lies on first circle etc.
seg t = circle_tangent(center[i],radius[i],center[j],radius[j],1);
ld angle = atan2(cp(B-A, t.second-t.first), dp(B-A, t.second-t.first));
if (angle < -EPS) angle += PI * 2;
if (angle + EPS < next_angle) { next_angle = angle; next = j;
C = t.first; D = t.second; } }
if (next == i) { perim += radius[i] * PI * 2; break; }
if (i == first && second == -1) second = next;
else if (i == first && second == next) { // done, calculate last angle
perim += radius[i] * next_angle; break; }
else perim += radius[i] * next_angle;
perim += abs(C - D); A = C; B = D; i = next; } return perim; }
////////////////////////////////////////////////////////////////////////////////
// General 3D geometry
////////////////////////////////////////////////////////////////////////////////
struct p3d{ ld x,y,z; p3d(ld xx=0, ld yy=0, ld zz=0) : x(xx), y(yy), z(zz) {} };
ld abs(const p3d &v){ return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); }
ostream &operator<<(ostream &os, const p3d &p){
return os << "(" << p.x << "," << p.y << "," << p.z << ")"; }
p3d operator+(const p3d&a,const p3d&b){ return p3d(a.x+b.x,a.y+b.y,a.z+b.z); }
p3d operator-(const p3d&a,const p3d&b){ return p3d(a.x-b.x,a.y-b.y,a.z-b.z); }
p3d operator*(const ld &s, const p3d &v){ return p3d(s*v.x, s*v.y, s*v.z); }
p3d operator/(const p3d&v, const ld &s){ return p3d(v.x/s, v.y/s, v.z/s); }
inline ld dot(const p3d &a, const p3d &b){ return a.x*b.x + a.y*b.y + a.z*b.z; }
inline p3d cross(const p3d &a, const p3d &b){
return p3d(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x); }
inline ld dist(const p3d &s, const p3d &p) {
return (p.x-s.x)*(p.x-s.x) + (p.y-s.y)*(p.y-s.y) + (p.z-s.z)*(p.z-s.z); }
// plane/line intersection. p - pt on plane, n - normal, a1 -> a2 : line
inline p3d pl_inter(const p3d &p, const p3d &n, const p3d &a1, const p3d &a2){
return a1 + dot(p - a1, n)/dot(n, a2 - a1)*(a2 - a1); }
////////////////////////////////////////////////////////////////////////////////
// CCW 3D rotation about arbitrary axis; tested on 2009 pacnw D but pray anyway
////////////////////////////////////////////////////////////////////////////////
inline p3d rotate(const p3d& p /*pt*/, const p3d& u /*axis*/, const ld& angle) {
ld c = cos(angle), s = sin(angle), t = 1 - cos(angle); return p3d(
p.x*(t*u.x*u.x + c) + p.y*(t*u.x*u.y - s*u.z) + p.z*(t*u.x*u.z + s*u.y),
p.x*(t*u.x*u.y + s*u.z) + p.y*(t*u.y*u.y + c) + p.z*(t*u.y*u.z - s*u.x),
p.x*(t*u.x*u.z - s*u.y) + p.y*(t*u.y*u.z + s*u.x) + p.z*(t*u.z*u.z + c)); }
////////////////////////////////////////////////////////////////////////////////
// Slow 3D convex hull
////////////////////////////////////////////////////////////////////////////////
struct face{int p1, p2, p3; face(int a, int b, int c) {p1=a, p2=b, p3=c;}};
int t, n; p3d data[1024];
bool above(const face &f, const p3d p){
p3d normal = cross(data[f.p2] - data[f.p1], data[f.p3] - data[f.p2]);
return dot(normal, p - data[f.p1]) > EPS; }
ld area(const face &f){
return abs(cross(data[f.p2] - data[f.p1], data[f.p3] - data[f.p1])); }
ld volume(const face &f){
p3d normal = cross(data[f.p2] - data[f.p1], data[f.p3] - data[f.p2]);
normal = normal / abs(normal);
ld h = dot(normal, data[f.p1]);
return area(f)*h/6; }
int main(){ // outputs area/volume of the CH in 3D
cin >> t;
while(t-- && cin >> n){
for(int i = 0; i < n; i++) cin >> data[i].x >> data[i].y >> data[i].z;
for(int i = n - 1; i >= 0; i--) data[i] = data[i] - data[0];
for(int i = 1; i < n; i++)
if(abs(data[i] - data[0]) > EPS){ swap(data[i], data[1]); break; }
for(int i = 2; i < n; i++)
if(abs(cross(data[1] - data[0], data[i] - data[0])) > EPS){
swap(data[i], data[2]); break; }
for(int i = 3; i < n; i++){
p3d normal = cross(data[1] - data[0], data[2] - data[0]);
if(abs(dot(normal, data[0] - data[i])) > EPS){
swap(data[i], data[3]); break; } }
vector < face > f; f.push_back(face(0, 1, 2)); f.push_back(face(2, 1, 0));
for(int i = 3; i < n; i++){
vector < face > next; set < int > edge;
for(int j = 0; j < (int)f.size(); j++) // remove the faces
if(above(f[j], data[i])){
edge.insert((f[j].p1 << 10) | f[j].p2);
edge.insert((f[j].p2 << 10) | f[j].p3);
edge.insert((f[j].p3 << 10) | f[j].p1);
}else next.push_back(f[j]);
for(__typeof(edge.begin()) it = edge.begin(); it != edge.end(); it++)
if(!edge.count( ((*it & 1023) << 10) | (*it >> 10) ) )
next.push_back(face(*it >> 10, *it & 1023, i));
f = next; }
ld ar = 0; ld vo = 0;
for(int i = 0; i < (int)f.size(); i++) ar += area(f[i]), vo += volume(f[i]);
cout.setf(ios::fixed), cout.precision(4);
cout << ar/2 << " " << vo << endl; }
return 0; }
////////////////////////////////////////////////////////////////////////////////
// Faster 3D convex hull
////////////////////////////////////////////////////////////////////////////////
typedef list<pair<face, si> > face_list;
ld dist(const face &f, const p3d p) {p3d normal = cross(data[f.p2] - data[f.p1],
data[f.p3] - data[f.p2]); return dot(normal, p - data[f.p1]);}
vector<face> faces; vector<bool> gone; // if this face is deleted
vector<vi> vis; // visible points
map<pii, int> adj; // adjacent faces
void add_face(const face& f) {
int i=faces.size();faces.push_back(f);vis.push_back(vi());gone.push_back(false);
adj[pii(f.p1, f.p2)] = i; adj[pii(f.p2, f.p3)] = i; adj[pii(f.p3, f.p1)] = i; }
void del_face(int i) { gone[i] = true; vis[i].clear(); }
void partition(int off, const vi& p) {
for(int i = 0; i < p.size(); ++i) for(int f = off; f < faces.size(); ++f) {
if(gone[f]) continue;
if(above(faces[f], data[p[i]])) { vis[f].push_back(p[i]); break; } } }
void convex_hull_clean_input() { random_shuffle(data, data + N);
for (int i = N - 1; i >= 0; i--) data[i] = data[i] - data[0];
for (int i = 1; i < N; i++)
if (abs(data[i]-data[0]) > EPS) {swap(data[i], data[1]); break;}
for (int i = 2; i < N; i++)
if (abs(cross(data[1] - data[0], data[i] - data[0])) > EPS){
swap(data[i], data[2]); break; }
for (int i = 3; i < N; i++) {
p3d normal = cross(data[1] - data[0], data[2] - data[0]);
if (abs(dot(normal, data[0] - data[i])) > EPS) {
swap(data[i], data[3]); break; } } }
vector<face> quick_hull() {
convex_hull_clean_input();
faces.clear(); gone.clear(); vis.clear(); adj.clear();
add_face(face(0, 1, 2)); add_face(face(2, 1, 0));
vi points; vector<face> ret;
// handle coplanar starting points
for(int i = 3; i < N; ++i) { vis[0].push_back(i); vis[1].push_back(i); }
for(int f = 0; f < faces.size(); ++f) {
if(vis[f].size() == 0) { continue; } if(gone[f]) continue;
ld maxdist = EPS; int p = -1; // select furthest point
for(int i = 0; i < vis[f].size(); ++i) {
ld z = dist(faces[f], data[vis[f][i]]);
if(z > maxdist) { maxdist = z; p = vis[f][i]; } }
points.clear(); set<pii> edges; si done; done.insert(f);
queue<int> q; q.push(f);
while(!q.empty()) { int n = q.front(); q.pop(); const face& ff = faces[n];
if(!above(ff, data[p])) continue;
for(int v = 0; v < vis[n].size(); ++v) {
if(vis[n][v] != p) points.push_back(vis[n][v]); }
edges.insert(pii(ff.p1, ff.p2)); edges.insert(pii(ff.p2, ff.p3));
edges.insert(pii(ff.p3, ff.p1)); si neib;
neib.insert(adj[pii(ff.p1, ff.p3)]); neib.insert(adj[pii(ff.p2, ff.p1)]);
neib.insert(adj[pii(ff.p3, ff.p2)]); del_face(n);
for(si::iterator s = neib.begin(); s != neib.end(); ++s) {
if(done.find(*s) != done.end()) continue; if(gone[*s]) continue;
done.insert(*s); q.push(*s); } }
int off = faces.size();
for(set<pii>::iterator it = edges.begin(); it != edges.end(); it++) {
if(!edges.count(pii(it->second, it->first))) {
add_face(face(it->first, it->second, p)); } }
partition(off, points); }
for(int f = 0; f < faces.size(); ++f) {if(!gone[f]) ret.push_back(faces[f]); }
return ret; }
////////////////////////////////////////////////////////////////////////////////
// Arbitrary-Dimension Minimum Enclosing Ball TESTED UVa 10005(2D), 10095(3D)
////////////////////////////////////////////////////////////////////////////////
// adapted from http://www.inf.ethz.ch/personal/gaertner/miniball.html
// Usage:
// 0. pray your soul remains intact after using black magic
// 1. create pt p(D) and set values in p[i] - DON'T FORGET THE D IN pt p(D)
// 2. add pt to Miniball mb with mb.add(p)
// 3. after adding all pts call mb.build() - WARNING: CALL THIS ONLY ONCE
// 4. coordinates of centre are in mb.c_c[d]
// 5. *SQUARED* radius of circle/ball/thing is in mb.c_r2
#define SQR(x) ((x)*(x))
const int D = 3; const ld EPS = 1e-9;
typedef vector<ld> pt;
typedef list<pt>::iterator It;
struct Miniball {
list<pt> L; It end; int m; pt c_c; ld c_r2;
vector<pt> c; pt q0; vector<ld> r2, z, f; vector<vector<ld> > v, a;
Miniball() : m(0), v(D+1,vector<ld>(D)), a(D+1,vector<ld>(D)), c(D+1,pt(D,0)),
q0(D), r2(D+1), z(D+1), f(D+1), end(L.begin()) { c_c=c[0], c_r2=-1; }
void add(pt &p) { L.push_back(p); }
void move_to_front(It i) { m--; if (end==i) end++; L.splice(L.begin(),L,i); }
void mtf_mb(It i) { end=L.begin(); if (m==D+1) return;
for (It k=L.begin(),j;(j=k++)!=i;) { ld e = get_e(j);
if (e > 0 && push(*j)) mtf_mb(j), move_to_front(j); } }
void pivot_mb(It i) {
It t=++L.begin(), pivot; mtf_mb(t); ld max_e, old_r2=-1;
do { if((max_e=max_excess(t,i,pivot)) > 0) {
if ((t=end)==pivot) ++t;
old_r2=c_r2; push(*pivot); mtf_mb(end); move_to_front(pivot); }
} while (max_e > 0 && c_r2 > old_r2); }
ld max_excess(It j,It i,It& pivot) { ld max_e=0,e;
for (; j!=i;++j) if ((e=get_e(j)) > max_e) max_e=e,pivot=j; return max_e; }
ld get_e(It j) { ld e=-c_r2; for (int i=0;i<D;++i) e+=SQR((*j)[i]-c_c[i]);
return e; }
bool push(const pt& p) { int i, j; if (!m) c[0]=q0=p, r2[0]=0; else {
for (i=0;i<D;++i) v[m][i]=p[i]-q0[i];
for (i=1;i<m;++i) { a[m][i]=0;
for (j=0;j<D;++j) a[m][i]+=v[i][j]*v[m][j];
a[m][i]*=(2/z[i]); }
for (i=1;i<m;++i) for (j=0;j<D;++j) v[m][j]-=a[m][i]*v[i][j];
z[m]=0; for (j=0;j<D;++j) z[m]+=2*SQR(v[m][j]);
if (z[m] < c_r2*EPS) return false;
ld e=-r2[m-1]; for (i=0;i<D;++i) e+=SQR(p[i]-c[m-1][i]);
f[m]=e/z[m];
for (i=0;i<D;++i) c[m][i]=c[m-1][i]+f[m]*v[m][i];
r2[m]=r2[m-1]+e*f[m]/2;
} c_c=c[m]; c_r2=r2[m]; m++; return true; }
void build(){ pivot_mb(L.end()); } };
////////////////////////////////////////////////////////////////////////////////
// Rational Numbers
////////////////////////////////////////////////////////////////////////////////
struct rational_t { ll nu, de;
rational_t(const ll &n = 0, const ll &d = 1) {
ll g = gcd(abs(n), abs(d)); nu = n / g; de = d / g;
if (de < 0) { nu = -nu; de = -de; }
}
rational_t operator+(const rational_t& b) const
{ return rational_t( nu*b.de+de*b.nu, de*b.de ); }
rational_t operator-(const rational_t& b) const
{ return rational_t( nu*b.de-de*b.nu, de*b.de ); }
rational_t operator-() { return rational_t(-nu, de); }
rational_t operator*(const rational_t& b) const
{ return rational_t( nu*b.nu, de*b.de ); }
rational_t operator/(const rational_t& b) const
{ return rational_t( nu*b.de, de*b.nu ); }
bool operator == (const rational_t & b) const {return nu * b.de == b.nu * de;}
bool operator == (const int &k) const { return nu == k * de; }
bool operator < (const rational_t& b) const { return nu * b.de < b.nu * de; }
};
////////////////////////////////////////////////////////////////////////////////
// Extended GCD
////////////////////////////////////////////////////////////////////////////////
// Find x,y such that ax + by = d = gcd(a,b)
// * a^-1 (mod m): if (egcd(a,m,x,y) == 1) return (x+m)%m; else ERROR;
ll egcd(ll a, ll b, ll& x, ll &y) {
if (!b) {x = 1; y = 0; return a;}//to ensure d>=0: x=sgn(a);y=0;return abs(a);
ll d = egcd(b, a%b, y, x); y -= x * (a/b);
return d; }
////////////////////////////////////////////////////////////////////////////////
// Extended GCD in canonical form
////////////////////////////////////////////////////////////////////////////////
// Assuming a != 0, find smallest y >= 0 such that ax + by = c (if possible)
bool canon_egcd(ll a, ll b, ll c, ll& x, ll& y) {
ll d = egcd(a, b, x, y), z = abs(a/d);
if (c%d) return false;
y = (y*(c/d)%z + z)%z, x = (c - b*y)/a;
return true; }
////////////////////////////////////////////////////////////////////////////////
// Chinese remainder theorem
////////////////////////////////////////////////////////////////////////////////
// z % m1 == a1, z % m2 == a2, 0 <= a1 < m1, 0 <= a2 < m2
// Return true and 0 <= A < M if possible, false otherwise
bool chin_rem(ll a1, ll m1, ll a2, ll m2, ll& A, ll& M) {
ll X1, X2, d = egcd(m1, m2, X1, X2);
if (a1 % d != a2 % d) return false;
M = m1/d*m2, A = ((X1*m1%M*(a2/d) + X2*m2%M*(a1/d) + a1%d)%M + M)%M;
return true; }
////////////////////////////////////////////////////////////////////////////////
// Linear Diophantine Equation Solver
////////////////////////////////////////////////////////////////////////////////
// Linear Diophantine Equation Solver for any number of variables
// Author: Adam Beacham & Howard Cheng
// Given the linear equation with integer coefficients a[i]:
// a[0]*x_0 + a[1]*x_1 + . . . + a[n-1]*x_n-1 = c
// It is assumed that no coefficient is 0.
// Determines whether integer solutions exist. If they do,
// provides a specific solution for the variables in the array sol.
// (sol is viewed as an n-dimensional vector).
// Then bas[0], bas[1], . . ., bas[n-1] are basis vectors for the integer
// solutions for the homogeneous equation:
// a[0]*x_0 + a[1]*x_1 + . . . + a[n-1]*x_n-1 = 0
// (Each bas[i] is an n-vector).
// Thus, all solutions are given by:
// (x_0, . . ., x_n-1) = sol + t_0*bas[0] + . . . + t_{n-1}*bas[n-1]
// where t_0, . . ., t_{n-1} are arbitrary integers.
ll gcd_solve(ll a[MAX_VAR], int numV, ll sol[MAX_VAR],
ll bas[MAX_VAR-1][MAX_VAR]){
ll ret, d, v, i;
if( numV == 2 ) {
ret = egcd(a[0],a[1],sol[0],sol[1]);
bas[0][0] = a[1]/ret;
bas[0][1] = -a[0]/ret;
} else if( numV > 2 ) {
d = gcd_solve(a,numV-1,sol,bas);
ret = egcd(d,a[numV-1],v,sol[numV-1]);
for( i=0; i<numV-1; i++ ) {
bas[numV-2][i] = a[numV-1]/ret * sol[i];
sol[i] *= v;
}
bas[numV-2][numV-1] = -d/ret;
} return ret; }
bool diophantine(ll a[MAX_VAR], int numV, ll c, ll sol[MAX_VAR],
ll bas[MAX_VAR-1][MAX_VAR]){
assert(numV > 1); int i,j,d,q;
for( i=0; i<numV; i++ ) assert( a[i] != 0 );
for( i=0; i<numV-1; i++ ) for( j=0; j<numV; j++ )
bas[i][j] = 0;
d = gcd_solve(a,numV,sol,bas);
if( c % d == 0 ) {
q = c/d;
for( i=0; i<numV; i++ ) sol[i] *= q;
return true;
} return false; }
////////////////////////////////////////////////////////////////////////////////
// Legendre symbol
////////////////////////////////////////////////////////////////////////////////
// There exists x, s.t. x^2=a(mod p) (p prime) iff L(a, p)>=0
// note L(a, p) * L(b, p) = L(a*b, p)
inline int legendre( int a, int p ) {
return (a%p)?(modpow(a, (p-1)/2, p ) == 1 ? 1 : -1):0;}
////////////////////////////////////////////////////////////////////////////////
// Modular Exponentiation
////////////////////////////////////////////////////////////////////////////////
ll modpow(ll a, ll p, ll M) { // assumes M > 1
ll r; for (r = 1; p; a = (a*a)%M, p /= 2) if (p%2) r = (r*a)%M; return r; }
////////////////////////////////////////////////////////////////////////////////
// Discrete Log
////////////////////////////////////////////////////////////////////////////////
// returns smallest x such that a^x == b (mod M) or -1 if
// no such x exists. O(sqrt(M)*log(sqrt(M))), faster if using hashing.
struct HLL{size_t operator()(const ll a)const{return(int)(a^(a>>32));}}; // hash
ll modlog(ll a, ll b, ll M) {
ll s = (ll)sqrt(M), p, i;
while (s*s < M) ++s;
map<ll, ll> H;
for (i = 0, p = 1; i < s; ++i, p = (p*a)%M)
if (!H.count(p))
H[p] = i;
for (i = 0, p = modpow(a, M-1-s, M); i < s; ++i, b = (b*p)%M)
if (H.count(b))
return i*s+H[b];
return -1;}
////////////////////////////////////////////////////////////////////////////////
// Polynomial GCD
////////////////////////////////////////////////////////////////////////////////
// returns a, b such that ax = by in the field we're talking about
inline void solve(int x, int y, int& a, int& b);
// polynomial coefficients are in decreasing order of exponents
inline vi operator % (const vi& p, const vi& q) {
vi copy = p; int diff = (int)p.size() - (int)q.size(), a, b;
for (int i = 0; i <= diff; ++i) { solve(q[0], copy[i], a, b);
for (int j = 0; j < p.size(); ++j) copy[j] *= b;
for (int j = 0; j < q.size(); ++j) copy[i+j] -= a*q[j]; }
return remove_leading_zero(copy); } // 00002342 -> 2343; 0 -> 0
vi gcd(const vi &p, const vi &q){return q.size()==1 && !q[0] ? p : gcd(q,p%q);}
////////////////////////////////////////////////////////////////////////////////
// Polynomial Root
////////////////////////////////////////////////////////////////////////////////
pol ruffini(const pol &p, pt r){ // returns p(x)/(x-r)
int deg = (int)p.size()-1; pol ret(deg); ret[deg-1] = p[deg];
for (int i = deg-2; i >= 0; --i) ret[i] = p[i+1] + ret[i+1]*r;
return ret; } // if want remainder: p[0] + ret[0]*r
pol poly_roots(pol poly) { // poly[i] is the coefficient for x^i
const int NUM_ITR = 25; // change as needed
const ld tol = 1E-12; // change as needed
pol ret; pt init_guess = 1; // initial guess
while (poly.size() > 1) {
int deg = poly.size() - 1; pt curr = init_guess, val, fd, sd;
for (int itr = 0; itr <= NUM_ITR; itr++) { val = fd = sd = 0;
for (int i = poly.size()-1; i >= 0; i--) {
val *= curr; val += poly[i];
if (i > 0) fd *= curr; fd += ((ld) i) * poly[i];
if (i > 1) sd *= curr; sd += ((ld) (i * (i-1))) * poly[i]; }
if (abs(val) < tol) break;
pt g = fd/val; pt h = g*g - sd/val;
pt disc = ((ld)(deg - 1))*(((ld) deg)*h-g*g);
pt dp = g + sqrt(disc); pt dn = g - sqrt(disc);
if (abs(dn)<abs(dp)) curr-=((ld) deg)/dp; else curr-=((ld) deg)/dn; }
if (abs(val) < tol){ ret.pb(curr); poly = ruffini(poly,curr); }
else init_guess *= -2; } // change as needed
return ret; }
////////////////////////////////////////////////////////////////////////////////
// Pythagorean triples
////////////////////////////////////////////////////////////////////////////////
typedef struct { int a, b, c; } ptrip;
int gen_triples(int n, ptrip *res) {
int a, b, p, q, cnt = 0;
for (p = 2; p*p < n; p++) {
for (q = 1+p%2; q < p && p*p+q*q < n; q += 2) {
if (gcd(p,q)!=1) continue;
a = p*p-q*q;
b = 2*p*q;
if (a < b) { res[cnt].a = a; res[cnt].b = b; }
else { res[cnt].a = b; res[cnt].b = a; }
res[cnt++].c = p*p+q*q;
} } return cnt; }
////////////////////////////////////////////////////////////////////////////////
// Farey Sequences
////////////////////////////////////////////////////////////////////////////////
vpii farey(int n){
vpii res; int a = 0, b = 1, c = 1, d = n, k; res.push_back(make_pair(0,1));
while(c<n){ k = (n+b)/d,swap(a,c),swap(b,d),c = k*a-c,d = k*b-d;
res.push_back(make_pair(a,b)); }
if(n==1)res.push_back(make_pair(1,1)); return res; }
////////////////////////////////////////////////////////////////////////////////
// Conic section solver
////////////////////////////////////////////////////////////////////////////////
// - Can determine LINE (2), CIRCLE (3), PARABOLA (3), ELLIPSE (4).
// - Assume the points are given as (x1,y1), (x2,y2), ...
// - First row represents variables
// (1) LINE (2 points)
// Eq: c1*x + c2*y + c3 = 0
// |[[x y 1] |
// | [x1 y1 1] | = 0
// | [x2 y2 1]]|
//
// (2) CIRCLE (3 points)
// Eq: c1*(x^2+y^2) + c2*x + c3*y + c4 = 0
// |[[x^2+y^2 x y 1] |
// | [x1^2+y1^2 x1 y1 1] | = 0
// | [x2^2+y2^2 x2 y2 1] |
// | [x3^2+y3^2 x3 y3 1]]|
// --Circle is *undefined* when c1 == 0
// --Solve to standard equation (x-x1)^2+(y-y1)^2=r^2 to check for
// other undefined cases. (like r^2 < 0).
//
// (3) PARABOLA (3 points)
// Eq: (Type 1 -- up-down) c1*x^2 + c2*x + c3*y + c4 = 0
// |[[x^2 x y 1] |
// | [x1^2 x1 y1 1] | = 0
// | [x2^2 x2 y2 1] |
// | [x3^2 x3 y3 1]]|
//
// Eq: (Type 2 -- left-right) c1*y^2 + c2*x + c3*y + c4 = 0
// |[[y^2 x y 1] |
// | [y1^2 x1 y1 1] | = 0
// | [y2^2 x2 y2 1] |
// | [y3^2 x3 y3 1]]|
//
// (4) ELLIPSE (4 points)
// Eq: c1*x^2 + c2*y^2 + c3*x + c4*y + c5 = 0
// |[[x^2 y^2 x y 1] |
// | [x1^2 y1^2 x1 y1 1] |
// | [x2^2 y2^2 x2 y2 1] | = 0
// | [x3^2 y3^2 x3 y3 1] |