-
Notifications
You must be signed in to change notification settings - Fork 0
/
carefree_linux.hpp
1532 lines (1308 loc) · 51.8 KB
/
carefree_linux.hpp
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
/*
* CareFree Library
* CopyRight (c) xiezheyuan 2024 - now
* Visit https://github.com/xiezheyuan/carefree for more details.
*/
#pragma once
#define CAREFREE_VERSION_MAJOR 0
#define CAREFREE_VERSION_MINOR 7
#define CAREFREE_VERSION "0.7"
#include <sys/stat.h>
#include <unistd.h>
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <fstream>
#include <initializer_list>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <vector>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wliteral-suffix"
#if __cplusplus >= 201703L
#define maybe_unused [[maybe_unused]]
#else
#define maybe_unused __attribute__((unused))
#endif
constexpr unsigned long long operator"" B(unsigned long long x) { return x; }
constexpr unsigned long long operator"" KiB(unsigned long long x) { return x * 1024; }
constexpr unsigned long long operator"" MiB(unsigned long long x) { return x * 1024 * 1024; }
constexpr unsigned long long operator"" GiB(unsigned long long x) { return x * 1024 * 1024 * 1024; }
constexpr unsigned long long operator"" TiB(unsigned long long x) { return x * 1024 * 1024 * 1024 * 1024; }
constexpr unsigned long long operator"" NS(unsigned long long x) { return x; }
constexpr unsigned long long operator"" MS(unsigned long long x) { return x * 1000 * 1000; }
constexpr unsigned long long operator"" S(unsigned long long x) { return x * 1000 * 1000 * 1000; }
constexpr unsigned long long operator"" MIN(unsigned long long x) { return x * 1000 * 1000 * 1000 * 60; }
namespace carefree_internal {
using std::string;
struct carefree_exception_name {
virtual string name() { return "carefree_exception"; }
};
template <class cpp_err_type, class err_name = carefree_exception_name>
class carefree_exception {
private:
string msg;
string cls_name;
public:
using err_type = cpp_err_type;
carefree_exception() { cls_name = err_name().name(); }
carefree_exception(string msg) : msg(msg) { cls_name = err_name().name(); }
carefree_exception(const char* msg) {
this->msg = msg;
cls_name = err_name().name();
}
string what() { return cls_name + " : " + get_msg(); }
cpp_err_type get_err() { return err_type(what()); };
string get_msg() { return msg; }
};
struct carefree_invalid_argument_name : public carefree_exception_name {
string name() { return "carefree_invalid_argument"; }
};
struct carefree_range_exception_name : public carefree_exception_name {
string name() { return "carefree_range_exception"; }
};
struct carefree_unsupported_operation_name : public carefree_exception_name {
string name() { return "carefree_unsupported_operation"; }
};
struct carefree_file_exception_name : public carefree_exception_name {
string name() { return "carefree_file_exception"; }
};
struct carefree_runtime_exception_name : public carefree_exception_name {
string name() { return "carefree_runtime_exception"; }
};
struct carefree_system_exception_name : public carefree_exception_name {
string name() { return "carefree_system_exception"; }
};
struct carefree_validate_failed_name : public carefree_exception_name {
string name() { return "carefree_validate_failed"; }
};
class _base_exception : public std::exception {
protected:
string msg;
public:
explicit _base_exception(const string& __arg) : msg(__arg) {};
explicit _base_exception(const char* __arg) : msg(__arg) {};
virtual ~_base_exception() noexcept = default;
virtual const char* what() const noexcept { return msg.c_str(); };
};
class _unsupported_operation : public _base_exception {
public:
explicit _unsupported_operation(const string& __arg) : _base_exception(__arg) {};
explicit _unsupported_operation(const char* __arg) : _base_exception(__arg) {};
virtual ~_unsupported_operation() noexcept = default;
};
class _file_exception : public _base_exception {
public:
explicit _file_exception(const string& __arg) : _base_exception(__arg) {};
explicit _file_exception(const char* __arg) : _base_exception(__arg) {};
virtual ~_file_exception() noexcept = default;
};
class _system_exception : public _base_exception {
public:
explicit _system_exception(const string& __arg) : _base_exception(__arg) {};
explicit _system_exception(const char* __arg) : _base_exception(__arg) {};
virtual ~_system_exception() noexcept = default;
};
class _validate_failed : public _base_exception {
public:
explicit _validate_failed(const string& __arg) : _base_exception(__arg) {};
explicit _validate_failed(const char* __arg) : _base_exception(__arg) {};
virtual ~_validate_failed() noexcept = default;
};
using _invalid_argument = std::invalid_argument;
using _range_exception = std::out_of_range;
using _runtime_exception = std::runtime_error;
using carefree_invalid_argument = carefree_exception<_invalid_argument, carefree_invalid_argument_name>;
using carefree_range_exception = carefree_exception<_range_exception, carefree_range_exception_name>;
using carefree_unsupported_operation = carefree_exception<_unsupported_operation, carefree_unsupported_operation_name>;
using carefree_file_exception = carefree_exception<_file_exception, carefree_file_exception_name>;
using carefree_runtime_exception = carefree_exception<_runtime_exception, carefree_runtime_exception_name>;
using carefree_system_exception = carefree_exception<_system_exception, carefree_system_exception_name>;
using carefree_validate_failed = carefree_exception<_validate_failed, carefree_validate_failed_name>;
enum exception_policy {
Throw,
Ignore,
Friendly,
Simulate,
};
exception_policy exception_policy_val = exception_policy::Throw;
exception_policy get_exception_policy() noexcept {
return exception_policy_val;
}
template <class T1, class T2>
void raise(carefree_exception<T1, T2> err) {
switch (get_exception_policy()) {
case Throw:
throw err.get_err();
break;
case Ignore:
std::fprintf(stderr, "CareFree Library : An Error Occured.\n%s\n", err.what().c_str());
break;
case Friendly:
std::fprintf(stderr, "CareFree Library : An Error Occured.\n%s\n", err.what().c_str());
exit(0);
break;
case Simulate:
std::fprintf(stderr, "CareFree Library : An Error Occured.\n%s\n", err.what().c_str());
std::terminate();
break;
default:
__builtin_unreachable();
std::abort();
break;
}
}
template <class T>
void err_range_checker(T l, T r, string func_name) {
string errmsg = func_name + " : " + "l(" + std::to_string(l) + ") > r(" + std::to_string(r) + ").";
if (l > r) raise(carefree_range_exception(errmsg));
}
template <class T>
void err_unempty_checker(T x, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + " is empty.";
if (x.empty()) raise(carefree_invalid_argument(errmsg));
}
template <class T>
void err_positive_checker(T x, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not positive.";
if (x <= 0) raise(carefree_invalid_argument(errmsg));
}
template <class T>
void err_natural_checker(T x, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not natural.";
if (x < 0) raise(carefree_invalid_argument(errmsg));
}
template <class T>
void err_inrange_checker(T x, T l, T r, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not in range [" + std::to_string(l) + ", " + std::to_string(r) + "].";
if (x < l || x > r) raise(carefree_range_exception(errmsg));
}
template <class T>
void err_less_checker(T x, T l, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not less than " + std::to_string(l) + ".";
if (x >= l) raise(carefree_range_exception(errmsg));
}
template <class T>
void err_greater_checker(T x, T l, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not greater than " + std::to_string(l) + ".";
if (x <= l) raise(carefree_range_exception(errmsg));
}
template <class T>
void err_leq_checker(T x, T l, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not less than or equal to " + std::to_string(l) + ".";
if (x > l) raise(carefree_range_exception(errmsg));
}
template <class T>
void err_geq_checker(T x, T l, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not greater than or equal to " + std::to_string(l) + ".";
if (x < l) raise(carefree_range_exception(errmsg));
}
template <class T>
void err_equal_checker(T x, T l, string func_name, string var_name) {
string errmsg = func_name + " :" + var_name + "(" + std::to_string(x) + ") is not equal to " + std::to_string(l) + ".";
if (x != l) raise(carefree_range_exception(errmsg));
}
template <class T>
void err_unequal_checker(T x, T l, string func_name, string var_name) {
string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not unequal to " + std::to_string(l) + ".";
if (x == l) raise(carefree_range_exception(errmsg));
}
void set_exception_policy(exception_policy policy) {
if (policy != Throw && policy != Ignore && policy != Friendly && policy != Simulate) {
raise(carefree_invalid_argument("set_exception_policy : unsupport policy."));
}
exception_policy_val = policy;
}
template <class T1, class T2>
string join_str(T1 a, T2 b) {
return string(a) + string(b);
}
template <class T>
string __fts(T val, unsigned precision = 10) {
static char buffer[255], buffer2[2047];
if (std::is_same<T, float>::value)
sprintf(buffer, "%%.%df", precision);
else if (std::is_same<T, double>::value)
sprintf(buffer, "%%.%dlf", precision);
else if (std::is_same<T, long double>::value)
sprintf(buffer, "%%.%dlf", precision);
else {
const std::type_info& x = typeid(T);
raise(carefree_invalid_argument(join_str("__fts : unsupport type ", x.name()).c_str()));
}
sprintf(buffer2, buffer, val);
string str(buffer2);
return str;
}
string fts(float val, unsigned precision = 10) {
return __fts(val, precision);
}
string fts(double val, unsigned precision = 10) {
return __fts(val, precision);
}
string fts(long double val, unsigned precision = 10) {
return __fts(val, precision);
}
template <class T>
std::vector<string> fts(std::vector<T> val, unsigned precision = 10) {
std::vector<string> ans;
for (auto it = val.begin(); it != val.end(); ++it) {
ans.push_back(fts(*it, precision));
}
return ans;
}
template <class T>
std::vector<T> ltv(std::initializer_list<T> val) {
return std::vector<T>(val);
}
std::mt19937_64 public_random_engine;
template <class T>
T randint(T l, T r) {
err_range_checker(l, r, __func__);
return std::uniform_int_distribution<T>(l, r)(public_random_engine);
}
template <class T>
T uniform(T l, T r) {
err_range_checker(l, r, __func__);
return std::uniform_real_distribution<T>(l, r)(public_random_engine);
}
double random() {
return uniform(0.0, 1.0);
}
template <class T>
typename T::value_type choice(T val) {
err_unempty_checker(val, __func__, "val");
return val[randint(0ull, val.size() - 1ull)];
}
template <class T>
void shuffle(T val) {
std::shuffle(val.begin(), val.end(), public_random_engine);
}
template <class T, class Value>
std::vector<Value> sequence(int n, T function) {
std::vector<Value> data;
err_positive_checker(n, __func__, "n");
for (int i = 1; i <= n; i++) {
data.push_back(function(i));
}
return data;
}
template <class T>
std::vector<T> sequence(int n, T l, T r) {
static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "T must be integral or floating point");
return sequence(n, [&](int i) {
if (std::is_integral<T>::value)
return (T)randint(l, r);
else
return (T)uniform(l, r);
});
}
template <class T>
std::vector<T> sequence(int lengthL, int lengthR, T l, T r) {
static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "T must be integral or floating point");
return sequence(randint(lengthL, lengthR), [&](int i) {
if (std::is_integral<T>::value)
return (T)randint(l, r);
else
return (T)uniform(l, r);
});
}
namespace strsets {
const string lower = "abcdefghijklmnopqrstuvwxyz";
const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string digit = "0123456789";
const string alphanum = lower + upper + digit;
const string alphabet = lower + upper;
const string slug = lower + digit + "-";
const string var_name = lower + upper + digit + "_";
const string bracket_general = "()[]{}<>";
const string bracket = "()[]{}";
const string quotes = "\"'";
const string math_symbols_naive = "+-*";
const string math_symbols_simple = "+-*/%";
const string math_symbols = math_symbols_simple + "^";
const string bool_symbols = "|&!";
const string bitwise_symbols = bool_symbols + "~^";
} // namespace strsets
string randstr(int length, const string sset = strsets::lower) {
err_natural_checker(length, __func__, "length");
err_unempty_checker(sset, __func__, "sset");
string str;
for (int i = 0; i < length; i++) str += choice(sset);
return str;
}
string randstr(int lengthL, int lengthR, const string sset = strsets::lower) {
return randstr(randint(lengthL, lengthR), sset);
}
template <class T>
double timer(T function) {
auto start = std::chrono::system_clock::now();
function();
auto end = std::chrono::system_clock::now();
return (double)std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
}
template <class T>
void gen_data(int subtask_count, int task_per_subtask, T function) {
err_positive_checker(subtask_count, __func__, "subtask_count");
err_positive_checker(task_per_subtask, __func__, "task_per_subtask");
int total_tasks = subtask_count * task_per_subtask;
int current_task = 0;
double average = 0;
int barWidth = 100;
std::cout << "[";
for (int k = 0; k < barWidth; ++k) {
std::cout << " ";
}
std::cout << "] " << 0 << "% ";
std::cout << "#-# N/A it / s\r";
for (int i = 1; i <= subtask_count; i++) {
for (int j = 1; j <= task_per_subtask; j++) {
double time_ = timer([&]() {
function(i, j);
});
average += time_;
current_task++;
float progress = static_cast<float>(current_task) / total_tasks;
int pos = static_cast<int>(barWidth * progress);
std::cout << "[";
for (int k = 0; k < barWidth; ++k) {
if (k < pos)
std::cout << "=";
else if (k == pos)
std::cout << ">";
else
std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << "% ";
std::cout << i << "-" << j << " ";
std::cout << fts(average / current_task, 2) << " it / s";
std::cout << "\r";
std::cout.flush();
}
}
std::cout << std::endl;
}
template <class T>
void gen_data(int task_count, T function) {
err_positive_checker(task_count, __func__, "task_count");
int total_tasks = task_count;
int current_task = 0;
double average = 0;
int barWidth = 100;
std::cout << "[";
for (int k = 0; k < barWidth; ++k) {
std::cout << " ";
}
std::cout << "] " << 0 << "% ";
std::cout << "# N/A it / s\r";
for (int i = 1; i <= task_count; i++) {
double time_ = timer([&]() {
function(i);
});
average += time_;
current_task++;
float progress = static_cast<float>(current_task) / total_tasks;
int pos = static_cast<int>(barWidth * progress);
std::cout << "[";
for (int k = 0; k < barWidth; ++k) {
if (k < pos)
std::cout << "=";
else if (k == pos)
std::cout << ">";
else
std::cout << " ";
}
std::cout << "] " << int(progress * 100.0) << "% ";
std::cout << i << " ";
std::cout << fts(average / current_task, 2) << " it / s";
std::cout << "\r";
std::cout.flush();
}
std::cout << std::endl;
}
__attribute__((constructor)) static void init_rnd_seed() {
public_random_engine.seed(std::time(NULL));
}
template <class T, class Compare = std::less<T>>
class BalancedTree {
private:
__gnu_pbds::tree<T, __gnu_pbds::null_type, Compare, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> tree;
public:
void insert(T x) { tree.insert(x); }
bool erase(T x) { return tree.erase(x); }
int rnk(T x) { return tree.order_of_key(x) + 1; }
T kth(int x) { return *tree.find_by_order(x - 1); }
int size() { return tree.size(); }
bool empty() { return tree.empty(); }
};
using _Weight = long long;
class graph {
public:
struct edge {
int from, to;
_Weight weight;
edge(int from, int to, _Weight weight = 0) : from(from), to(to), weight(weight) {}
};
struct weighted_output {
string operator()(edge edg) {
return std::to_string(edg.from) + " " + std::to_string(edg.to) + " " + std::to_string(edg.weight);
}
};
struct unweighted_output {
string operator()(edge edg) {
return std::to_string(edg.from) + " " + std::to_string(edg.to);
}
};
private:
struct chain_node {
int nxt, to;
_Weight w;
chain_node() {}
chain_node(int nxt, int to, _Weight w) : nxt(nxt), to(to), w(w) {}
};
std::vector<chain_node> chain;
std::vector<int> head;
std::vector<std::map<int, bool>> edge_map;
std::vector<edge> edge_vct;
public:
int N;
bool directed;
bool enable_edge_map;
graph(int N, bool directed = false, bool enable_edge_map = true) {
err_positive_checker(N, __func__, "N");
this->N = N;
this->directed = directed;
this->enable_edge_map = enable_edge_map;
head = std::vector<int>(N + 1, -1);
edge_map = std::vector<std::map<int, bool>>(N + 1);
}
void add(edge edg, bool __add_vector = true) {
err_inrange_checker(edg.from, 0, N, __func__, "edg.from");
err_inrange_checker(edg.to, 0, N, __func__, "edg.to");
chain.push_back(chain_node(head[edg.from], edg.to, edg.weight));
head[edg.from] = chain.size() - 1;
if (!directed && __add_vector) add(edge(edg.to, edg.from, edg.weight), false);
if (__add_vector) edge_vct.push_back(edg);
if (enable_edge_map) edge_map[edg.from][edg.to] = true;
}
void add(int from, int to, _Weight weight = 0) {
add(edge(from, to, weight));
}
bool has_edge(edge edg) {
if (!enable_edge_map) raise(carefree_unsupported_operation("has_edge : edge map is not enabled"));
return edge_map[edg.from][edg.to];
}
bool has_edge(int from, int to) {
return has_edge(edge(from, to));
}
std::vector<edge> get_edges() {
return edge_vct;
}
std::vector<edge> get_edges(int from) {
err_inrange_checker(from, 0, N, __func__, "from");
std::vector<edge> edges;
for (int i = head[from]; ~i; i = chain[i].nxt) edges.push_back(edge(from, chain[i].to, chain[i].w));
return edges;
}
template <class T = weighted_output>
string to_string(bool shuffle = false) {
std::vector<edge> edges = get_edges();
if (shuffle) std::shuffle(edges.begin(), edges.end(), public_random_engine);
string str;
for (auto it = edges.begin(); it != edges.end(); ++it) {
str += T()(*it);
if ((it + 1) != edges.end()) str += '\n';
}
return str;
}
};
using edge = graph::edge;
using weighted_output = graph::weighted_output;
using unweighted_output = graph::unweighted_output;
bool is_tree(graph g) {
std::vector<int> fa(g.N + 1);
for (int i = 1; i <= g.N; i++) fa[i] = i;
auto edges = g.get_edges();
if (edges.size() != (unsigned)(g.N - 1)) return false;
std::function<int(int)> find = [&](int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
};
for (auto i : edges) {
int u = i.from, v = i.to;
if (find(u) == find(v)) return false;
fa[find(u)] = find(v);
}
return true;
}
graph relabel(graph g) {
std::vector<int> perm;
for (int i = 1; i <= g.N; i++) perm.push_back(i);
std::shuffle(perm.begin(), perm.end(), public_random_engine);
graph new_(g.N, g.directed, g.enable_edge_map);
for (auto i : g.get_edges()) {
new_.add(perm[i.from - 1], perm[i.to - 1], i.weight);
}
return new_;
}
graph prufer_decode(int n, std::vector<int> prufer, _Weight weightL = 0, _Weight weightR = 0) {
std::vector<int> deg(n + 1, 1);
prufer.insert(prufer.begin(), 0);
graph g(n, false);
if (prufer.size() != (unsigned)(n - 1)) raise(carefree_invalid_argument("prufer_decode : prufer size must be n-1"));
for (int i = 1; i <= (n - 2); i++) {
err_inrange_checker(prufer[i], 1, n, __func__, "prufer[" + std::to_string(i) + "]");
}
for (int i = 1; i <= (n - 2); i++) deg[prufer[i]]++;
int ptr = 1, leaf = 0;
while (deg[ptr] != 1) ptr++;
leaf = ptr;
for (int i = 1; i <= (n - 2); i++) {
int v = prufer[i];
g.add(v, leaf, randint(weightL, weightR));
if (--deg[v] == 1 && v < ptr)
leaf = v;
else {
ptr++;
while (deg[ptr] != 1) ptr++;
leaf = ptr;
}
}
g.add(n, leaf, randint(weightL, weightR));
return g;
}
std::vector<int> get_depth(graph g) {
std::queue<int> q;
std::vector<int> depth(g.N + 1);
q.push(1);
depth[1] = 1;
while (!q.empty()) {
auto u = q.front();
q.pop();
for (auto i : g.get_edges(u)) {
if (!depth[i.to]) {
depth[i.to] = depth[u] + 1;
q.push(i.to);
}
}
}
return depth;
}
graph introvert(graph tree) {
auto depth = get_depth(tree);
graph g(tree.N, true);
for (auto i : tree.get_edges()) {
int u = i.from, v = i.to;
auto w = i.weight;
if (depth[u] < depth[v]) std::swap(u, v);
g.add(u, v, w);
}
return g;
}
graph externalize(graph tree) {
auto depth = get_depth(tree);
graph g(tree.N, true);
for (auto i : tree.get_edges()) {
int u = i.from, v = i.to;
auto w = i.weight;
if (depth[u] > depth[v]) std::swap(u, v);
g.add(u, v, w);
}
return g;
}
graph lowhigh(int n, double low, double high, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
for (int i = 2; i <= n; i++) {
int fa = randint(std::max((int)((i - 1) * low), 1), std::min((int)((i - 1) * high), i - 1));
g.add(fa, i, randint(weightL, weightR));
}
return g;
}
graph naive_tree(int n, _Weight weightL = 0, _Weight weightR = 0) {
return lowhigh(n, 0, 1, weightL, weightR);
}
graph tail(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
for (int i = 2; i <= n; i++) {
int fa = randint(std::max(i - k, 1), i - 1);
g.add(fa, i, randint(weightL, weightR));
}
return g;
}
graph chain(int n, _Weight weightL = 0, _Weight weightR = 0) {
return tail(n, 1, weightL, weightR);
}
graph star(int n, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
for (int i = 2; i <= n; i++) {
g.add(1, i, randint(weightL, weightR));
}
return g;
}
graph flower(int n, _Weight weightL = 0, _Weight weightR = 0) {
return star(n, weightL, weightR);
}
graph max_degree(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
BalancedTree<std::pair<int, int>> tree;
tree.insert({1, 0});
for (int i = 2; i <= n; i++) {
auto fa = tree.kth(randint(1, tree.size()));
tree.erase(fa);
if (fa.second < k) tree.insert({fa.first, fa.second + 1});
g.add(fa.first, i, randint(weightL, weightR));
tree.insert({i, 0});
}
return g;
}
graph binary_tree(int n, _Weight weightL = 0, _Weight weightR = 0) {
return max_degree(n, 3, weightL, weightR);
}
graph chain_star(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
for (int i = 2; i <= k; i++) g.add(i - 1, i, randint(weightL, weightR));
for (int i = k + 1; i <= n; i++) g.add(randint(1, k), i, randint(weightL, weightR));
return g;
}
graph silkworm(int n, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
for (int i = 2; i <= (n >> 1); i++) g.add(i - 1, i, randint(weightL, weightR));
for (int i = (n >> 1) + 1; i <= (n >> 1) << 1; i++) g.add(i - (n >> 1), i, randint(weightL, weightR));
if (((n >> 1) << 1) != n) g.add(randint(1, n - 1), n, randint(weightL, weightR));
return g;
}
graph firecrackers(int n, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
int tmp = n / 3;
for (int i = 2; i <= tmp; i++) g.add(i - 1, i, randint(weightL, weightR));
for (int i = tmp + 1; i <= tmp * 2; i++) g.add(i - tmp, i, randint(weightL, weightR));
for (int i = (tmp << 1) + 1; i <= tmp * 3; i++) g.add(i - (tmp << 1), i, randint(weightL, weightR));
for (int i = (tmp * 3 + 1); i <= n; i++) g.add(randint(1, i - 1), i, randint(weightL, weightR));
return g;
}
graph complete(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
std::queue<int> q;
q.push(1);
int tot = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
int bound = std::min(tot + k - 1, n);
for (int i = tot + 1; i <= bound; i++) {
g.add(u, (++tot), randint(weightL, weightR));
q.push(i);
}
}
return g;
}
graph complete_binary(int n, _Weight weightL = 0, _Weight weightR = 0) {
return complete(n, 3, weightL, weightR);
}
graph random_tree(int n, _Weight weightL = 0, _Weight weightR = 0) {
graph g(n, false);
std::vector<int> prufer;
for (int i = 1; i <= n - 2; i++) prufer.push_back(randint(1, n));
return prufer_decode(n, prufer, weightL, weightR);
}
graph dag(int n, int m, bool repeat_edges = false, _Weight weightL = 0, _Weight weightR = 0) {
graph tree = random_tree(n, weightL, weightR);
auto depth = get_depth(tree);
graph ret = externalize(tree);
err_geq_checker(m, n - 1, __func__, "m");
for (int i = n; i <= m; i++) {
while (true) {
int u = randint(1, n);
int v = randint(1, n);
if (u == v) continue;
if (depth[u] > depth[v]) std::swap(u, v);
if (!repeat_edges && ret.has_edge(u, v)) continue;
ret.add(u, v, randint(weightL, weightR));
break;
}
}
return ret;
}
graph connected_undirected_graph(int n, int m, bool repeat_edges = false, bool self_loop = false, _Weight weightL = 0, _Weight weightR = 0) {
graph tree = random_tree(n, weightL, weightR);
graph ret = tree;
err_geq_checker(m, n - 1, __func__, "m");
for (int i = n; i <= m; i++) {
while (true) {
int u = randint(1, n);
int v = randint(1, n);
if (!self_loop && u == v) continue;
if (!repeat_edges && ret.has_edge(u, v)) continue;
ret.add(u, v, randint(weightL, weightR));
break;
}
}
return ret;
}
graph connected_directed_graph(int n, int m, bool repeat_edges = false, bool self_loop = false, _Weight weightL = 0, _Weight weightR = 0) {
graph tree = random_tree(n, weightL, weightR);
graph ret = externalize(tree);
err_geq_checker(m, n - 1, __func__, "m");
for (int i = n; i <= m; i++) {
while (true) {
int u = randint(1, n);
int v = randint(1, n);
if (!self_loop && u == v) continue;
if (!repeat_edges && ret.has_edge(u, v)) continue;
ret.add(u, v, randint(weightL, weightR));
break;
}
}
return ret;
}
graph random_graph(int n, int m, bool directed = true, bool repeat_edges = false, bool self_loop = false, _Weight weightL = 0, _Weight weightR = 0) {
graph ret(n, directed);
for (int i = 1; i <= m; i++) {
while (true) {
int u = randint(1, n);
int v = randint(1, n);
if (!self_loop && u == v) continue;
if (!repeat_edges && ret.has_edge(u, v)) continue;
ret.add(u, v, randint(weightL, weightR));
break;
}
}
return ret;
}
class testcase_writer {
private:
class file_writer {
private:
std::FILE* fp;
void _ein() {
if (fp == nullptr) raise(carefree_file_exception("testcase_writer::file_writer::_ein : file is not opened."));
}
public:
string _filename;
file_writer() {}
file_writer(const char* filename) {
_filename = filename;
if (std::strlen(filename)) {
fp = std::fopen(filename, "w");
if (fp == NULL) raise(carefree_file_exception("testcase_writer::file_writer::file_writer : cannot open file " + _filename));
} else
fp = nullptr;
}
void close() {
if (fp != nullptr) std::fclose(fp);
}
~file_writer() { close(); }
void writeChar(char val) {
_ein();
std::fputc(val, fp);
}
template <class T>
void writeInteger(T val) {
_ein();
if (val < 0) {
val = -val;
writeChar('-');
}
if (val == 0) {
writeChar('0');
return;
}
if (val >= 10) writeInteger(val / 10);
writeChar('0' + val % 10);
}
void writeString(const char* val) {
_ein();
const char* ptr = val;
while (*ptr != '\0') writeChar(*(ptr++));
}
void writeString(string val) {
_ein();
writeString(val.c_str());
}
void flush() {
_ein();
std::fflush(fp);
}
};
file_writer* fin;
file_writer* fout;
bool locked;
void _eil() {
if (locked) raise(carefree_unsupported_operation("testcase_writer::_eil : input/output file has already locked."));
}
void lock() { locked = true; }
public:
testcase_writer(string input_file, string output_file = "") {
fin = new file_writer(input_file.c_str());
fout = new file_writer(output_file.c_str());
locked = false;
}