Repository navigation
Expand file tree
/
Copy pathtemplate.txt
More file actions
1616 lines (1356 loc) · 48.3 KB
/
Copy pathtemplate.txt
File metadata and controls
1616 lines (1356 loc) · 48.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// template: https://github.com/GONGRYONGWANG/ProblemSolving/blob/main/template.txt
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<utility>
#include<list>
#include<queue>
#include<stack>
#include<deque>
#include<set>
#include<unordered_set>
#include<map>
#include<unordered_map>
#include<cmath>
#include<algorithm>
#include<bitset>
#include<cstdlib>
#include<ctime> // srand(time(0))
#include<regex> // 정규표현식
#include<random> // rand
#include<complex> // complex number
#include<numeric>
#include<cassert>
#include <climits>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef complex<double> cpx;
#define pq priority_queue
#define endl "\n"
const ll INF = 1e18 + 7;
const int inf = 1e9 + 7;
const long double pi = 3.14159265358979323846;
const string debug = "output: ";
// 랜덤
#include<random> // rand
std::mt19937 gen;
void rng_init() {
std::random_device rd;
gen.seed(rd()); // main에서 1번
}
int randint(int l, int r) {
std::uniform_int_distribution<int> dist(l, r);
return dist(gen);
}
struct VectorHasher { // unordered_set<vector<int>,VectorHasher>
size_t operator()(const vector<int>& V) const {
size_t hash = V.size();
for (auto& i : V) {
hash ^= i + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}
return hash;
}
};
struct PiiHasher { // unordered_set<pii, PiiHasher>
size_t operator()(const pii& x) const {
return hash<long long>()(((long long)x.first) ^ (((long long)x.second) << 32));
}
};
struct DequeHasher {
template <typename T>
std::size_t operator()(const std::deque<T>& dq) const {
std::size_t hash = 0;
std::hash<T> hasher;
for (const auto& elem : dq) {
// deque의 각 요소의 해시 값을 합침
hash ^= hasher(elem) + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}
return hash;
}
};
const int RANDOM = chrono::high_resolution_clock::now().time_since_epoch().count(); // random hash
struct chash {
int operator()(int x) const { return x ^ RANDOM; }
};
bool coordinatecmp(pll a, pll b) { // 반시계 각도 정렬
// 1. 사분면 비교 (y > 0 이면 위쪽, y == 0 이면 x > 0 이면 오른쪽)
auto half = [](pair<long long, long long> p) {
if (p.second > 0) return 1;
if (p.second < 0) return 0;
return p.first > 0 ? 1 : 0;
};
int ha = half(a), hb = half(b);
if (ha != hb) return ha > hb;
// 2. 같은 반평면이면 cross product 비교
return a.first * b.second - a.second * b.first > 0;
}
vector<vector<ll>> matmul( const vector<vector<ll>>& a, const vector<vector<ll>>& b, ll mod = 0) { // 행렬 곱
assert(a[0].size() == b.size());
vector<vector<ll>> ret(a.size(), vector<ll>(b[0].size(), 0));
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < b[0].size(); j++) {
for (int k = 0; k < a[0].size(); k++) {
ret[i][j] += a[i][k] * b[k][j];
if(mod) ret[i][j] %= mod;
}
}
}
return ret;
}
vector<vector<ll>> powmat(const vector<vector<ll>>& mat, ll n, ll mod = 0) { // 행렬 거듭제곱
if (n == 1) return mat;
if (n % 2) {
return matmul(powmat(mat, n - 1, mod), mat , mod);
}
vector<vector<ll>> half = powmat(mat, n / 2, mod);
return matmul(half, half, mod);
}
ll fibo(ll n, ll mod = 0) { // 행렬 거듭제곱 이용 피보나치
if (n < 2) {
return n;
}
vector<vector<ll>> ret = matmul(powmat({ {1,1},{1,0} }, n - 1, mod), { {1},{0} }, mod);
return ret[0][0];
}
vector<int> getPi(const string s) { // KMP 선행 작업, pattern->전이함수
vector<int> pi(s.size(), 0);
int j = 0;
for (int i = 1; i < s.size(); i++) {
while ((j > 0) && (s[i] != s[j])) {
j = pi[j - 1];
}
if (s[i] == s[j]) {
j++;
pi[i] = j;
}
}
return pi;
}
vector<int> kmp(const string& s, const string& t, const vector<int>& pi) { //KMP, kmp(pattern, txt, pi)
vector<int> result;
int j = 0;
for (int i = 0; i < t.size(); i++) {
while ((j > 0) && (t[i] != s[j])) {
j = pi[j - 1];
}
if (t[i] == s[j]) {
if (j == s.size() - 1) {
result.push_back(i - s.size() + 1);
j = pi[j];
}
else {
j++;
}
}
}
return result;
}
vector<int> getPi(const vector<int>& pattern) { // 수열용 KMP 선행작업
vector<int> pi(pattern.size(), 0);
int j = 0;
for (int i = 1; i < pattern.size(); i++) {
while (j > 0 && pattern[i] != pattern[j]) {
j = pi[j - 1];
}
if (pattern[i] == pattern[j]) {
j++;
pi[i] = j;
}
}
return pi;
}
vector<int> kmp(const vector<int>& pattern, const vector<int>& text, const vector<int>& pi) { // 수열용 KMP
vector<int> result;
int j = 0;
for (int i = 0; i < text.size(); i++) {
while (j > 0 && text[i] != pattern[j]) {
j = pi[j - 1];
}
if (text[i] == pattern[j]) {
if (j == pattern.size() - 1) {
result.push_back(i - pattern.size() + 1);
j = pi[j];
} else {
j++;
}
}
}
return result;
}
string manacher_preprocess(string& s) { // 매내처 선행작업
string ret = "";
char tmp = '#';
for (char x : s) {
ret += tmp;
ret += x;
}
ret += tmp;
return ret;
}
vector<ll> manacher(string& s) { // O(s.length())
int N = s.length();
vector<ll> ret(N, 0);
ll r = 0, p = 0;
for (int i = 0; i < N; i++) {
if (i <= r) ret[i] = min(ret[2 * p - i], r - i);
else ret[i] = 0;
while (i - ret[i] - 1 >= 0 && i + ret[i] + 1 < N && s[i - ret[i] - 1] == s[i + ret[i] + 1]) ret[i] += 1;
if (r < i + ret[i]) {
r = i + ret[i];
p = i;
}
}
return ret;
}
vector<int> manacher_preprocess(const vector<int>& seq) { // 수열용 매내처 선행작업
vector<int> ret;
ret.push_back(-1); // Sentinel value to simulate '#'
for (int x : seq) {
ret.push_back(x);
ret.push_back(-1); // Sentinel value between elements
}
return ret;
}
vector<int> manacher(const vector<int>& seq) { // 수열용 매내처
int N = seq.size();
vector<int> ret(N, 0);
int r = 0, p = 0;
for (int i = 0; i < N; i++) {
if (i <= r) ret[i] = min(ret[2 * p - i], r - i);
else ret[i] = 0;
while (i - ret[i] - 1 >= 0 && i + ret[i] + 1 < N && seq[i - ret[i] - 1] == seq[i + ret[i] + 1]) {
ret[i] += 1;
}
if (r < i + ret[i]) {
r = i + ret[i];
p = i;
}
}
return ret;
}
vector<int> build_suffix_array(const string& s) { // Suffix Array (SA) O(NlogN)
int n = s.size();
const int ALPHABET = 256;
vector<int> sa(n), rank(n), tmp(n), cnt(max(ALPHABET, n));
for (int i = 0; i < n; i++) {
sa[i] = i;
rank[i] = s[i];
}
for (int k = 1; k < n; k <<= 1) {
auto cmp = [&](int i, int j) {
if (rank[i] != rank[j]) return rank[i] < rank[j];
int ri = (i + k < n) ? rank[i + k] : -1;
int rj = (j + k < n) ? rank[j + k] : -1;
return ri < rj;
};
sort(sa.begin(), sa.end(), cmp);
tmp[sa[0]] = 0;
for (int i = 1; i < n; i++)
tmp[sa[i]] = tmp[sa[i - 1]] + cmp(sa[i - 1], sa[i]);
rank = tmp;
}
return sa;
}
vector<int> build_lcp_array(const string& s, const vector<int>& sa) {
int n = s.size();
vector<int> rank(n), lcp(n); // 크기를 n으로 하고, lcp[0] = 0으로 둠
for (int i = 0; i < n; i++)
rank[sa[i]] = i;
int h = 0;
for (int i = 0; i < n; i++) {
if (rank[i] == 0) {
lcp[0] = 0; // 첫 위치는 비교할 이전 접미사가 없음
continue;
}
int j = sa[rank[i] - 1];
while (i + h < n && j + h < n && s[i + h] == s[j + h])
h++;
lcp[rank[i]] = h;
if (h > 0) h--;
}
return lcp;
}
struct AhoCorasick { // 아호-코라식
struct Node {
unordered_map<char, int> next; // Transition table
int fail = -1; // Failure link
vector<int> output; // Stores the indices of patterns that end here
};
vector<Node> trie;
AhoCorasick() {
trie.push_back(Node()); // Root node
}
// Insert a pattern into the trie
void insert(const string& pattern, int patternIndex) {
int currentNode = 0;
for (char ch : pattern) {
if (trie[currentNode].next.find(ch) == trie[currentNode].next.end()) {
trie[currentNode].next[ch] = trie.size();
trie.push_back(Node());
}
currentNode = trie[currentNode].next[ch];
}
trie[currentNode].output.push_back(patternIndex);
}
// Build the failure links
void build() {
queue<int> q;
// Set the fail link of the root's children to root
for (const auto& pair : trie[0].next) {
int child = pair.second;
trie[child].fail = 0;
q.push(child);
}
// Perform BFS to build failure links
while (!q.empty()) {
int node = q.front();
q.pop();
for (const auto& pair : trie[node].next) {
char ch = pair.first;
int child = pair.second;
int failNode = trie[node].fail;
// Follow the failure link until we find a match
while (failNode != -1 && trie[failNode].next.find(ch) == trie[failNode].next.end()) {
failNode = trie[failNode].fail;
}
if (failNode == -1) {
trie[child].fail = 0;
}
else {
trie[child].fail = trie[failNode].next[ch];
trie[child].output.insert(trie[child].output.end(),
trie[trie[child].fail].output.begin(),
trie[trie[child].fail].output.end());
}
q.push(child);
}
}
}
// Search for patterns in a given string and return all matches
vector<int> search(const string& text) {
vector<int> matches;
int currentNode = 0;
for (int i = 0; i < text.length(); ++i) {
char ch = text[i];
// Follow the transition links, or fail if no match
while (currentNode != -1 && trie[currentNode].next.find(ch) == trie[currentNode].next.end()) {
currentNode = trie[currentNode].fail;
}
if (currentNode == -1) {
currentNode = 0;
continue;
}
currentNode = trie[currentNode].next[ch];
// Collect matched pattern indices
for (int patternIndex : trie[currentNode].output) {
matches.push_back(patternIndex);
}
}
return matches;
}
};
ll gcd(ll a, ll b) {
if (a < b) swap(a, b);
while (b != 0) {
ll n = a % b;
a = b;
b = n;
}
return a;
}
ll lcm(ll a, ll b) {
ll g = gcd(a, b);
return a / g * b;
}
pll xgcd(ll a, ll b) {
if (b == 0) {
return {1, 0};
}
auto [x1, y1] = xgcd(b, a % b);
ll x = y1;
ll y = x1 - (a / b) * y1;
return {x, y};
}
ll powmod(ll x, ll n, ll mod) {
if (n == 0) return 1;
if (n % 2) return x * powmod(x, n - 1, mod) % mod;
ll half = powmod(x, n / 2, mod);
return half * half % mod;
}
ll modinv(ll x, ll mod) { // when mod is primenum
x %= mod;
return powmod(x, mod - 2, mod);
}
//const ll Fsize = 1;
//ll F[Fsize];
ll factorial(ll x) {
ll ret = 1;
//ret = F[x]; //
return ret;
}
//ll modI[Fsize]; ll modIF[Fsize];
ll modinvfactorial(ll x) {
ll ret = 1;
//ret = modIF[x]; //
return ret;
}
ll combination(ll n, ll r, ll mod) {
if (r == 0 || n == r) return 1;
return factorial(n) * modinvfactorial(n - r) % mod * modinvfactorial(r) % mod;
}
int popcount(uint n) { // https://blog.naver.com/jinhan814/222540111549
n = (n >> 1 & 0x55555555) + (n & 0x55555555);
n = (n >> 2 & 0x33333333) + (n & 0x33333333);
n = (n >> 4 & 0x0F0F0F0F) + (n & 0x0F0F0F0F);
n = (n >> 8 & 0x00FF00FF) + (n & 0x00FF00FF);
n = (n >> 16 & 0x0000FFFF) + (n & 0x0000FFFF);
return n;
}
int ccw(const pair<int, int>& p1, const pair<int, int>& p2, const pair<int, int>& p3) { // CCW (Counter Clockwise) 판별 함수
long long cross = 1LL * (p2.first - p1.first) * (p3.second - p1.second) -
1LL * (p2.second - p1.second) * (p3.first - p1.first);
return (cross > 0) - (cross < 0); // 1: CCW, -1: CW, 0: Collinear
}
vector<pair<int, int>> convexHull(vector<pair<int, int>> points) { // 컨벡스 헐 계산 함수
if (points.size() <= 2) return points; // 점이 2개 이하인 경우 그대로 반환
// 좌표를 x 기준, 같으면 y 기준으로 정렬
sort(points.begin(), points.end());
vector<pair<int, int>> lower, upper;
// 아래쪽 헐 계산
for (const auto& point : points) {
while (lower.size() >= 2 && ccw(lower[lower.size() - 2], lower[lower.size() - 1], point) <= 0) {
lower.pop_back();
}
lower.push_back(point);
}
// 위쪽 헐 계산
for (auto it = points.rbegin(); it != points.rend(); ++it) {
while (upper.size() >= 2 && ccw(upper[upper.size() - 2], upper[upper.size() - 1], *it) <= 0) {
upper.pop_back();
}
upper.push_back(*it);
}
// 마지막 점이 중복되므로 제거
lower.pop_back();
upper.pop_back();
// 아래쪽과 위쪽을 합쳐 반시계 방향으로 반환
lower.insert(lower.end(), upper.begin(), upper.end());
return lower;
}
pair<int, int> rotatingCalipers(const vector<pair<int, int>>& hull) { // 가장 먼 두 점
int n = hull.size();
if (n == 1) return { 0, 0 };
if (n == 2) return { 0, 1 };
int max_i = 0, max_j = 0;
long long maxDistSq = 0;
int j = 1;
for (int i = 0; i < n; ++i) {
int ni = (i + 1) % n;
while (true) {
int nj = (j + 1) % n;
// 외적 비교
long long cross = 1LL * (hull[ni].first - hull[i].first) * (hull[nj].second - hull[j].second) -
1LL * (hull[ni].second - hull[i].second) * (hull[nj].first - hull[j].first);
if (cross > 0) j = nj;
else break;
}
long long dx = 1LL * hull[i].first - hull[j].first;
long long dy = 1LL * hull[i].second - hull[j].second;
long long distSq = dx * dx + dy * dy;
if (distSq > maxDistSq) {
maxDistSq = distSq;
max_i = i;
max_j = j;
}
}
return { max_i, max_j };
}
long long doubledPolygonArea(const vector<pair<int, int>>& polygon) { // polygon에 convexhull 넣기
long long area2 = 0;
int n = polygon.size();
for (int i = 0; i < n; ++i) {
const auto& [x1, y1] = polygon[i];
const auto& [x2, y2] = polygon[(i + 1) % n];
area2 += 1LL * x1 * y2 - 1LL * x2 * y1;
}
return abs(area2); // 실제 넓이의 2배
}
bool intersect(pll A, pll B, pll C, pll D) { // 선분 교차 판정 A-B , C-D
if (A > B) swap(A, B);
if (C > D) swap(C, D);
ll l1 = ccw(A, B, C) * ccw(A, B, D);
ll l2 = ccw(C, D, A) * ccw(C, D, B);
if (l1 == 0 && l2 == 0) {
return A <= D && C <= B;
}
return l1 <= 0 && l2 <= 0;
}
bool isredundant(pll& a, pll& b, pll& c) { // CHT에서 가운데 라인이 무의미 한지 확인.
return (b.second - a.second) * (b.first - c.first) >= (c.second - b.second) * (a.first - b.first);
}
vector<ll> slope_trick(const vector<ll>& v) { // A(i)=<A(i+1). 역순으로 사전순 최소?
priority_queue<ll> q;
vector<ll> opt(v.size());
for (int i = 0; i < v.size(); i++) {
if (q.empty() || q.top() <= v[i]) q.push(v[i]);
else {
q.pop();
q.push(v[i]);
q.push(v[i]);
}
opt[i] = q.top();
}
for (int i = v.size() - 2; i >= 0; i--) opt[i] = min(opt[i], opt[i + 1]);
return opt;
}
struct MF { // Dinic O(EV^2)
struct Edge {
int to, rev;
long long flow, cap;
Edge(int to, int rev, long long cap) : to(to), rev(rev), flow(0), cap(cap) {}
};
int n;
vector<vector<Edge>> adj; // get이후 edge vector를 이용해서 trace, cap<=flow인 간선은 continue하며 bfs.
vector<int> level, ptr;
MF(int n) : n(n), adj(n), level(n), ptr(n) {}
void addEdge(int u, int v, long long cap, bool directed = true) {
if (cap == 0) return;
adj[u].emplace_back(v, adj[v].size(), cap);
if (!directed) adj[v].emplace_back(u, adj[u].size() - 1, cap);
else adj[v].emplace_back(u, adj[u].size() - 1, 0);
}
bool bfs(int source, int sink) {
fill(level.begin(), level.end(), -1);
level[source] = 0;
queue<int> q;
q.push(source);
while (!q.empty()) {
int node = q.front();
q.pop();
for (Edge& e : adj[node]) {
if (level[e.to] == -1 && e.flow < e.cap) { // 잔여 용량이 있는 간선을 찾음
level[e.to] = level[node] + 1;
q.push(e.to);
}
}
}
return level[sink] != -1;
}
long long dfs(int node, int sink, long long pushed) {
if (pushed == 0) return 0;
if (node == sink) return pushed;
for (int& cid = ptr[node]; cid < adj[node].size(); cid++) {
Edge& e = adj[node][cid];
if (level[e.to] != level[node] + 1 || e.flow == e.cap) continue;
long long tr = dfs(e.to, sink, min(pushed, e.cap - e.flow));
if (tr == 0) continue;
e.flow += tr;
adj[e.to][e.rev].flow -= tr;
return tr;
}
return 0;
}
long long get(int source, int sink) {
long long flow = 0;
while (bfs(source, sink)) {
fill(ptr.begin(), ptr.end(), 0);
while (long long pushed = dfs(source, sink, LLONG_MAX)) {
flow += pushed;
}
}
return flow;
}
void trace(int src) {
queue<int> q;
q.push(src);
vector<bool> visited(n, false);
visited[src] = true;
vector<int> ret;
while (!q.empty()) {
int cur = q.front();
q.pop();
for (Edge& e : adj[cur]) {
if (e.cap <= e.flow) continue;
if (visited[e.to]) continue;
q.push(e.to);
ret.push_back(e.to);
visited[e.to] = true;
}
}
cout << ret.size() << " ";
for (int x : ret) {
cout << x << " ";
}
cout << endl;
}
};
struct MCMF { // SPFA O(VEf) - Practically Ef
struct Edge {
int to, rev;
long long cap, flow, cost;
Edge(int to, int rev, long long cap, long long cost) : to(to), rev(rev), cap(cap), flow(0), cost(cost) {}
};
int n;
vector<vector<Edge>> adj;
vector<long long> dist;
vector<int> parent, parentEdge;
vector<bool> inQueue;
int source, sink;
MCMF(int n) : n(n), adj(n), dist(n), parent(n), parentEdge(n), inQueue(n), source(-1), sink(-1) {}
void setSource(int s) {
source = s;
}
void setSink(int t) {
sink = t;
}
void addEdge(int u, int v, long long cap, long long cost, bool directed = true) {
if (cap == 0) return;
adj[u].emplace_back(v, adj[v].size(), cap, cost);
adj[v].emplace_back(u, adj[u].size() - 1, 0, -cost); // 역방향 간선
if (!directed) {
adj[v].emplace_back(u, adj[u].size(), cap, cost);
adj[u].emplace_back(v, adj[v].size() - 1, 0, -cost);
}
}
bool spfa() {
fill(dist.begin(), dist.end(), LLONG_MAX);
fill(inQueue.begin(), inQueue.end(), false);
queue<int> q;
dist[source] = 0;
inQueue[source] = true;
q.push(source);
while (!q.empty()) {
int u = q.front();
q.pop();
inQueue[u] = false;
for (int i = 0; i < adj[u].size(); ++i) {
Edge& e = adj[u][i];
if (e.flow < e.cap && dist[u] + e.cost < dist[e.to]) {
dist[e.to] = dist[u] + e.cost;
parent[e.to] = u;
parentEdge[e.to] = i;
if (!inQueue[e.to]) {
inQueue[e.to] = true;
q.push(e.to);
}
}
}
}
return dist[sink] != LLONG_MAX;
}
pair<long long, long long> get(int _source = -1, int _sink = -1) {
if (_source != -1) {
setSource(_source);
setSink(_sink);
}
long long maxFlow = 0, minCost = 0;
while (spfa()) {
long long flow = LLONG_MAX;
for (int u = sink; u != source; u = parent[u]) {
Edge& e = adj[parent[u]][parentEdge[u]];
flow = min(flow, e.cap - e.flow);
}
for (int u = sink; u != source; u = parent[u]) {
Edge& e = adj[parent[u]][parentEdge[u]];
e.flow += flow;
adj[u][e.rev].flow -= flow;
minCost += flow * e.cost;
}
maxFlow += flow;
}
return { maxFlow, minCost };
}
};
struct BiMatch { // Hopcroft-Karp O(E*sqrtV)
int n, m; // n: left side vertices, m: right side vertices
vector<vector<int>> adj; // adjacency list
vector<int> pairU, pairV, dist;
// pairU 또는 pairV를 출력해서 매칭 결과를 print 가능.
BiMatch(int n, int m) : n(n), m(m), adj(n + 1), pairU(n + 1), pairV(m + 1), dist(n + 1) {}
void addEdge(int u, int v) {
adj[u].push_back(v);
}
bool bfs() {
queue<int> q;
for (int u = 1; u <= n; u++) {
if (pairU[u] == 0) { // If u is free (not matched)
dist[u] = 0;
q.push(u);
}
else {
dist[u] = INT_MAX;
}
}
dist[0] = INT_MAX;
while (!q.empty()) {
int u = q.front();
q.pop();
if (dist[u] < dist[0]) {
for (int v : adj[u]) {
if (dist[pairV[v]] == INT_MAX) { // If pairV[v] is not yet visited
dist[pairV[v]] = dist[u] + 1;
q.push(pairV[v]);
}
}
}
}
return dist[0] != INT_MAX; // If there's an augmenting path
}
bool dfs(int u) {
if (u != 0) {
for (int v : adj[u]) {
if (dist[pairV[v]] == dist[u] + 1 && dfs(pairV[v])) {
pairV[v] = u;
pairU[u] = v;
return true;
}
}
dist[u] = INT_MAX;
return false;
}
return true;
}
int get() {
fill(pairU.begin(), pairU.end(), 0);
fill(pairV.begin(), pairV.end(), 0);
int matching = 0;
while (bfs()) {
for (int u = 1; u <= n; u++) {
if (pairU[u] == 0 && dfs(u)) {
matching++;
}
}
}
return matching;
}
};
struct Hungarian { // O(N^3)
int n; // 문제의 크기 (n x n 행렬)
vector<vector<long long>> cost; // 비용 행렬
vector<long long> u, v; // 레이블
vector<int> p, way;// 경로 추적
vector<int> matchResult; // 최종 매칭 결과 (작업자 -> 작업)
Hungarian(int n) : n(n), cost(n, vector<long long>(n, 0)), u(n + 1, 0), v(n + 1, 0), p(n + 1, 0), way(n + 1, 0), matchResult(n, -1) {}
void addEdge(int i, int j, long long weight) {
cost[i][j] = weight;
}
long long get() {
for (int i = 1; i <= n; i++) {
vector<long long> minv(n + 1, LLONG_MAX);
vector<bool> used(n + 1, false);
int j0 = 0;
p[0] = i;
do {
used[j0] = true;
int i0 = p[j0];
long long delta = LLONG_MAX;
int j1;
for (int j = 1; j <= n; j++) {
if (!used[j]) {
long long cur = cost[i0 - 1][j - 1] - u[i0] - v[j];
if (cur < minv[j]) {
minv[j] = cur;
way[j] = j0;
}
if (minv[j] < delta) {
delta = minv[j];
j1 = j;
}
}
}
for (int j = 0; j <= n; j++) {
if (used[j]) {
u[p[j]] += delta;
v[j] -= delta;
}
else {
minv[j] -= delta;
}
}
j0 = j1;
} while (p[j0] != 0);
do {
int j1 = way[j0];
p[j0] = p[j1];
j0 = j1;
} while (j0 != 0);
}
// 매칭 결과 저장
for (int j = 1; j <= n; j++) {
matchResult[p[j] - 1] = j - 1;
}
return -v[0]; // 최저 비용 반환
}
void trace() {
for (int i = 0; i < n; i++) {
cout << i + 1 << " " << matchResult[i] + 1 << endl;
}
}
};
struct GlobalMincut { // StoerWagner O(N^3)
int N;
vector<vector<ll>> w; // adjacency matrix
GlobalMincut(int n) : N(n), w(n + 1, vector<ll>(n + 1, 0)) {}
void add_edge(int u, int v, ll c = 1) {
if (u == v) return;
w[u][v] += c;
w[v][u] += c;
}
ll mincut() {
vector<int> v(N + 1);
iota(v.begin() + 1, v.end(), 1);
ll best = INF;
int n = N;
while (n > 1) {
vector<ll> weight(n + 1, 0);
vector<char> added(n + 1, 0);
int prev = -1, sel = -1;
for (int i = 1; i <= n; i++) {
// pick max-weight vertex not yet added
sel = -1;
for (int j = 1; j <= n; j++)
if (!added[j] && (sel == -1 || weight[j] > weight[sel]))
sel = j;
added[sel] = 1;
if (i == n) {
// sel is t, prev is s
best = min(best, weight[sel]);
// merge sel into prev
for (int j = 1; j <= n; j++) {
if (j == sel) continue;
w[v[prev]][v[j]] += w[v[sel]][v[j]];
w[v[j]][v[prev]] = w[v[prev]][v[j]];
}
v.erase(v.begin() + sel);
n--;
break;
}
prev = sel;
for (int j = 1; j <= n; j++)
if (!added[j]) weight[j] += w[v[sel]][v[j]];
}
}
return best;
}
};
struct GeneralMatch { // Micali-Vazirani O(E*sqrt(V)*(log*V)). reference: https://github.com/ggawryal/MV-matching/tree/main
GeneralMatch(int n) : n(n), adj(n) {}
void addEdge(int a, int b, bool directed = false) {
adj[a].push_back(Edge(b, (int)adj[b].size()));
if (!directed) {
adj[b].push_back(Edge(a, (int)adj[a].size() - 1));
}
}
//disjoint set union data structure
struct DSU {
vector<int> link;
vector<int> directParent;
vector<int> size;
vector<int> groupRoot;