Carefree (For Windows) 0.7
CareFree Library - A Light Data Generator for OI & ACM
载入中...
搜索中...
未找到
carefree.hpp
浏览该文件的文档.
1/*
2 * CareFree Library
3 * CopyRight (c) xiezheyuan 2024 - now
4 * Visit https://github.com/xiezheyuan/carefree for more details.
5 */
6
7#pragma once
8
9#if __cplusplus < 201300L
10#error "carefree library need C++ 14 or higher version"
11#endif
12#ifndef __GNUC__
13#error "carefree library need GCC compiler or similar"
14#endif
15#ifndef _WIN32
16#ifndef __linux__
17#error "carefree library need Linux or Windows system."
18#else
19#error "carefree library don't support Linux system now.Please wait."
20#endif
21#else
22#include <windows.h>
23#ifdef PSAPI_LINKED
24#include <psapi.h>
25#endif
26#endif
27
28#define CAREFREE_VERSION_MAJOR 0
29#define CAREFREE_VERSION_MINOR 7
30#define CAREFREE_VERSION "0.7"
31
32#include <io.h>
33#include <sys/stat.h>
34#include <unistd.h>
35
36#include <algorithm>
37#include <chrono>
38#include <cstdio>
39#include <cstdlib>
40#include <cstring>
41#include <ctime>
42#include <ext/pb_ds/assoc_container.hpp>
43#include <ext/pb_ds/tree_policy.hpp>
44#include <fstream>
45#include <initializer_list>
46#include <iomanip>
47#include <iostream>
48#include <map>
49#include <numeric>
50#include <queue>
51#include <random>
52#include <sstream>
53#include <stdexcept>
54#include <string>
55#include <type_traits>
56#include <typeinfo>
57#include <vector>
58
59#pragma GCC diagnostic push
60#pragma GCC diagnostic ignored "-Wliteral-suffix"
61
62#if __cplusplus >= 201703L
63#define maybe_unused [[maybe_unused]]
64#else
65#define maybe_unused __attribute__((unused))
66#endif
67
68constexpr unsigned long long operator"" B(unsigned long long x) { return x; }
69
70constexpr unsigned long long operator"" KiB(unsigned long long x) { return x * 1024; }
71
72constexpr unsigned long long operator"" MiB(unsigned long long x) { return x * 1024 * 1024; }
73
74constexpr unsigned long long operator"" GiB(unsigned long long x) { return x * 1024 * 1024 * 1024; }
75
76constexpr unsigned long long operator"" TiB(unsigned long long x) { return x * 1024 * 1024 * 1024 * 1024; }
77
78constexpr unsigned long long operator"" NS(unsigned long long x) { return x; }
79
80constexpr unsigned long long operator"" MS(unsigned long long x) { return x * 1000 * 1000; }
81
82constexpr unsigned long long operator"" S(unsigned long long x) { return x * 1000 * 1000 * 1000; }
83
84constexpr unsigned long long operator"" MIN(unsigned long long x) { return x * 1000 * 1000 * 1000 * 60; }
85
87
88 using std::string;
89
91 virtual string name() { return "carefree_exception"; }
92 };
93
94 template <class cpp_err_type, class err_name = carefree_exception_name>
96 private:
97 string msg;
98 string cls_name;
99
100 public:
101 using err_type = cpp_err_type;
102
103 carefree_exception() { cls_name = err_name().name(); }
104
105 carefree_exception(string msg) : msg(msg) { cls_name = err_name().name(); }
106
107 carefree_exception(const char* msg) {
108 this->msg = msg;
109 cls_name = err_name().name();
110 }
111
112 string what() { return cls_name + " : " + get_msg(); }
113
114 cpp_err_type get_err() { return err_type(what()); };
115
116 string get_msg() { return msg; }
117 };
118
120 string name() { return "carefree_invalid_argument"; }
121 };
122
124 string name() { return "carefree_range_exception"; }
125 };
126
128 string name() { return "carefree_unsupported_operation"; }
129 };
130
132 string name() { return "carefree_file_exception"; }
133 };
134
136 string name() { return "carefree_runtime_exception"; }
137 };
138
140 string name() { return "carefree_system_exception"; }
141 };
142
144 string name() { return "carefree_validate_failed"; }
145 };
146
147 class _base_exception : public std::exception {
148 protected:
149 string msg;
150
151 public:
152 explicit _base_exception(const string& __arg) : msg(__arg) {};
153 explicit _base_exception(const char* __arg) : msg(__arg) {};
154 virtual ~_base_exception() noexcept = default;
155 virtual const char* what() const noexcept { return msg.c_str(); };
156 };
157
159 public:
160 explicit _unsupported_operation(const string& __arg) : _base_exception(__arg) {};
161 explicit _unsupported_operation(const char* __arg) : _base_exception(__arg) {};
162 virtual ~_unsupported_operation() noexcept = default;
163 };
164
166 public:
167 explicit _file_exception(const string& __arg) : _base_exception(__arg) {};
168 explicit _file_exception(const char* __arg) : _base_exception(__arg) {};
169 virtual ~_file_exception() noexcept = default;
170 };
171
173 public:
174 explicit _system_exception(const string& __arg) : _base_exception(__arg) {};
175 explicit _system_exception(const char* __arg) : _base_exception(__arg) {};
176 virtual ~_system_exception() noexcept = default;
177 };
178
180 public:
181 explicit _validate_failed(const string& __arg) : _base_exception(__arg) {};
182 explicit _validate_failed(const char* __arg) : _base_exception(__arg) {};
183 virtual ~_validate_failed() noexcept = default;
184 };
185
186 using _invalid_argument = std::invalid_argument;
187
188 using _range_exception = std::out_of_range;
189
190 using _runtime_exception = std::runtime_error;
191
193
195
197
199
201
203
205
216
218
222
223 template <class T1, class T2>
225 switch (get_exception_policy()) {
226 case Throw:
227 throw err.get_err();
228 break;
229 case Ignore:
230 std::fprintf(stderr, "CareFree Library : An Error Occured.\n%s\n", err.what().c_str());
231 break;
232 case Friendly:
233 std::fprintf(stderr, "CareFree Library : An Error Occured.\n%s\n", err.what().c_str());
234 exit(0);
235 break;
236 case Simulate:
237 std::fprintf(stderr, "CareFree Library : An Error Occured.\n%s\n", err.what().c_str());
238 std::terminate();
239 break;
240 default:
241 __builtin_unreachable();
242 std::abort();
243 break;
244 }
245 }
246
247 template <class T>
248 void err_range_checker(T l, T r, string func_name) {
249 string errmsg = func_name + " : " + "l(" + std::to_string(l) + ") > r(" + std::to_string(r) + ").";
250 if (l > r) raise(carefree_range_exception(errmsg));
251 }
252
253 template <class T>
254 void err_unempty_checker(T x, string func_name, string var_name) {
255 string errmsg = func_name + " : " + var_name + " is empty.";
256 if (x.empty()) raise(carefree_invalid_argument(errmsg));
257 }
258
259 template <class T>
260 void err_positive_checker(T x, string func_name, string var_name) {
261 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not positive.";
262 if (x <= 0) raise(carefree_invalid_argument(errmsg));
263 }
264
265 template <class T>
266 void err_natural_checker(T x, string func_name, string var_name) {
267 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not natural.";
268 if (x < 0) raise(carefree_invalid_argument(errmsg));
269 }
270
271 template <class T>
272 void err_inrange_checker(T x, T l, T r, string func_name, string var_name) {
273 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not in range [" + std::to_string(l) + ", " + std::to_string(r) + "].";
274 if (x < l || x > r) raise(carefree_range_exception(errmsg));
275 }
276
277 template <class T>
278 void err_less_checker(T x, T l, string func_name, string var_name) {
279 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not less than " + std::to_string(l) + ".";
280 if (x >= l) raise(carefree_range_exception(errmsg));
281 }
282
283 template <class T>
284 void err_greater_checker(T x, T l, string func_name, string var_name) {
285 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not greater than " + std::to_string(l) + ".";
286 if (x <= l) raise(carefree_range_exception(errmsg));
287 }
288
289 template <class T>
290 void err_leq_checker(T x, T l, string func_name, string var_name) {
291 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not less than or equal to " + std::to_string(l) + ".";
292 if (x > l) raise(carefree_range_exception(errmsg));
293 }
294
295 template <class T>
296 void err_geq_checker(T x, T l, string func_name, string var_name) {
297 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not greater than or equal to " + std::to_string(l) + ".";
298 if (x < l) raise(carefree_range_exception(errmsg));
299 }
300
301 template <class T>
302 void err_equal_checker(T x, T l, string func_name, string var_name) {
303 string errmsg = func_name + " :" + var_name + "(" + std::to_string(x) + ") is not equal to " + std::to_string(l) + ".";
304 if (x != l) raise(carefree_range_exception(errmsg));
305 }
306
307 template <class T>
308 void err_unequal_checker(T x, T l, string func_name, string var_name) {
309 string errmsg = func_name + " : " + var_name + "(" + std::to_string(x) + ") is not unequal to " + std::to_string(l) + ".";
310 if (x == l) raise(carefree_range_exception(errmsg));
311 }
312
314 if (policy != Throw && policy != Ignore && policy != Friendly && policy != Simulate) {
315 raise(carefree_invalid_argument("set_exception_policy : unsupport policy."));
316 }
317 exception_policy_val = policy;
318 }
319
320 template <class T1, class T2>
321 string join_str(T1 a, T2 b) {
322 return string(a) + string(b);
323 }
324
325 template <class T>
326 string __fts(T val, unsigned precision = 10) {
327 static char buffer[255], buffer2[2047];
328 if (std::is_same<T, float>::value)
329 sprintf(buffer, "%%.%df", precision);
330 else if (std::is_same<T, double>::value)
331 sprintf(buffer, "%%.%dlf", precision);
332 else if (std::is_same<T, long double>::value)
333 sprintf(buffer, "%%.%dlf", precision);
334 else {
335 const std::type_info& x = typeid(T);
336 raise(carefree_invalid_argument(join_str("__fts : unsupport type ", x.name()).c_str()));
337 }
338 sprintf(buffer2, buffer, val);
339 string str(buffer2);
340 return str;
341 }
342
343 string fts(float val, unsigned precision = 10) {
344 return __fts(val, precision);
345 }
346
347 string fts(double val, unsigned precision = 10) {
348 return __fts(val, precision);
349 }
350
351 string fts(long double val, unsigned precision = 10) {
352 return __fts(val, precision);
353 }
354
355 template <class T>
356 std::vector<string> fts(std::vector<T> val, unsigned precision = 10) {
357 std::vector<string> ans;
358 for (auto it = val.begin(); it != val.end(); ++it) {
359 ans.push_back(fts(*it, precision));
360 }
361 return ans;
362 }
363
364 template <class T>
365 std::vector<T> ltv(std::initializer_list<T> val) {
366 return std::vector<T>(val);
367 }
368
369 std::mt19937_64 public_random_engine;
370
371 template <class T>
372 T randint(T l, T r) {
373 err_range_checker(l, r, __func__);
374 return std::uniform_int_distribution<T>(l, r)(public_random_engine);
375 }
376
377 template <class T>
378 T uniform(T l, T r) {
379 err_range_checker(l, r, __func__);
380 return std::uniform_real_distribution<T>(l, r)(public_random_engine);
381 }
382
383 double random() {
384 return uniform(0.0, 1.0);
385 }
386
387 template <class T>
388 typename T::value_type choice(T val) {
389 err_unempty_checker(val, __func__, "val");
390 return val[randint(0ull, val.size() - 1ull)];
391 }
392
393 template <class T>
394 void shuffle(T val) {
395 std::shuffle(val.begin(), val.end(), public_random_engine);
396 }
397
398 template <class T, class Value>
399 std::vector<Value> sequence(int n, T function) {
400 std::vector<Value> data;
401 err_positive_checker(n, __func__, "n");
402 for (int i = 1; i <= n; i++) {
403 data.push_back(function(i));
404 }
405 return data;
406 }
407
408 template <class T>
409 std::vector<T> sequence(int n, T l, T r) {
410 static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "T must be integral or floating point");
411 return sequence(n, [&](int i) {
412 if (std::is_integral<T>::value)
413 return (T)randint(l, r);
414 else
415 return (T)uniform(l, r);
416 });
417 }
418
419 template <class T>
420 std::vector<T> sequence(int lengthL, int lengthR, T l, T r) {
421 static_assert(std::is_integral<T>::value || std::is_floating_point<T>::value, "T must be integral or floating point");
422 return sequence(randint(lengthL, lengthR), [&](int i) {
423 if (std::is_integral<T>::value)
424 return (T)randint(l, r);
425 else
426 return (T)uniform(l, r);
427 });
428 }
429
430 namespace strsets {
431 const string lower = "abcdefghijklmnopqrstuvwxyz";
432 const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
433 const string digit = "0123456789";
434 const string alphanum = lower + upper + digit;
435 const string alphabet = lower + upper;
436 const string slug = lower + digit + "-";
437 const string var_name = lower + upper + digit + "_";
438 const string bracket_general = "()[]{}<>";
439 const string bracket = "()[]{}";
440 const string quotes = "\"'";
441 const string math_symbols_naive = "+-*";
442 const string math_symbols_simple = "+-*/%";
443 const string math_symbols = math_symbols_simple + "^";
444 const string bool_symbols = "|&!";
445 const string bitwise_symbols = bool_symbols + "~^";
446 } // namespace strsets
447
448 string randstr(int length, const string sset = strsets::lower) {
449 err_natural_checker(length, __func__, "length");
450 err_unempty_checker(sset, __func__, "sset");
451 string str;
452 for (int i = 0; i < length; i++) str += choice(sset);
453 return str;
454 }
455
456 string randstr(int lengthL, int lengthR, const string sset = strsets::lower) {
457 return randstr(randint(lengthL, lengthR), sset);
458 }
459
460 template <class T>
461 double timer(T function) {
462 auto start = std::chrono::system_clock::now();
463 function();
464 auto end = std::chrono::system_clock::now();
465 return (double)std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
466 }
467
468 template <class T>
469 void gen_data(int subtask_count, int task_per_subtask, T function) {
470 err_positive_checker(subtask_count, __func__, "subtask_count");
471 err_positive_checker(task_per_subtask, __func__, "task_per_subtask");
472 int total_tasks = subtask_count * task_per_subtask;
473 int current_task = 0;
474 double average = 0;
475 int barWidth = 100;
476 std::cout << "[";
477 for (int k = 0; k < barWidth; ++k) {
478 std::cout << " ";
479 }
480 std::cout << "] " << 0 << "% ";
481 std::cout << "#-# N/A it / s\r";
482 for (int i = 1; i <= subtask_count; i++) {
483 for (int j = 1; j <= task_per_subtask; j++) {
484 double time_ = timer([&]() {
485 function(i, j);
486 });
487 average += time_;
488 current_task++;
489 float progress = static_cast<float>(current_task) / total_tasks;
490 int pos = static_cast<int>(barWidth * progress);
491 std::cout << "[";
492 for (int k = 0; k < barWidth; ++k) {
493 if (k < pos)
494 std::cout << "=";
495 else if (k == pos)
496 std::cout << ">";
497 else
498 std::cout << " ";
499 }
500 std::cout << "] " << int(progress * 100.0) << "% ";
501 std::cout << i << "-" << j << " ";
502 std::cout << fts(average / current_task, 2) << " it / s";
503 std::cout << "\r";
504 std::cout.flush();
505 }
506 }
507 std::cout << std::endl;
508 }
509
510 template <class T>
511 void gen_data(int task_count, T function) {
512 err_positive_checker(task_count, __func__, "task_count");
513 int total_tasks = task_count;
514 int current_task = 0;
515 double average = 0;
516 int barWidth = 100;
517 std::cout << "[";
518 for (int k = 0; k < barWidth; ++k) {
519 std::cout << " ";
520 }
521 std::cout << "] " << 0 << "% ";
522 std::cout << "# N/A it / s\r";
523 for (int i = 1; i <= task_count; i++) {
524 double time_ = timer([&]() {
525 function(i);
526 });
527 average += time_;
528 current_task++;
529 float progress = static_cast<float>(current_task) / total_tasks;
530 int pos = static_cast<int>(barWidth * progress);
531 std::cout << "[";
532 for (int k = 0; k < barWidth; ++k) {
533 if (k < pos)
534 std::cout << "=";
535 else if (k == pos)
536 std::cout << ">";
537 else
538 std::cout << " ";
539 }
540 std::cout << "] " << int(progress * 100.0) << "% ";
541 std::cout << i << " ";
542 std::cout << fts(average / current_task, 2) << " it / s";
543 std::cout << "\r";
544 std::cout.flush();
545 }
546 std::cout << std::endl;
547 }
548
549 __attribute__((constructor)) static void init_rnd_seed() {
550 public_random_engine.seed(std::time(NULL));
551 }
552
553 template <class T, class Compare = std::less<T>>
555 private:
556 __gnu_pbds::tree<T, __gnu_pbds::null_type, Compare, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> tree;
557
558 public:
559 void insert(T x) { tree.insert(x); }
560
561 bool erase(T x) { return tree.erase(x); }
562
563 int rnk(T x) { return tree.order_of_key(x) + 1; }
564
565 T kth(int x) { return *tree.find_by_order(x - 1); }
566
567 int size() { return tree.size(); }
568
569 bool empty() { return tree.empty(); }
570 };
571
572 using _Weight = long long;
573
574 class graph {
575 public:
576 struct edge {
577 int from, to;
579 edge(int from, int to, _Weight weight = 0) : from(from), to(to), weight(weight) {}
580 };
581
583 string operator()(edge edg) {
584 return std::to_string(edg.from) + " " + std::to_string(edg.to) + " " + std::to_string(edg.weight);
585 }
586 };
587
589 string operator()(edge edg) {
590 return std::to_string(edg.from) + " " + std::to_string(edg.to);
591 }
592 };
593
594 private:
595 struct chain_node {
596 int nxt, to;
597 _Weight w;
598 chain_node() {}
599 chain_node(int nxt, int to, _Weight w) : nxt(nxt), to(to), w(w) {}
600 };
601 std::vector<chain_node> chain;
602 std::vector<int> head;
603 std::vector<std::map<int, bool>> edge_map;
604 std::vector<edge> edge_vct;
605
606 public:
607 int N;
608
610
612
613 graph(int N, bool directed = false, bool enable_edge_map = true) {
614 err_positive_checker(N, __func__, "N");
615 this->N = N;
616 this->directed = directed;
617 this->enable_edge_map = enable_edge_map;
618 head = std::vector<int>(N + 1, -1);
619 edge_map = std::vector<std::map<int, bool>>(N + 1);
620 }
621
622 void add(edge edg, bool __add_vector = true) {
623 err_inrange_checker(edg.from, 0, N, __func__, "edg.from");
624 err_inrange_checker(edg.to, 0, N, __func__, "edg.to");
625 chain.push_back(chain_node(head[edg.from], edg.to, edg.weight));
626 head[edg.from] = chain.size() - 1;
627 if (!directed && __add_vector) add(edge(edg.to, edg.from, edg.weight), false);
628 if (__add_vector) edge_vct.push_back(edg);
629 if (enable_edge_map) edge_map[edg.from][edg.to] = true;
630 }
631
632 void add(int from, int to, _Weight weight = 0) {
633 add(edge(from, to, weight));
634 }
635
636 bool has_edge(edge edg) {
637 if (!enable_edge_map) raise(carefree_unsupported_operation("has_edge : edge map is not enabled"));
638 return edge_map[edg.from][edg.to];
639 }
640
641 bool has_edge(int from, int to) {
642 return has_edge(edge(from, to));
643 }
644
645 std::vector<edge> get_edges() {
646 return edge_vct;
647 }
648
649 std::vector<edge> get_edges(int from) {
650 err_inrange_checker(from, 0, N, __func__, "from");
651 std::vector<edge> edges;
652 for (int i = head[from]; ~i; i = chain[i].nxt) edges.push_back(edge(from, chain[i].to, chain[i].w));
653 return edges;
654 }
655
656 template <class T = weighted_output>
657 string to_string(bool shuffle = false) {
658 std::vector<edge> edges = get_edges();
659 if (shuffle) std::shuffle(edges.begin(), edges.end(), public_random_engine);
660 string str;
661 for (auto it = edges.begin(); it != edges.end(); ++it) {
662 str += T()(*it);
663 if ((it + 1) != edges.end()) str += '\n';
664 }
665 return str;
666 }
667 };
668
670
672
674
675 bool is_tree(graph g) {
676 std::vector<int> fa(g.N + 1);
677 for (int i = 1; i <= g.N; i++) fa[i] = i;
678 auto edges = g.get_edges();
679 if (edges.size() != (unsigned)(g.N - 1)) return false;
680 std::function<int(int)> find = [&](int x) {
681 return fa[x] == x ? x : fa[x] = find(fa[x]);
682 };
683 for (auto i : edges) {
684 int u = i.from, v = i.to;
685 if (find(u) == find(v)) return false;
686 fa[find(u)] = find(v);
687 }
688 return true;
689 }
690
692 std::vector<int> perm;
693 for (int i = 1; i <= g.N; i++) perm.push_back(i);
694 std::shuffle(perm.begin(), perm.end(), public_random_engine);
695 graph new_(g.N, g.directed, g.enable_edge_map);
696 for (auto i : g.get_edges()) {
697 new_.add(perm[i.from - 1], perm[i.to - 1], i.weight);
698 }
699 return new_;
700 }
701
702 graph prufer_decode(int n, std::vector<int> prufer, _Weight weightL = 0, _Weight weightR = 0) {
703 std::vector<int> deg(n + 1, 1);
704 prufer.insert(prufer.begin(), 0);
705 graph g(n, false);
706 if (prufer.size() != (unsigned)(n - 1)) raise(carefree_invalid_argument("prufer_decode : prufer size must be n-1"));
707 for (int i = 1; i <= (n - 2); i++) {
708 err_inrange_checker(prufer[i], 1, n, __func__, "prufer[" + std::to_string(i) + "]");
709 }
710 for (int i = 1; i <= (n - 2); i++) deg[prufer[i]]++;
711 int ptr = 1, leaf = 0;
712 while (deg[ptr] != 1) ptr++;
713 leaf = ptr;
714 for (int i = 1; i <= (n - 2); i++) {
715 int v = prufer[i];
716 g.add(v, leaf, randint(weightL, weightR));
717 if (--deg[v] == 1 && v < ptr)
718 leaf = v;
719 else {
720 ptr++;
721 while (deg[ptr] != 1) ptr++;
722 leaf = ptr;
723 }
724 }
725 g.add(n, leaf, randint(weightL, weightR));
726 return g;
727 }
728
729 std::vector<int> get_depth(graph g) {
730 std::queue<int> q;
731 std::vector<int> depth(g.N + 1);
732 q.push(1);
733 depth[1] = 1;
734 while (!q.empty()) {
735 auto u = q.front();
736 q.pop();
737 for (auto i : g.get_edges(u)) {
738 if (!depth[i.to]) {
739 depth[i.to] = depth[u] + 1;
740 q.push(i.to);
741 }
742 }
743 }
744 return depth;
745 }
746
748 auto depth = get_depth(tree);
749 graph g(tree.N, true);
750 for (auto i : tree.get_edges()) {
751 int u = i.from, v = i.to;
752 auto w = i.weight;
753 if (depth[u] < depth[v]) std::swap(u, v);
754 g.add(u, v, w);
755 }
756 return g;
757 }
758
760 auto depth = get_depth(tree);
761 graph g(tree.N, true);
762 for (auto i : tree.get_edges()) {
763 int u = i.from, v = i.to;
764 auto w = i.weight;
765 if (depth[u] > depth[v]) std::swap(u, v);
766 g.add(u, v, w);
767 }
768 return g;
769 }
770
771 graph lowhigh(int n, double low, double high, _Weight weightL = 0, _Weight weightR = 0) {
772 graph g(n, false);
773 for (int i = 2; i <= n; i++) {
774 int fa = randint(std::max((int)((i - 1) * low), 1), std::min((int)((i - 1) * high), i - 1));
775 g.add(fa, i, randint(weightL, weightR));
776 }
777 return g;
778 }
779
780 graph naive_tree(int n, _Weight weightL = 0, _Weight weightR = 0) {
781 return lowhigh(n, 0, 1, weightL, weightR);
782 }
783
784 graph tail(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
785 graph g(n, false);
786 for (int i = 2; i <= n; i++) {
787 int fa = randint(std::max(i - k, 1), i - 1);
788 g.add(fa, i, randint(weightL, weightR));
789 }
790 return g;
791 }
792
793 graph chain(int n, _Weight weightL = 0, _Weight weightR = 0) {
794 return tail(n, 1, weightL, weightR);
795 }
796
797 graph star(int n, _Weight weightL = 0, _Weight weightR = 0) {
798 graph g(n, false);
799 for (int i = 2; i <= n; i++) {
800 g.add(1, i, randint(weightL, weightR));
801 }
802 return g;
803 }
804
805 graph flower(int n, _Weight weightL = 0, _Weight weightR = 0) {
806 return star(n, weightL, weightR);
807 }
808
809 graph max_degree(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
810 graph g(n, false);
812 tree.insert({1, 0});
813 for (int i = 2; i <= n; i++) {
814 auto fa = tree.kth(randint(1, tree.size()));
815 tree.erase(fa);
816 if (fa.second < k) tree.insert({fa.first, fa.second + 1});
817 g.add(fa.first, i, randint(weightL, weightR));
818 tree.insert({i, 0});
819 }
820 return g;
821 }
822
823 graph binary_tree(int n, _Weight weightL = 0, _Weight weightR = 0) {
824 return max_degree(n, 3, weightL, weightR);
825 }
826
827 graph chain_star(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
828 graph g(n, false);
829 for (int i = 2; i <= k; i++) g.add(i - 1, i, randint(weightL, weightR));
830 for (int i = k + 1; i <= n; i++) g.add(randint(1, k), i, randint(weightL, weightR));
831 return g;
832 }
833
834 graph silkworm(int n, _Weight weightL = 0, _Weight weightR = 0) {
835 graph g(n, false);
836 for (int i = 2; i <= (n >> 1); i++) g.add(i - 1, i, randint(weightL, weightR));
837 for (int i = (n >> 1) + 1; i <= (n >> 1) << 1; i++) g.add(i - (n >> 1), i, randint(weightL, weightR));
838 if (((n >> 1) << 1) != n) g.add(randint(1, n - 1), n, randint(weightL, weightR));
839 return g;
840 }
841
842 graph firecrackers(int n, _Weight weightL = 0, _Weight weightR = 0) {
843 graph g(n, false);
844 int tmp = n / 3;
845 for (int i = 2; i <= tmp; i++) g.add(i - 1, i, randint(weightL, weightR));
846 for (int i = tmp + 1; i <= tmp * 2; i++) g.add(i - tmp, i, randint(weightL, weightR));
847 for (int i = (tmp << 1) + 1; i <= tmp * 3; i++) g.add(i - (tmp << 1), i, randint(weightL, weightR));
848 for (int i = (tmp * 3 + 1); i <= n; i++) g.add(randint(1, i - 1), i, randint(weightL, weightR));
849 return g;
850 }
851
852 graph complete(int n, int k, _Weight weightL = 0, _Weight weightR = 0) {
853 graph g(n, false);
854 std::queue<int> q;
855 q.push(1);
856 int tot = 1;
857 while (!q.empty()) {
858 int u = q.front();
859 q.pop();
860 int bound = std::min(tot + k - 1, n);
861 for (int i = tot + 1; i <= bound; i++) {
862 g.add(u, (++tot), randint(weightL, weightR));
863 q.push(i);
864 }
865 }
866 return g;
867 }
868
869 graph complete_binary(int n, _Weight weightL = 0, _Weight weightR = 0) {
870 return complete(n, 3, weightL, weightR);
871 }
872
873 graph random_tree(int n, _Weight weightL = 0, _Weight weightR = 0) {
874 graph g(n, false);
875 std::vector<int> prufer;
876 for (int i = 1; i <= n - 2; i++) prufer.push_back(randint(1, n));
877 return prufer_decode(n, prufer, weightL, weightR);
878 }
879
880 graph dag(int n, int m, bool repeat_edges = false, _Weight weightL = 0, _Weight weightR = 0) {
881 graph tree = random_tree(n, weightL, weightR);
882 auto depth = get_depth(tree);
883 graph ret = externalize(tree);
884 err_geq_checker(m, n - 1, __func__, "m");
885 for (int i = n; i <= m; i++) {
886 while (true) {
887 int u = randint(1, n);
888 int v = randint(1, n);
889 if (u == v) continue;
890 if (depth[u] > depth[v]) std::swap(u, v);
891 if (!repeat_edges && ret.has_edge(u, v)) continue;
892 ret.add(u, v, randint(weightL, weightR));
893 break;
894 }
895 }
896 return ret;
897 }
898
899 graph connected_undirected_graph(int n, int m, bool repeat_edges = false, bool self_loop = false, _Weight weightL = 0, _Weight weightR = 0) {
900 graph tree = random_tree(n, weightL, weightR);
901 graph ret = tree;
902 err_geq_checker(m, n - 1, __func__, "m");
903 for (int i = n; i <= m; i++) {
904 while (true) {
905 int u = randint(1, n);
906 int v = randint(1, n);
907 if (!self_loop && u == v) continue;
908 if (!repeat_edges && ret.has_edge(u, v)) continue;
909 ret.add(u, v, randint(weightL, weightR));
910 break;
911 }
912 }
913 return ret;
914 }
915
916 graph connected_directed_graph(int n, int m, bool repeat_edges = false, bool self_loop = false, _Weight weightL = 0, _Weight weightR = 0) {
917 graph tree = random_tree(n, weightL, weightR);
918 graph ret = externalize(tree);
919 err_geq_checker(m, n - 1, __func__, "m");
920 for (int i = n; i <= m; i++) {
921 while (true) {
922 int u = randint(1, n);
923 int v = randint(1, n);
924 if (!self_loop && u == v) continue;
925 if (!repeat_edges && ret.has_edge(u, v)) continue;
926 ret.add(u, v, randint(weightL, weightR));
927 break;
928 }
929 }
930 return ret;
931 }
932
933 graph random_graph(int n, int m, bool directed = true, bool repeat_edges = false, bool self_loop = false, _Weight weightL = 0, _Weight weightR = 0) {
934 graph ret(n, directed);
935 for (int i = 1; i <= m; i++) {
936 while (true) {
937 int u = randint(1, n);
938 int v = randint(1, n);
939 if (!self_loop && u == v) continue;
940 if (!repeat_edges && ret.has_edge(u, v)) continue;
941 ret.add(u, v, randint(weightL, weightR));
942 break;
943 }
944 }
945 return ret;
946 }
947
949 private:
950 class file_writer {
951 private:
952 std::FILE* fp;
953 void _ein() {
954 if (fp == nullptr) raise(carefree_file_exception("testcase_writer::file_writer::_ein : file is not opened."));
955 }
956
957 public:
958 string _filename;
959 file_writer() {}
960 file_writer(const char* filename) {
961 _filename = filename;
962 if (std::strlen(filename)) {
963 fp = std::fopen(filename, "w");
964 if (fp == NULL) raise(carefree_file_exception("testcase_writer::file_writer::file_writer : cannot open file " + _filename));
965 } else
966 fp = nullptr;
967 }
968 void close() {
969 if (fp != nullptr) std::fclose(fp);
970 }
971 ~file_writer() { close(); }
972 void writeChar(char val) {
973 _ein();
974 std::fputc(val, fp);
975 }
976 template <class T>
977 void writeInteger(T val) {
978 _ein();
979 if (val < 0) {
980 val = -val;
981 writeChar('-');
982 }
983 if (val == 0) {
984 writeChar('0');
985 return;
986 }
987 if (val >= 10) writeInteger(val / 10);
988 writeChar('0' + val % 10);
989 }
990 void writeString(const char* val) {
991 _ein();
992 const char* ptr = val;
993 while (*ptr != '\0') writeChar(*(ptr++));
994 }
995 void writeString(string val) {
996 _ein();
997 writeString(val.c_str());
998 }
999 void flush() {
1000 _ein();
1001 std::fflush(fp);
1002 }
1003 };
1004
1005 file_writer* fin;
1006 file_writer* fout;
1007 bool locked;
1008
1009 void _eil() {
1010 if (locked) raise(carefree_unsupported_operation("testcase_writer::_eil : input/output file has already locked."));
1011 }
1012 void lock() { locked = true; }
1013
1014 public:
1015 testcase_writer(string input_file, string output_file = "") {
1016 fin = new file_writer(input_file.c_str());
1017 fout = new file_writer(output_file.c_str());
1018 locked = false;
1019 }
1020
1021 testcase_writer(string file_prefix, unsigned data_id, string input_suffix = ".in", string output_suffix = ".out", bool disable_output = false) {
1022 fin = new file_writer((file_prefix + std::to_string(data_id) + input_suffix).c_str());
1023 if (!disable_output)
1024 fout = new file_writer((file_prefix + std::to_string(data_id) + output_suffix).c_str());
1025 else
1026 fout = new file_writer("");
1027 locked = false;
1028 }
1029
1030 testcase_writer(string file_prefix, unsigned subtask_id, unsigned task_id, string input_suffix = ".in", string output_suffix = ".out", bool disable_output = false) {
1031 fin = new file_writer((file_prefix + std::to_string(subtask_id) + "-" + std::to_string(task_id) + input_suffix).c_str());
1032 if (!disable_output)
1033 fout = new file_writer((file_prefix + std::to_string(subtask_id) + "-" + std::to_string(task_id) + output_suffix).c_str());
1034 else
1035 fout = new file_writer("");
1036 locked = false;
1037 }
1038
1039 void input_write(char val) {
1040 _eil();
1041 fin->writeChar(val);
1042 }
1043 void output_write(char val) {
1044 _eil();
1045 fout->writeChar(val);
1046 }
1047
1048 void input_write(int val) {
1049 _eil();
1050 fin->writeInteger(val);
1051 }
1052 void output_write(int val) {
1053 _eil();
1054 fout->writeInteger(val);
1055 }
1056
1057 void output_write(long long val) {
1058 _eil();
1059 fout->writeInteger(val);
1060 }
1061 void input_write(long long val) {
1062 _eil();
1063 fin->writeInteger(val);
1064 }
1065
1066 void input_write(unsigned int val) {
1067 _eil();
1068 fin->writeInteger(val);
1069 }
1070 void output_write(unsigned int val) {
1071 _eil();
1072 fout->writeInteger(val);
1073 }
1074
1075 void input_write(unsigned long long val) {
1076 _eil();
1077 fin->writeInteger(val);
1078 }
1079 void output_write(unsigned long long val) {
1080 _eil();
1081 fout->writeInteger(val);
1082 }
1083
1084 void input_write(unsigned short val) {
1085 _eil();
1086 fin->writeInteger(val);
1087 }
1088 void output_write(unsigned short val) {
1089 _eil();
1090 fout->writeInteger(val);
1091 }
1092
1093 void input_write(short val) {
1094 _eil();
1095 fin->writeInteger(val);
1096 }
1097 void output_write(short val) {
1098 _eil();
1099 fout->writeInteger(val);
1100 }
1101
1102#ifdef CAREFREE_INT128_SUPPORT
1103 void input_write(__int128 val) {
1104 _eil();
1105 fin->writeInteger(val);
1106 }
1107 void output_write(__int128 val) {
1108 _eil();
1109 fout->writeInteger(val);
1110 }
1111
1112 void input_write(unsigned __int128 val) {
1113 _eil();
1114 fin->writeInteger(val);
1115 }
1116 void output_write(unsigned __int128 val) {
1117 _eil();
1118 fout->writeInteger(val);
1119 }
1120#endif
1121 void input_write(string val) {
1122 _eil();
1123 fin->writeString(val);
1124 }
1125 void output_write(string val) {
1126 _eil();
1127 fout->writeString(val);
1128 }
1129
1130 void input_write(const char* val) {
1131 _eil();
1132 fin->writeString(val);
1133 }
1134 void output_write(const char* val) {
1135 _eil();
1136 fout->writeString(val);
1137 }
1138
1139 void input_write(bool val) {
1140 _eil();
1141 fin->writeString(val ? "true" : "false");
1142 }
1143 void output_write(bool val) {
1144 _eil();
1145 fout->writeString(val ? "true" : "false");
1146 }
1147
1148 template <class T>
1149 void input_write(std::vector<T> val) {
1150 _eil();
1151 for (auto it = val.begin(); it != val.end(); ++it) {
1152 input_write(*it);
1153 if ((it + 1) != val.end()) input_write(' ');
1154 }
1155 }
1156 template <class T>
1157 void output_write(std::vector<T> val) {
1158 _eil();
1159 for (auto it = val.begin(); it != val.end(); ++it) {
1160 output_write(*it);
1161 if ((it + 1) != val.end()) output_write(' ');
1162 }
1163 }
1164
1165 void input_write(graph val) {
1166 _eil();
1167 input_write(val.to_string());
1168 }
1170 _eil();
1171 output_write(val.to_string());
1172 }
1173
1174 void input_write(edge val) {
1175 _eil();
1176 input_write(weighted_output()(val));
1177 }
1178 void output_write(edge val) {
1179 _eil();
1180 output_write(weighted_output()(val));
1181 }
1182
1183 template <class T, typename... Args>
1184 void input_write(T val, Args... args) {
1185 _eil();
1186 input_write(val);
1187 input_write(' ');
1188 input_write(args...);
1189 }
1190
1191 template <class T, typename... Args>
1192 void output_write(T val, Args... args) {
1193 _eil();
1194 output_write(val);
1195 output_write(' ');
1196 output_write(args...);
1197 }
1198
1199 void input_writeln() { input_write('\n'); }
1200 void output_writeln() { output_write('\n'); }
1201
1202 template <class T>
1203 void input_writeln(T val) {
1204 _eil();
1205 input_write(val);
1206 input_write('\n');
1207 }
1208
1209 template <class T>
1210 void output_writeln(T val) {
1211 _eil();
1212 output_write(val);
1213 output_write('\n');
1214 }
1215
1216 template <class T, typename... Args>
1217 void input_writeln(T val, Args... args) {
1218 _eil();
1219 input_write(val);
1220 input_write(' ');
1221 input_writeln(args...);
1222 }
1223
1224 template <class T, typename... Args>
1225 void output_writeln(T val, Args... args) {
1226 _eil();
1227 output_write(val);
1228 output_write(' ');
1229 output_writeln(args...);
1230 }
1231
1232 bool is_locked() { return locked; }
1233
1234 void input_flush() { fin->flush(); }
1235 void output_flush() { fout->flush(); }
1236
1237 void output_gen(string program) {
1238 _eil();
1239 fin->close();
1240 fout->close();
1241 lock();
1242 int stdin_ = dup(fileno(stdin));
1243 freopen(fin->_filename.c_str(), "r", stdin);
1244 int stdout_ = dup(fileno(stdout));
1245 freopen(fout->_filename.c_str(), "w", stdout);
1246 int returnid = std::system(program.c_str());
1247 if (returnid != 0) raise(carefree_runtime_exception("testcase_writer::output_gen : program exited with non-zero return code"));
1248 dup2(stdin_, fileno(stdin));
1249 dup2(stdout_, fileno(stdout));
1250 }
1251
1252 string input_name() {
1253 return fin->_filename;
1254 }
1255
1256 string output_name() {
1257 return fout->_filename;
1258 }
1259
1260 void close() {
1261 delete fin;
1262 delete fout;
1263 fin = nullptr;
1264 fout = nullptr;
1265 }
1266
1268 if (fin != nullptr) delete fin;
1269 if (fout != nullptr) delete fout;
1270 }
1271 };
1272
1273 using testcase_io [[deprecated("use testcase_writer instead.")]] = testcase_writer;
1274
1276 private:
1277 string content;
1278
1279 public:
1281 content = "";
1282 }
1283
1284 void add(string input_name, int time_limit, int memory_limit, int score = -1, int subtask_id = -1) {
1285 const string space = " ";
1286 string current = "";
1287 current += (input_name + ":\n");
1288 current += (space + "timeLimit: " + std::to_string(time_limit) + "\n");
1289 current += (space + "memoryLimit: " + std::to_string(memory_limit) + "\n");
1290 if (score != -1) current += (space + "score: " + std::to_string(score) + "\n");
1291 if (subtask_id != -1) current += (space + "subtaskId: " + std::to_string(subtask_id) + "\n");
1292 current += "\n";
1293 content += current;
1294 }
1295
1296 void save(string filename = "config.yml") {
1297 FILE* fobj = fopen(filename.c_str(), "w");
1298 if (fobj == NULL) raise(carefree_file_exception("luogu_testcase_config_writer::save : failed to open file " + filename));
1299 fputs(content.c_str(), fobj);
1300 if (fclose(fobj) != 0) raise(carefree_file_exception("luogu_testcase_config_writer::save : failed to close file " + filename));
1301 }
1302
1303 string to_string() {
1304 return content;
1305 }
1306 };
1307
1309 public:
1310 virtual void close() = 0;
1311 virtual void kill() = 0;
1312 virtual bool is_running() const = 0;
1313 virtual int return_code() const = 0;
1314 virtual int pid() const = 0;
1315 virtual size_t memory() const = 0;
1316 };
1317
1318#ifdef _WIN32
1319 class process_win : public process_base {
1320 private:
1321 string command_, input_file_, output_file_;
1322 HANDLE process_handle_ = nullptr, hOutputFile = nullptr, hInputFile = nullptr;
1323
1324 public:
1325 process_win(const string& cmd, const string& input = "", const string& output = "")
1326 : command_(cmd), input_file_(input), output_file_(output) {
1327 _STARTUPINFOA si;
1328 PROCESS_INFORMATION pi;
1329 ZeroMemory(&si, sizeof(si));
1330 si.cb = sizeof(si);
1331 ZeroMemory(&pi, sizeof(pi));
1332 if (!input_file_.empty()) {
1333 SECURITY_ATTRIBUTES saAttr;
1334 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1335 saAttr.bInheritHandle = TRUE;
1336 saAttr.lpSecurityDescriptor = NULL;
1337 hInputFile = CreateFileA(input_file_.c_str(), GENERIC_READ, 0, &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
1338 if (hInputFile == INVALID_HANDLE_VALUE) {
1339 raise(carefree_file_exception("ProcessWin : failed to open input file " + input_file_));
1340 }
1341 si.hStdInput = hInputFile;
1342 }
1343 if (!output_file_.empty()) {
1344 SECURITY_ATTRIBUTES saAttr;
1345 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
1346 saAttr.bInheritHandle = TRUE;
1347 saAttr.lpSecurityDescriptor = NULL;
1348 hOutputFile = CreateFileA(output_file_.c_str(), GENERIC_WRITE, 0, &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
1349 if (hOutputFile == INVALID_HANDLE_VALUE) {
1350 raise(carefree_file_exception("ProcessWin : failed to open output file " + output_file_));
1351 }
1352 si.hStdOutput = hOutputFile;
1353 si.hStdError = NULL;
1354 si.dwFlags |= STARTF_USESTDHANDLES;
1355 }
1356 if (!CreateProcessA(NULL, (char*)(command_.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
1357 raise(carefree_system_exception("ProcessWin : failed to create process " + command_));
1358 }
1359 CloseHandle(pi.hThread);
1360 process_handle_ = pi.hProcess;
1361 }
1362
1363 void close() {
1364 if (process_handle_ != nullptr) {
1365 CloseHandle(process_handle_);
1366 }
1367 if (hInputFile != nullptr) CloseHandle(hInputFile);
1368 if (hOutputFile != nullptr) {
1369 FlushFileBuffers(hOutputFile);
1370 CloseHandle(hOutputFile);
1371 }
1372 }
1373
1375 close();
1376 }
1377
1378 void kill() {
1379 if (is_running())
1380 TerminateProcess(process_handle_, 1);
1381 }
1382
1383 bool is_running() const {
1384 DWORD exit_code;
1385 if (GetExitCodeProcess(process_handle_, &exit_code) && exit_code == STILL_ACTIVE) {
1386 return true;
1387 }
1388 return false;
1389 }
1390
1391 int return_code() const {
1392 DWORD exit_code;
1393 if (!GetExitCodeProcess(process_handle_, &exit_code) || exit_code == STILL_ACTIVE) {
1394 raise(carefree_system_exception("return_code : process has not yet terminated."));
1395 }
1396 return static_cast<int>(exit_code);
1397 }
1398
1399 int pid() const {
1400 return (int)GetProcessId(process_handle_);
1401 }
1402
1403 size_t memory() const {
1404#ifdef PSAPI_LINKED
1405 PROCESS_MEMORY_COUNTERS_EX pmc;
1406 ZeroMemory(&pmc, sizeof(pmc));
1407 pmc.cb = sizeof(pmc);
1408 if (!GetProcessMemoryInfo(process_handle_, (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc))) {
1409 raise(carefree_system_exception("memory : failed to retrieve process memory information."));
1410 return 0ull;
1411 }
1412 return (size_t)pmc.PrivateUsage;
1413#else
1414 return 0ull;
1415#endif
1416 }
1417 };
1419#endif
1420
1435
1437 switch (type) {
1438 case Accepted:
1439 return "Accepted";
1440 case WrongAnswer:
1441 return "Wrong Answer";
1442 case TimeLimitExceeded:
1443 return "Time Limit Exceeded";
1445 return "Memory Limit Exceeded";
1446 case RuntimeError:
1447 return "Runtime Error";
1448 case CompileError:
1449 return "Compile Error";
1450 case PresentationError:
1451 return "Presentation Error";
1453 return "Output Limit Exceeded";
1454 case UnknownError:
1455 return "Unknown Error";
1456 case JudgeFailed:
1457 return "Judge Failed";
1458 case PartiallyCorrect:
1459 return "Partially Correct";
1460 case Skipped:
1461 return "Skipped";
1462 default:
1463 return "Unknown Error";
1464 }
1465 return "Unknown Error";
1466 }
1467
1469 switch (type) {
1470 case Accepted:
1471 return "AC";
1472 case WrongAnswer:
1473 return "WA";
1474 case TimeLimitExceeded:
1475 return "TLE";
1477 return "MLE";
1478 case RuntimeError:
1479 return "RE";
1480 case CompileError:
1481 return "CE";
1482 case PresentationError:
1483 return "PE";
1485 return "OLE";
1486 case UnknownError:
1487 return "UKE";
1488 case JudgeFailed:
1489 return "JF";
1490 case PartiallyCorrect:
1491 return "PC";
1492 case Skipped:
1493 return "SK";
1494 default:
1495 return "UKE";
1496 }
1497 return "UKE";
1498 }
1499
1500 using ull = unsigned long long;
1501
1504 string message;
1505 double ratio;
1508
1509 string to_str() const {
1510 string ret = jrt2s(type) + "\t" + message + "\t";
1511 ret += std::to_string(time / 1000.0 / 1000.0) + "ms\t";
1512 ret += std::to_string(memory / 1024.0 / 1024.0) + "MiB\t";
1513 ret += std::to_string(ratio * 100) + "%";
1514 return ret;
1515 }
1516 };
1517
1518 std::vector<string> __split(const string& str, string delims) {
1519 std::vector<string> tokens;
1520 string tmp;
1521 for (auto it = str.begin(); it != str.end(); ++it) {
1522 if (delims.find(*it) != string::npos) {
1523 tokens.push_back(tmp);
1524 tmp.clear();
1525 continue;
1526 }
1527 tmp += *it;
1528 }
1529 tokens.push_back(tmp);
1530 return tokens;
1531 }
1532
1534 public:
1535 class readable {
1536 public:
1537 virtual string read() = 0;
1538 };
1539
1540 class file : public readable {
1541 private:
1542 string filename_;
1543
1544 public:
1545 file(const string& filename) : filename_(filename) {}
1546 string read() {
1547 std::ifstream file(filename_, std::ios::in);
1548 if (!file.is_open()) {
1549 Sleep(1000);
1550 file.open(filename_, std::ios::in);
1551 if (!file.is_open()) raise(carefree_file_exception("read : failed to open file " + filename_));
1552 }
1553 string content;
1554 while (file.good()) {
1555 string line;
1556 std::getline(file, line);
1557 content += line + '\n';
1558 }
1559 file.close();
1560 return content;
1561 }
1562 };
1563
1564 class text : public readable {
1565 private:
1566 string content_;
1567
1568 public:
1569 text(const string& content) : content_(content) {}
1570 string read() { return content_; }
1571 };
1572
1573 virtual judge_result from_text(const string& text1, const string& text2) = 0;
1574
1575 virtual judge_result from_file(const string& filename1, const string& filename2) {
1576 return from_text(file(filename1).read(), file(filename2).read());
1577 }
1578
1579 template <class T1, class T2>
1581 return from_text(a.read(), b.read());
1582 }
1583
1584 virtual judge_result test(const string& input_path maybe_unused, const string& output_path, const string& answer_path) {
1585 return from_file(answer_path, output_path);
1586 }
1587 };
1588
1592
1594 public:
1595 judge_result from_text(const string& text1, const string& text2) {
1596 if (text1 == text2) {
1597 return {Accepted, "correct", 1.0, 0ull, 0ull};
1598 }
1599 return {WrongAnswer, "not correct", 0.0, 0ull, 0ull};
1600 }
1601 };
1602
1604 public:
1605 judge_result from_text(const string& text1, const string& text2) {
1606 auto lines1 = __split(text1, "\n");
1607 auto lines2 = __split(text2, "\n");
1608 if (lines1.size() != lines2.size()) {
1609 string errmsg = "expected " + std::to_string(lines1.size()) + " line(s), but got " + std::to_string(lines2.size()) + " line(s).";
1610 return {WrongAnswer, errmsg, 0.0, 0ull, 0ull};
1611 }
1612 for (ull i = 0; i < lines1.size(); ++i) {
1613 if (lines1[i] != lines2[i]) {
1614 string errmsg = "at line " + std::to_string(i + 1);
1615 errmsg += ", expected \"" + lines1[i] + "\"";
1616 errmsg += ", but got \"" + lines2[i] + "\".";
1617 return {WrongAnswer, errmsg, 0.0, 0ull, 0ull};
1618 }
1619 }
1620 return {Accepted, "correct", 1.0, 0ull, 0ull};
1621 }
1622 };
1623
1625 public:
1626 judge_result from_text(const string& text1, const string& text2) {
1627 auto tokens1_ = __split(text1, " \t\r\n");
1628 auto tokens2_ = __split(text2, " \t\r\n");
1629 std::vector<string> tokens1, tokens2;
1630 std::copy_if(tokens1_.begin(), tokens1_.end(), std::back_inserter(tokens1), [](const string& s) { return s != ""; });
1631 std::copy_if(tokens2_.begin(), tokens2_.end(), std::back_inserter(tokens2), [](const string& s) { return s != ""; });
1632 if (tokens1.size() != tokens2.size()) {
1633 string errmsg = "expected " + std::to_string(tokens1.size()) + " token(s), but got " + std::to_string(tokens2.size()) + " token(s).";
1634 return {WrongAnswer, errmsg, 0.0, 0, 0};
1635 }
1636 for (ull i = 0; i < tokens1.size(); ++i) {
1637 if (tokens1[i] != tokens2[i]) {
1638 string errmsg = "at token " + std::to_string(i + 1);
1639 errmsg += ", expected \"" + tokens1[i] + "\"";
1640 errmsg += ", but got \"" + tokens2[i] + "\".";
1641 return {WrongAnswer, errmsg, 0.0, 0ull, 0ull};
1642 }
1643 }
1644 return {Accepted, "correct", 1.0, 0ull, 0ull};
1645 }
1646 };
1647
1649 static ull id;
1650 return ++id;
1651 }
1652
1653 string quote(string s) {
1654 std::stringstream ss;
1655 ss << std::quoted(s);
1656 return ss.str();
1657 }
1658
1660 private:
1661 string testlib_path;
1662
1663 string extract_outcome(string xml) {
1664 size_t start_pos = xml.find("outcome = \"");
1665 if (start_pos == string::npos) return "";
1666 start_pos += 11;
1667 size_t end_pos = xml.find("\"", start_pos);
1668 if (end_pos == string::npos) return "";
1669 return xml.substr(start_pos, end_pos - start_pos);
1670 }
1671
1672 string extract_points(string xml) {
1673 size_t start_pos = xml.find("points = \"");
1674 if (start_pos == string::npos) return "";
1675 start_pos += 10;
1676 size_t end_pos = xml.find("\"", start_pos);
1677 if (end_pos == string::npos) return "";
1678 return xml.substr(start_pos, end_pos - start_pos);
1679 }
1680
1681 string extract_result(string xml) {
1682 size_t start_pos = xml.find("\">") + 2;
1683 if (start_pos == string::npos) return "";
1684 size_t end_pos = xml.rfind("</result>");
1685 if (end_pos == string::npos) return "";
1686 return xml.substr(start_pos, end_pos - start_pos);
1687 }
1688
1689 public:
1690 testlib_comparator(const string& testlib_path) {
1691 this->testlib_path = testlib_path;
1692 }
1693
1694 judge_result test(string input_path, string output_path, string answer_path) {
1695 string cmd = testlib_path + " ";
1696 cmd += quote(input_path) + " " + quote(output_path) + " " + quote(answer_path);
1697 cmd += " ";
1698 string xml_path = "carefree_testlib_report_" + std::to_string(nextid()) + ".xml";
1699 cmd += quote(xml_path) + " -appes";
1700 int ret = system(cmd.c_str());
1701 string content = file(xml_path).read();
1702 std::remove(xml_path.c_str());
1703 string outcome = extract_outcome(content);
1704 string message = extract_result(content);
1705 if (outcome.empty()) return {UnknownError, "cannot parse report file.", 0.0, 0ull, 0ull};
1706 if (outcome == "accepted")
1707 return {Accepted, message, 1.0, 0ull, 0ull};
1708 else if (outcome == "wrong-answer")
1709 return {WrongAnswer, message, 0.0, 0ull, 0ull};
1710 else if (outcome == "presentation-error")
1711 return {PresentationError, message, 0.0, 0ull, 0ull};
1712 else if (outcome == "points") {
1713 string points = extract_points(content);
1714 if (points.empty()) return {UnknownError, "cannot parse report file.", 0.0, 0ull, 0ull};
1715 return {PartiallyCorrect, message, std::stod(points), 0ull, 0ull};
1716 } else
1717 return {JudgeFailed, message, 0.0, 0ull, 0ull};
1718 }
1719
1720 judge_result from_text(const string& text1 maybe_unused, const string& text2 maybe_unused) {
1721 raise(carefree_unsupported_operation("testlib_comparator::from_text : unsupported from_text method."));
1722 return {UnknownError, "unsupported from_text method", 0.0, 0ull, 0ull};
1723 }
1724 };
1725
1726 struct limprog {
1727 string program;
1730
1731 limprog(string program, ull time, ull memory) : program(program), time(time), memory(memory) {}
1732 };
1733
1734 judge_result limited_run(limprog prog, const string& input_file, const string& output_file) {
1735 auto start = std::chrono::system_clock::now();
1736 ull memory = 0, tim = 0;
1737 process proc(prog.program, input_file, output_file);
1738 while (proc.is_running()) {
1739 auto now = std::chrono::system_clock::now();
1740 tim = std::chrono::duration_cast<std::chrono::nanoseconds>(now - start).count();
1741 if (tim > prog.time) {
1742 proc.kill();
1743 return {TimeLimitExceeded, "time limit exceeded.", 0.0, tim, memory};
1744 }
1745 memory = std::max(memory, proc.memory());
1746 if (memory > prog.memory) {
1747 proc.kill();
1748 return {MemoryLimitExceeded, "memory limit exceeded.", 0.0, tim, memory};
1749 }
1750 }
1751 if (proc.return_code() != 0) {
1752 return {RuntimeError, "program finished with exit non-zero code " + std::to_string(proc.return_code()) + ".", 0.0, tim, memory};
1753 }
1754 return {Accepted, "program finished successfully.", 1.0, tim, memory};
1755 }
1756
1757 bool is_file_creatable(string filename) {
1758 if (access(filename.c_str(), F_OK) != -1) return false;
1759 std::ofstream f(filename, std::ios::out);
1760 if (f.is_open()) {
1761 f.close();
1762 std::remove(filename.c_str());
1763 return true;
1764 }
1765 return false;
1766 };
1767
1768 template <class T>
1769 judge_result judge(limprog prog, const string& input_file, const string& answer_file, T cmp, bool ole_check = true) {
1770 string output_file;
1771 do {
1772 output_file = "carefree_output_" + std::to_string(nextid()) + ".out";
1773 } while (!is_file_creatable(output_file));
1774 judge_result ans = limited_run(prog, input_file, output_file);
1775 if (ans.type != Accepted) {
1776 std::remove(output_file.c_str());
1777 return ans;
1778 }
1779 if (ole_check) {
1780 struct stat output_stat {};
1781 stat(output_file.c_str(), &output_stat);
1782 struct stat answer_stat {};
1783 stat(answer_file.c_str(), &answer_stat);
1784 if (output_stat.st_size > answer_stat.st_size * 10) {
1785 std::remove(output_file.c_str());
1786 return {OutputLimitExceeded, "output limit exceeded.", 0.0, ans.time, ans.memory};
1787 }
1788 }
1789 judge_result ans2 = cmp.test(input_file, output_file, answer_file);
1790 std::remove(output_file.c_str());
1791 return {ans2.type, ans2.message, ans2.ratio, ans.time, ans.memory};
1792 }
1793
1794 template <class T1, class T2>
1795 bool combat(limprog champion, limprog challenger, T1 input_generator, T2 cmp, int times = -1, bool ole_check = true) {
1796 for (int i = 0; i != times; i++) {
1797 fprintf(stderr, "Round #%d : ", i + 1);
1798 string input_file = "";
1799 do {
1800 input_file = "carefree_input_" + std::to_string(nextid()) + ".in";
1801 } while (!is_file_creatable(input_file));
1802 testcase_writer writer(input_file, "");
1803 input_generator(writer);
1804 string answer_file;
1805 do {
1806 answer_file = "carefree_answer_" + std::to_string(nextid()) + ".ans";
1807 } while (!is_file_creatable(answer_file));
1808 auto ret = limited_run(champion, input_file, answer_file);
1809 if (ret.type != Accepted) {
1810 fprintf(stderr, "champion is lost.\n");
1811 fprintf(stderr, "%s\n", ret.to_str().c_str());
1812 fprintf(stderr, "please watch input file \"%s\" to check.", input_file.c_str());
1813 return false;
1814 }
1815 ret = judge(challenger, input_file, answer_file, cmp, ole_check = ole_check);
1816 if (ret.type != Accepted) {
1817 fprintf(stderr, "challenger is lost.\n");
1818 fprintf(stderr, "%s\n", ret.to_str().c_str());
1819 fprintf(stderr, "please watch input file \"%s\" to check.", input_file.c_str());
1820 return false;
1821 }
1822 std::remove(answer_file.c_str());
1823 std::remove(input_file.c_str());
1824 fprintf(stderr, "champion and challenger are still alive.\n");
1825 }
1826 return true;
1827 }
1828
1829 void listdir(string path, std::vector<string>& files) {
1830 intptr_t hFile = 0;
1831 _finddata_t fileinfo;
1832 if ((hFile = _findfirst(path.append("/*").c_str(), &fileinfo)) != -1) {
1833 while (_findnext(hFile, &fileinfo) == 0) {
1834 if (strcmp(fileinfo.name, ".."))
1835 files.push_back(fileinfo.name);
1836 }
1837 _findclose(hFile);
1838 }
1839 }
1840
1842 return getcwd(NULL, 0);
1843 }
1844
1846 std::vector<string> files;
1847 listdir(working_directory(), files);
1848 int cnt = 0;
1849 for (auto& i : files) {
1850 if (i.find("carefree_input_") == 0 ||
1851 i.find("carefree_output_") == 0 ||
1852 i.find("carefree_answer_") == 0 ||
1853 i.find("carefree_testlib_report_") == 0) {
1854 std::remove(i.c_str());
1855 cnt++;
1856 }
1857 }
1858 return cnt;
1859 }
1860
1868
1877
1878 namespace cpp_warnings {
1879 const int Wnone = 0;
1880 const int Wall = 1;
1881 const int Wextra = 2;
1882 const int Wpedantic = 4;
1883 const int Werror = 8;
1884
1885 using type = int;
1886 }; // namespace cpp_warnings
1887
1889 private:
1890 string gcc_path = "g++";
1891 string filename;
1892 string output_name;
1893 optimization_type opti = O2;
1894 cpp_version cpp = Cpp14;
1895 cpp_warnings::type warning = 0;
1896 bool link_static = false, debug = false;
1897 std::vector<string> include_files, include_dirs, link_libs;
1898 std::map<string, string> defintions;
1899
1900 public:
1901 gcc_compile(string filename, string output_name) : filename(filename), output_name(output_name) {};
1902
1903 gcc_compile& gcc(string gcc_path) {
1904 this->gcc_path = gcc_path;
1905 return *this;
1906 }
1907
1909 this->opti = opti;
1910 return *this;
1911 }
1912
1914 this->cpp = cpp;
1915 return *this;
1916 }
1917
1919 this->warning = warning;
1920 return *this;
1921 }
1922
1924 this->warning |= warning;
1925 return *this;
1926 }
1927
1928 gcc_compile& linking_static(bool link_static = true) {
1929 this->link_static = link_static;
1930 return *this;
1931 }
1932
1933 gcc_compile& include_file(string filename) {
1934 this->include_files.push_back(filename);
1935 return *this;
1936 }
1937
1938 gcc_compile& define(string key, string value = "") {
1939 this->defintions[key] = value;
1940 return *this;
1941 }
1942
1944 this->include_dirs.push_back(dir);
1945 return *this;
1946 }
1947
1948 gcc_compile& link(string lib) {
1949 this->link_libs.push_back(lib);
1950 return *this;
1951 }
1952
1953 gcc_compile& debug_mode(bool debug = true) {
1954 this->debug = debug;
1955 return *this;
1956 }
1957
1958 string command() {
1959 string cmd = gcc_path + " " + quote(filename);
1960 if (debug) {
1961 cmd += " -g";
1962 }
1963 switch (opti) {
1964 case O0:
1965 cmd += " -O0";
1966 case O1:
1967 cmd += " -O1";
1968 break;
1969 case O2:
1970 cmd += " -O2";
1971 break;
1972 case O3:
1973 cmd += " -O3";
1974 break;
1975 case Ofast:
1976 cmd += " -Ofast";
1977 break;
1978 }
1979 switch (cpp) {
1980 case Cpp98:
1981 cmd += " -std=c++98";
1982 break;
1983 case Cpp03:
1984 cmd += " -std=c++03";
1985 break;
1986 case Cpp11:
1987 cmd += " -std=c++11";
1988 break;
1989 case Cpp14:
1990 cmd += " -std=c++14";
1991 break;
1992 case Cpp17:
1993 cmd += " -std=c++17";
1994 break;
1995 case Cpp20:
1996 cmd += " -std=c++20";
1997 break;
1998 }
1999
2000 if (warning == cpp_warnings::Wnone) {
2001 cmd += " -w";
2002 } else {
2003 if (warning & cpp_warnings::Wall) {
2004 cmd += " -Wall";
2005 }
2006 if (warning & cpp_warnings::Wextra) {
2007 cmd += " -Wextra";
2008 }
2009 if (warning & cpp_warnings::Wpedantic) {
2010 cmd += " -pedantic";
2011 }
2012 if (warning & cpp_warnings::Werror) {
2013 cmd += " -Werror";
2014 }
2015 }
2016
2017 for (auto& i : include_files) {
2018 cmd += " -include " + i;
2019 }
2020
2021 for (auto& i : include_dirs) {
2022 cmd += " -I" + i;
2023 }
2024
2025 for (auto& i : defintions) {
2026 if (i.second.empty())
2027 cmd += " -D" + i.first;
2028 else
2029 cmd += " -D" + i.first + "=" + i.second;
2030 }
2031
2032 for (auto& i : link_libs) {
2033 cmd += " -l" + i;
2034 }
2035
2036 if (link_static) {
2037 cmd += " -static";
2038 }
2039
2040 cmd += " -o " + quote(output_name);
2041
2042 return cmd;
2043 }
2044
2046 return std::system(this->command().c_str()) == 0 ? judge_result_type::Accepted : judge_result_type::CompileError;
2047 }
2048 };
2049
2051 exception_policy Throw = exception_policy::Throw;
2052 exception_policy Ignore = exception_policy::Ignore;
2053 exception_policy Friendly = exception_policy::Friendly;
2054 exception_policy Simulate = exception_policy::Simulate;
2055
2056 judge_result_type Accepted = judge_result_type::Accepted;
2057 judge_result_type WrongAnswer = judge_result_type::WrongAnswer;
2058 judge_result_type TimeLimitExceeded = judge_result_type::TimeLimitExceeded;
2059 judge_result_type MemoryLimitExceeded = judge_result_type::MemoryLimitExceeded;
2060 judge_result_type RuntimeError = judge_result_type::RuntimeError;
2061 judge_result_type CompileError = judge_result_type::CompileError;
2062 judge_result_type PresentationError = judge_result_type::PresentationError;
2063 judge_result_type OutputLimitExceeded = judge_result_type::OutputLimitExceeded;
2064 judge_result_type UnknownError = judge_result_type::UnknownError;
2065 judge_result_type JudgeFailed = judge_result_type::JudgeFailed;
2066 judge_result_type PartiallyCorrect = judge_result_type::PartiallyCorrect;
2067 judge_result_type Skipped = judge_result_type::Skipped;
2068
2069 optimization_type O0 = optimization_type::O0;
2070 optimization_type O1 = optimization_type::O1;
2071 optimization_type O2 = optimization_type::O2;
2072 optimization_type O3 = optimization_type::O3;
2073 optimization_type Ofast = optimization_type::Ofast;
2074
2075 cpp_version Cpp98 = cpp_version::Cpp98;
2076 cpp_version Cpp03 = cpp_version::Cpp03;
2077 cpp_version Cpp11 = cpp_version::Cpp11;
2078 cpp_version Cpp14 = cpp_version::Cpp14;
2079 cpp_version Cpp17 = cpp_version::Cpp17;
2080 cpp_version Cpp20 = cpp_version::Cpp20;
2081
2088
2089 void helloworld() {
2090 const string version_str = CAREFREE_VERSION;
2091 const string product_name_art = " .o88b. .d8b. d8888b. d88888b d88888b d8888b. d88888b d88888b \nd8P Y8 d8' `8b 88 `8D 88' 88' 88 `8D 88' 88' \n8P 88ooo88 88oobY' 88ooooo 88ooo 88oobY' 88ooooo 88ooooo \n8b 88~~~88 88`8b 88~~~~~ 88~~~ 88`8b 88~~~~~ 88~~~~~ \nY8b d8 88 88 88 `88. 88. 88 88 `88. 88. 88. \n `Y88P' YP YP 88 YD Y88888P YP 88 YD Y88888P Y88888P \n \n \n";
2092 std::cout << ("Hello World! -- The greeting from Carefree " + version_str + "\n\n");
2093 std::cout << product_name_art << '\n';
2094 std::cout << "For more information, please visit : https://github.com/xiezheyuan/carefree/\n";
2095 std::cout << "Do you want me to help you open this URL? (y | others): ";
2096 string prompt;
2097 std::cin >> prompt;
2098 if (prompt == "y" || prompt == "Y") {
2099 std::system("start http://github.com/xiezheyuan/carefree/");
2100 }
2101 }
2102
2103 template <class T>
2105 private:
2106 std::function<bool(T)> val;
2107
2108 public:
2109 condition(std::function<bool(T)> x) : val(x) {}
2110 bool operator()(T x) const { return val(x); }
2111 };
2112
2113 template <class T>
2115 return condition<T>([a, b](T v) { return a(v) || b(v); });
2116 }
2117
2118 template <class T>
2120 return condition<T>([a, b](T v) { return a(v) && b(v); });
2121 }
2122
2123 template <class T>
2125 return condition<T>([a](T v) { return !a(v); });
2126 }
2127
2128 template <class T>
2130
2131 template <class T>
2133
2134 namespace pred {
2135 namespace num {
2136 template <class T>
2138 return condition<T>([x](T v) { return v < x; });
2139 }
2140
2141 template <class T>
2143 return condition<T>([x](T v) { return v > x; });
2144 }
2145
2146 template <class T>
2148 return condition<T>([x](T v) { return v == x; });
2149 }
2150
2151 template <class T>
2152 condition<T> leq(T x) { return lt(x) || eq(x); }
2153
2154 template <class T>
2155 condition<T> geq(T x) { return gt(x) || eq(x); }
2156
2157 template <class T>
2158 condition<T> neq(T x) { return !eq(x); }
2159
2160 template <class T>
2161 condition<T> inrange(T l, T r) { return geq(l) && leq(r); }
2162 } // namespace num
2163
2164 namespace str {
2166 return condition<string>([x](string v) { return v.length() < x; });
2167 }
2168
2170 return condition<string>([x](string v) { return v.length() > x; });
2171 }
2172
2174 return condition<string>([x](string v) { return v.length() == x; });
2175 }
2176
2177 condition<string> len_leq(size_t x) { return len_lt(x) || len_eq(x); }
2178
2179 condition<string> len_geq(size_t x) { return len_gt(x) || len_eq(x); }
2180
2181 condition<string> len_neq(size_t x) { return !len_eq(x); }
2182
2183 condition<string> len_inrange(size_t l, size_t r) { return len_geq(l) && len_leq(r); }
2184
2186
2188
2190 return condition<string>([s](string x) {
2191 std::map<char, bool> m;
2192 for (size_t i = 0; i < s.length(); i++) {
2193 m[s[i]] = true;
2194 }
2195 for (size_t i = 0; i < x.length(); i++) {
2196 if (!m[x[i]]) {
2197 return false;
2198 }
2199 }
2200 return true;
2201 });
2202 }
2203 } // namespace str
2204
2205 namespace seq {
2206 template <class T = int>
2207 condition<std::vector<T>> len_lt(size_t x) {
2208 return condition<std::vector<T>>([x](string v) { return v.length() < x; });
2209 }
2210
2211 template <class T = int>
2212 condition<std::vector<T>> len_gt(size_t x) {
2213 return condition<std::vector<T>>([x](string v) { return v.length() > x; });
2214 }
2215
2216 template <class T = int>
2217 condition<std::vector<T>> len_eq(size_t x) {
2218 return condition<std::vector<T>>([x](string v) { return v.length() == x; });
2219 }
2220
2221 template <class T = int>
2222 condition<std::vector<T>> len_leq(size_t x) { return len_lt(x) || len_eq(x); }
2223
2224 template <class T = int>
2225 condition<std::vector<T>> len_geq(size_t x) { return len_gt(x) || len_eq(x); }
2226
2227 template <class T = int>
2228 condition<std::vector<T>> len_neq(size_t x) { return !len_eq(x); }
2229
2230 template <class T = int>
2231 condition<std::vector<T>> len_inrange(size_t l, size_t r) { return len_geq(l) && len_leq(r); }
2232
2233 template <class T = int>
2234 condition<std::vector<T>> empty() { return len_eq(0); }
2235
2236 template <class T = int>
2237 condition<std::vector<T>> unempty() { return len_gt(0); }
2238
2239 template <class T = int>
2241 return condition<std::vector<T>>([](std::vector<T> v) {
2242 for (size_t i = 0; i < v.size() - 1; i++) {
2243 if (v[i] < v[i + 1]) {
2244 return false;
2245 }
2246 }
2247 return true;
2248 });
2249 }
2250
2251 template <class T = int>
2253 return condition<std::vector<T>>([](std::vector<T> v) {
2254 for (size_t i = 0; i < v.size() - 1; i++) {
2255 if (v[i] > v[i + 1]) {
2256 return false;
2257 }
2258 }
2259 return true;
2260 });
2261 }
2262
2263 } // namespace seq
2264 } // namespace pred
2265
2266} // namespace carefree_internal
2267
2268namespace carefree {
2343 using carefree_internal::testcase_io;
2352
2355 namespace pred = carefree_internal::pred;
2359} // namespace carefree
2360
2361#pragma GCC diagnostic pop
#define maybe_unused
Definition carefree.hpp:65
#define CAREFREE_VERSION
Definition carefree.hpp:30
Definition carefree.hpp:147
string msg
Definition carefree.hpp:149
virtual const char * what() const noexcept
Definition carefree.hpp:155
_base_exception(const char *__arg)
Definition carefree.hpp:153
_base_exception(const string &__arg)
Definition carefree.hpp:152
virtual ~_base_exception() noexcept=default
Definition carefree.hpp:165
virtual ~_file_exception() noexcept=default
_file_exception(const char *__arg)
Definition carefree.hpp:168
_file_exception(const string &__arg)
Definition carefree.hpp:167
Definition carefree.hpp:172
_system_exception(const char *__arg)
Definition carefree.hpp:175
_system_exception(const string &__arg)
Definition carefree.hpp:174
virtual ~_system_exception() noexcept=default
_unsupported_operation(const char *__arg)
Definition carefree.hpp:161
virtual ~_unsupported_operation() noexcept=default
_unsupported_operation(const string &__arg)
Definition carefree.hpp:160
Definition carefree.hpp:179
_validate_failed(const string &__arg)
Definition carefree.hpp:181
virtual ~_validate_failed() noexcept=default
_validate_failed(const char *__arg)
Definition carefree.hpp:182
Definition carefree.hpp:554
bool erase(T x)
Definition carefree.hpp:561
bool empty()
Definition carefree.hpp:569
int rnk(T x)
Definition carefree.hpp:563
void insert(T x)
Definition carefree.hpp:559
T kth(int x)
Definition carefree.hpp:565
int size()
Definition carefree.hpp:567
Definition carefree.hpp:95
string what()
Definition carefree.hpp:112
cpp_err_type get_err()
Definition carefree.hpp:114
carefree_exception(const char *msg)
Definition carefree.hpp:107
carefree_exception(string msg)
Definition carefree.hpp:105
carefree_exception()
Definition carefree.hpp:103
cpp_err_type err_type
Definition carefree.hpp:101
string get_msg()
Definition carefree.hpp:116
Definition carefree.hpp:1540
file(const string &filename)
Definition carefree.hpp:1545
string read()
Definition carefree.hpp:1546
Definition carefree.hpp:1535
Definition carefree.hpp:1564
string read()
Definition carefree.hpp:1570
text(const string &content)
Definition carefree.hpp:1569
Definition carefree.hpp:1533
virtual judge_result test(const string &input_path __attribute__((unused)), const string &output_path, const string &answer_path)
Definition carefree.hpp:1584
virtual judge_result from_text(const string &text1, const string &text2)=0
judge_result operator()(T1 a, T2 b)
Definition carefree.hpp:1580
virtual judge_result from_file(const string &filename1, const string &filename2)
Definition carefree.hpp:1575
Definition carefree.hpp:2104
condition(std::function< bool(T)> x)
Definition carefree.hpp:2109
bool operator()(T x) const
Definition carefree.hpp:2110
Definition carefree.hpp:1888
gcc_compile & include_file(string filename)
Definition carefree.hpp:1933
gcc_compile & debug_mode(bool debug=true)
Definition carefree.hpp:1953
gcc_compile(string filename, string output_name)
Definition carefree.hpp:1901
judge_result_type start()
Definition carefree.hpp:2045
gcc_compile & warning_level(cpp_warnings::type warning)
Definition carefree.hpp:1918
gcc_compile & add_warning(cpp_warnings::type warning)
Definition carefree.hpp:1923
string command()
Definition carefree.hpp:1958
gcc_compile & linking_static(bool link_static=true)
Definition carefree.hpp:1928
gcc_compile & include_dir(string dir)
Definition carefree.hpp:1943
gcc_compile & link(string lib)
Definition carefree.hpp:1948
gcc_compile & define(string key, string value="")
Definition carefree.hpp:1938
gcc_compile & cpp_version(cpp_version cpp)
Definition carefree.hpp:1913
gcc_compile & optimization(optimization_type opti)
Definition carefree.hpp:1908
gcc_compile & gcc(string gcc_path)
Definition carefree.hpp:1903
Definition carefree.hpp:574
int N
Definition carefree.hpp:607
bool has_edge(edge edg)
Definition carefree.hpp:636
bool directed
Definition carefree.hpp:609
std::vector< edge > get_edges(int from)
Definition carefree.hpp:649
void add(int from, int to, _Weight weight=0)
Definition carefree.hpp:632
string to_string(bool shuffle=false)
Definition carefree.hpp:657
bool enable_edge_map
Definition carefree.hpp:611
void add(edge edg, bool __add_vector=true)
Definition carefree.hpp:622
std::vector< edge > get_edges()
Definition carefree.hpp:645
bool has_edge(int from, int to)
Definition carefree.hpp:641
graph(int N, bool directed=false, bool enable_edge_map=true)
Definition carefree.hpp:613
luogu_testcase_config_writer()
Definition carefree.hpp:1280
string to_string()
Definition carefree.hpp:1303
void add(string input_name, int time_limit, int memory_limit, int score=-1, int subtask_id=-1)
Definition carefree.hpp:1284
void save(string filename="config.yml")
Definition carefree.hpp:1296
Definition carefree.hpp:1308
virtual bool is_running() const =0
virtual int pid() const =0
virtual size_t memory() const =0
virtual int return_code() const =0
Definition carefree.hpp:1319
process_win(const string &cmd, const string &input="", const string &output="")
Definition carefree.hpp:1325
bool is_running() const
Definition carefree.hpp:1383
void kill()
Definition carefree.hpp:1378
void close()
Definition carefree.hpp:1363
~process_win()
Definition carefree.hpp:1374
size_t memory() const
Definition carefree.hpp:1403
int return_code() const
Definition carefree.hpp:1391
int pid() const
Definition carefree.hpp:1399
Definition carefree.hpp:1593
judge_result from_text(const string &text1, const string &text2)
Definition carefree.hpp:1595
Definition carefree.hpp:1603
judge_result from_text(const string &text1, const string &text2)
Definition carefree.hpp:1605
Definition carefree.hpp:948
void input_write(string val)
Definition carefree.hpp:1121
void input_write(char val)
Definition carefree.hpp:1039
void output_write(unsigned __int128 val)
Definition carefree.hpp:1116
void input_writeln(T val, Args... args)
Definition carefree.hpp:1217
void input_write(graph val)
Definition carefree.hpp:1165
void input_write(__int128 val)
Definition carefree.hpp:1103
void input_write(std::vector< T > val)
Definition carefree.hpp:1149
void input_write(bool val)
Definition carefree.hpp:1139
void output_writeln()
Definition carefree.hpp:1200
void input_flush()
Definition carefree.hpp:1234
string output_name()
Definition carefree.hpp:1256
void output_write(graph val)
Definition carefree.hpp:1169
testcase_writer(string file_prefix, unsigned data_id, string input_suffix=".in", string output_suffix=".out", bool disable_output=false)
Definition carefree.hpp:1021
testcase_writer(string input_file, string output_file="")
Definition carefree.hpp:1015
void input_write(unsigned __int128 val)
Definition carefree.hpp:1112
void output_write(long long val)
Definition carefree.hpp:1057
void output_writeln(T val, Args... args)
Definition carefree.hpp:1225
void output_flush()
Definition carefree.hpp:1235
void input_write(short val)
Definition carefree.hpp:1093
void output_write(T val, Args... args)
Definition carefree.hpp:1192
void output_write(bool val)
Definition carefree.hpp:1143
testcase_writer(string file_prefix, unsigned subtask_id, unsigned task_id, string input_suffix=".in", string output_suffix=".out", bool disable_output=false)
Definition carefree.hpp:1030
void output_write(const char *val)
Definition carefree.hpp:1134
void input_write(T val, Args... args)
Definition carefree.hpp:1184
void input_write(const char *val)
Definition carefree.hpp:1130
void output_write(unsigned short val)
Definition carefree.hpp:1088
void input_write(long long val)
Definition carefree.hpp:1061
void output_writeln(T val)
Definition carefree.hpp:1210
void input_write(unsigned int val)
Definition carefree.hpp:1066
void input_write(unsigned long long val)
Definition carefree.hpp:1075
void output_write(unsigned long long val)
Definition carefree.hpp:1079
bool is_locked()
Definition carefree.hpp:1232
void input_write(int val)
Definition carefree.hpp:1048
void input_writeln()
Definition carefree.hpp:1199
void input_write(edge val)
Definition carefree.hpp:1174
void output_write(std::vector< T > val)
Definition carefree.hpp:1157
void output_write(edge val)
Definition carefree.hpp:1178
void output_write(char val)
Definition carefree.hpp:1043
void output_write(string val)
Definition carefree.hpp:1125
void output_write(int val)
Definition carefree.hpp:1052
void output_write(unsigned int val)
Definition carefree.hpp:1070
void output_write(short val)
Definition carefree.hpp:1097
void output_write(__int128 val)
Definition carefree.hpp:1107
void output_gen(string program)
Definition carefree.hpp:1237
void input_write(unsigned short val)
Definition carefree.hpp:1084
void input_writeln(T val)
Definition carefree.hpp:1203
void close()
Definition carefree.hpp:1260
string input_name()
Definition carefree.hpp:1252
~testcase_writer()
Definition carefree.hpp:1267
Definition carefree.hpp:1659
judge_result test(string input_path, string output_path, string answer_path)
Definition carefree.hpp:1694
judge_result from_text(const string &text1 __attribute__((unused)), const string &text2 __attribute__((unused)))
Definition carefree.hpp:1720
testlib_comparator(const string &testlib_path)
Definition carefree.hpp:1690
Definition carefree.hpp:1624
judge_result from_text(const string &text1, const string &text2)
Definition carefree.hpp:1626
Definition carefree.hpp:1878
const int Wextra
Definition carefree.hpp:1881
const int Wpedantic
Definition carefree.hpp:1882
const int Werror
Definition carefree.hpp:1883
const int Wall
Definition carefree.hpp:1880
int type
Definition carefree.hpp:1885
const int Wnone
Definition carefree.hpp:1879
Definition carefree.hpp:2135
condition< T > inrange(T l, T r)
Definition carefree.hpp:2161
condition< T > neq(T x)
Definition carefree.hpp:2158
condition< T > geq(T x)
Definition carefree.hpp:2155
condition< T > leq(T x)
Definition carefree.hpp:2152
condition< T > eq(T x)
Definition carefree.hpp:2147
condition< T > gt(T x)
Definition carefree.hpp:2142
condition< T > lt(T x)
Definition carefree.hpp:2137
Definition carefree.hpp:2205
condition< std::vector< T > > decrease()
Definition carefree.hpp:2252
condition< std::vector< T > > increase()
Definition carefree.hpp:2240
Definition carefree.hpp:2164
condition< string > empty()
Definition carefree.hpp:2185
condition< string > unempty()
Definition carefree.hpp:2187
condition< string > len_leq(size_t x)
Definition carefree.hpp:2177
condition< string > len_geq(size_t x)
Definition carefree.hpp:2179
condition< string > len_gt(size_t x)
Definition carefree.hpp:2169
condition< string > len_inrange(size_t l, size_t r)
Definition carefree.hpp:2183
condition< string > len_neq(size_t x)
Definition carefree.hpp:2181
condition< string > len_eq(size_t x)
Definition carefree.hpp:2173
condition< string > sset(string s)
Definition carefree.hpp:2189
condition< string > len_lt(size_t x)
Definition carefree.hpp:2165
Definition carefree.hpp:2134
Definition carefree.hpp:430
const string math_symbols
Definition carefree.hpp:443
const string bracket_general
Definition carefree.hpp:438
const string digit
Definition carefree.hpp:433
const string math_symbols_naive
Definition carefree.hpp:441
const string lower
Definition carefree.hpp:431
const string math_symbols_simple
Definition carefree.hpp:442
const string alphabet
Definition carefree.hpp:435
const string quotes
Definition carefree.hpp:440
const string slug
Definition carefree.hpp:436
const string bool_symbols
Definition carefree.hpp:444
const string var_name
Definition carefree.hpp:437
const string upper
Definition carefree.hpp:432
const string bracket
Definition carefree.hpp:439
const string bitwise_symbols
Definition carefree.hpp:445
const string alphanum
Definition carefree.hpp:434
Definition carefree.hpp:86
std::invalid_argument _invalid_argument
Definition carefree.hpp:186
graph introvert(graph tree)
Definition carefree.hpp:747
T uniform(T l, T r)
Definition carefree.hpp:378
judge_result judge(limprog prog, const string &input_file, const string &answer_file, T cmp, bool ole_check=true)
Definition carefree.hpp:1769
void set_exception_policy(exception_policy policy)
Definition carefree.hpp:313
std::vector< string > __split(const string &str, string delims)
Definition carefree.hpp:1518
graph random_graph(int n, int m, bool directed=true, bool repeat_edges=false, bool self_loop=false, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:933
std::vector< int > get_depth(graph g)
Definition carefree.hpp:729
bool is_tree(graph g)
Definition carefree.hpp:675
void shuffle(T val)
Definition carefree.hpp:394
graph connected_undirected_graph(int n, int m, bool repeat_edges=false, bool self_loop=false, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:899
ull nextid()
Definition carefree.hpp:1648
void err_equal_checker(T x, T l, string func_name, string var_name)
Definition carefree.hpp:302
void err_range_checker(T l, T r, string func_name)
Definition carefree.hpp:248
void listdir(string path, std::vector< string > &files)
Definition carefree.hpp:1829
graph dag(int n, int m, bool repeat_edges=false, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:880
int autoclear_tmpfiles()
Definition carefree.hpp:1845
graph flower(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:805
condition< T > operator&&(condition< T > a, condition< T > b)
Definition carefree.hpp:2119
bool is_file_creatable(string filename)
Definition carefree.hpp:1757
optimization_type
Definition carefree.hpp:1861
@ O0
Definition carefree.hpp:1862
@ O1
Definition carefree.hpp:1863
@ O3
Definition carefree.hpp:1865
@ Ofast
Definition carefree.hpp:1866
@ O2
Definition carefree.hpp:1864
void err_natural_checker(T x, string func_name, string var_name)
Definition carefree.hpp:266
graph random_tree(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:873
judge_result_type
Definition carefree.hpp:1421
@ UnknownError
Definition carefree.hpp:1430
@ Accepted
Definition carefree.hpp:1422
@ MemoryLimitExceeded
Definition carefree.hpp:1425
@ JudgeFailed
Definition carefree.hpp:1431
@ WrongAnswer
Definition carefree.hpp:1423
@ PartiallyCorrect
Definition carefree.hpp:1432
@ RuntimeError
Definition carefree.hpp:1426
@ TimeLimitExceeded
Definition carefree.hpp:1424
@ CompileError
Definition carefree.hpp:1427
@ OutputLimitExceeded
Definition carefree.hpp:1429
@ Skipped
Definition carefree.hpp:1433
@ PresentationError
Definition carefree.hpp:1428
double random()
Definition carefree.hpp:383
bool combat(limprog champion, limprog challenger, T1 input_generator, T2 cmp, int times=-1, bool ole_check=true)
Definition carefree.hpp:1795
void err_leq_checker(T x, T l, string func_name, string var_name)
Definition carefree.hpp:290
void err_unempty_checker(T x, string func_name, string var_name)
Definition carefree.hpp:254
string working_directory()
Definition carefree.hpp:1841
long long _Weight
Definition carefree.hpp:572
void err_positive_checker(T x, string func_name, string var_name)
Definition carefree.hpp:260
graph lowhigh(int n, double low, double high, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:771
graph binary_tree(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:823
std::runtime_error _runtime_exception
Definition carefree.hpp:190
condition< T > operator||(condition< T > a, condition< T > b)
Definition carefree.hpp:2114
void helloworld()
Definition carefree.hpp:2089
T::value_type choice(T val)
Definition carefree.hpp:388
graph relabel(graph g)
Definition carefree.hpp:691
carefree_exception< _range_exception, carefree_range_exception_name > carefree_range_exception
Definition carefree.hpp:194
graph externalize(graph tree)
Definition carefree.hpp:759
std::vector< Value > sequence(int n, T function)
Definition carefree.hpp:399
graph naive_tree(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:780
double timer(T function)
Definition carefree.hpp:461
struct carefree_internal::__enum_shortcut ES
T randint(T l, T r)
Definition carefree.hpp:372
graph connected_directed_graph(int n, int m, bool repeat_edges=false, bool self_loop=false, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:916
graph complete_binary(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:869
void err_less_checker(T x, T l, string func_name, string var_name)
Definition carefree.hpp:278
string quote(string s)
Definition carefree.hpp:1653
void gen_data(int subtask_count, int task_per_subtask, T function)
Definition carefree.hpp:469
string jrt2sf(judge_result_type type)
Definition carefree.hpp:1468
graph firecrackers(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:842
condition< T > operator!(condition< T > a)
Definition carefree.hpp:2124
string jrt2s(judge_result_type type)
Definition carefree.hpp:1436
void err_greater_checker(T x, T l, string func_name, string var_name)
Definition carefree.hpp:284
graph max_degree(int n, int k, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:809
graph silkworm(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:834
condition< T > operator&(condition< T > a, condition< T > b)
Definition carefree.hpp:2132
exception_policy get_exception_policy() noexcept
Definition carefree.hpp:219
string join_str(T1 a, T2 b)
Definition carefree.hpp:321
graph chain_star(int n, int k, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:827
carefree_exception< _invalid_argument, carefree_invalid_argument_name > carefree_invalid_argument
Definition carefree.hpp:192
string __fts(T val, unsigned precision=10)
Definition carefree.hpp:326
unsigned long long ull
Definition carefree.hpp:1500
void err_inrange_checker(T x, T l, T r, string func_name, string var_name)
Definition carefree.hpp:272
std::out_of_range _range_exception
Definition carefree.hpp:188
string fts(float val, unsigned precision=10)
Definition carefree.hpp:343
graph tail(int n, int k, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:784
exception_policy
Definition carefree.hpp:206
@ Simulate
Definition carefree.hpp:214
@ Throw
Definition carefree.hpp:208
@ Ignore
Definition carefree.hpp:210
@ Friendly
Definition carefree.hpp:212
condition< T > operator|(condition< T > a, condition< T > b)
Definition carefree.hpp:2129
std::mt19937_64 public_random_engine
Definition carefree.hpp:369
std::vector< T > ltv(std::initializer_list< T > val)
Definition carefree.hpp:365
exception_policy exception_policy_val
Definition carefree.hpp:217
graph complete(int n, int k, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:852
void err_unequal_checker(T x, T l, string func_name, string var_name)
Definition carefree.hpp:308
graph star(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:797
void raise(carefree_exception< T1, T2 > err)
Definition carefree.hpp:224
string randstr(int length, const string sset=strsets::lower)
Definition carefree.hpp:448
graph chain(int n, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:793
cpp_version
Definition carefree.hpp:1869
@ Cpp11
Definition carefree.hpp:1872
@ Cpp17
Definition carefree.hpp:1874
@ Cpp98
Definition carefree.hpp:1870
@ Cpp14
Definition carefree.hpp:1873
@ Cpp03
Definition carefree.hpp:1871
@ Cpp20
Definition carefree.hpp:1875
graph prufer_decode(int n, std::vector< int > prufer, _Weight weightL=0, _Weight weightR=0)
Definition carefree.hpp:702
void err_geq_checker(T x, T l, string func_name, string var_name)
Definition carefree.hpp:296
judge_result limited_run(limprog prog, const string &input_file, const string &output_file)
Definition carefree.hpp:1734
__attribute__((constructor)) static void init_rnd_seed()
Definition carefree.hpp:549
Definition carefree.hpp:2268
Definition carefree.hpp:2050
virtual string name()
Definition carefree.hpp:91
string name()
Definition carefree.hpp:132
string name()
Definition carefree.hpp:120
string name()
Definition carefree.hpp:124
string name()
Definition carefree.hpp:136
string name()
Definition carefree.hpp:140
string name()
Definition carefree.hpp:128
string name()
Definition carefree.hpp:144
Definition carefree.hpp:576
int to
Definition carefree.hpp:577
edge(int from, int to, _Weight weight=0)
Definition carefree.hpp:579
int from
Definition carefree.hpp:577
_Weight weight
Definition carefree.hpp:578
string operator()(edge edg)
Definition carefree.hpp:589
string operator()(edge edg)
Definition carefree.hpp:583
Definition carefree.hpp:1502
string message
Definition carefree.hpp:1504
ull time
Definition carefree.hpp:1506
double ratio
Definition carefree.hpp:1505
ull memory
Definition carefree.hpp:1507
string to_str() const
Definition carefree.hpp:1509
judge_result_type type
Definition carefree.hpp:1503
Definition carefree.hpp:1726
string program
Definition carefree.hpp:1727
ull time
Definition carefree.hpp:1728
ull memory
Definition carefree.hpp:1729
limprog(string program, ull time, ull memory)
Definition carefree.hpp:1731