forked from EndlessCheng/codeforces-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
4307 lines (4006 loc) · 125 KB
/
graph.go
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
package copypasta
import (
"container/heap"
. "fmt"
"io"
"math"
"math/bits"
"sort"
)
/*
Graph Theory Playlist https://www.youtube.com/playlist?list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P
图论的小技巧以及扩展 https://www.luogu.com.cn/blog/chengni5673/tu-lun-di-xiao-ji-qiao-yi-ji-kuo-zhan
边权转点权:在 v-w 之间加一个点,这个点的点权就是原来的边权(原图的点的点权视作 0)
点权转边权:将一个点拆分成两个点,用一条边连起来,新边的边权就是该点的点权(原图的边的边权视作 0)
其它情况:也可以用 min/max 等价转换 http://codeforces.com/problemset/problem/915/F
TIPS: 使用一个 fa 数组(初始化为 -1)记录搜索树中的节点的父节点,这样对每个节点都有一条到根的路径(根的 fa 为 -1)
NOTE: 独立集相关问题,可以从染色的角度考虑
NOTE: 度数大于 √M 的点不超过 2√M 个
相关题目 & 无向图定向 https://leetcode-cn.com/problems/minimum-degree-of-a-connected-trio-in-a-graph/solution/gei-wu-xiang-tu-ding-xiang-by-lucifer100-c72d/
https://oeis.org/A031878 Maximal number of edges in Hamiltonian path in complete graph on n nodes
a(n) = C(n, 2) n%2==0
a(n) = C(n, 2)-n/2+1 n%2==1
环与独立集 https://codeforces.com/problemset/problem/1364/D
匹配与独立集 https://codeforces.com/problemset/problem/1198/C
建图 https://codeforces.com/problemset/problem/1635/E
归纳 https://codeforces.com/problemset/problem/412/D
构造 https://codeforces.com/problemset/problem/41/E
转换 https://codeforces.com/problemset/problem/788/B
转换 https://codeforces.com/problemset/problem/788/C
加边 https://codeforces.com/problemset/problem/723/E
第k小路径 https://codeforces.com/problemset/problem/1196/F
给一无向图,从中删除恰好一条边,求可以让图变成二分图的所有边的下标 https://codeforces.com/problemset/problem/19/E
倒水问题 https://www.luogu.com.cn/problem/P1432
顶点有限制的生成树 https://codeforces.com/problemset/problem/723/F
Trémaux tree https://en.wikipedia.org/wiki/Tr%C3%A9maux_tree
DFS 树与 BFS 树 https://atcoder.jp/contests/abc251/tasks/abc251_f
证明 https://atcoder.jp/contests/abc251/editorial/3987
奇妙 BFS https://codeforces.com/problemset/problem/1651/D
竞赛图
竞赛图的一些性质 https://www.cnblogs.com/acha/p/9042984.html
- SCC 的拓扑序是唯一的
- 拓扑序上,不同 SCC 的点的入度,越靠前的严格越小
https://codeforces.com/problemset/problem/1498/E
https://codeforces.com/problemset/problem/1514/E
todo 竞赛图与三元环 https://codeforces.com/problemset/problem/117/C
定义连通性
https://codeforces.com/problemset/problem/1689/E
todo《挑战》例题+练习题
2.5 节 - 最短路 & 最小生成树
3255 https://www.luogu.com.cn/problem/P2865 次短路
3723 http://poj.org/problem?id=3723 建模+MST
3169 https://www.luogu.com.cn/problem/P4878 差分约束
2139 http://poj.org/problem?id=2139 Floyd
3259 https://www.luogu.com.cn/problem/P2850 多源 SPFA(建议读原文,洛谷翻译不完整)
3268 https://www.luogu.com.cn/problem/P1821 反图 Dij
https://onlinejudge.u-aizu.ac.jp/problems/2249 Dij 的过程中更新花费,注意距离相等时取花费最小值
https://onlinejudge.u-aizu.ac.jp/problems/2200 todo
1258 https://www.luogu.com.cn/problem/P1546 Prim
2377 http://poj.org/problem?id=2377 最大生成树
https://onlinejudge.u-aizu.ac.jp/problems/2224 为了让原图无环,需要去除不在最大生成树上的边
2395 https://www.luogu.com.cn/problem/P1547 最小生成树的最长边:Kruskal 中最后一条加入 MST 中的边的长度
3.5 节 - 二分图
3041
3057
1274
2112
1486
1466
3692
2724
2226
AOJ 2251
3.5节 - 网络流
最大流
3281
3469
3713
2987
2914
3155
最小费用流
2135
2175
3686
3680
3068
2195
3422
AOJ 2266
AOJ 2230
4.3 节 - SCC & 2SAT
2186
3683
3180
1236
3678
2723
2749
*/
// namespace
type graph struct{}
// len(g[v]) 表示结点 v 在无向图上的度/有向图上的出度
// 对于树来说叶结点有 len(g[v]) == 1
func (*graph) readGraph(in io.Reader, n, m int) [][]int {
g := make([][]int, n)
for i := 0; i < m; i++ {
var v, w int
Fscan(in, &v, &w)
v--
w--
g[v] = append(g[v], w)
g[w] = append(g[w], v)
}
return g
}
// 链式前向星
// https://oi-wiki.org//graph/save/#_14
func (*graph) readGraphList(in io.Reader, n, m int) {
type edge struct{ to, prev int }
edgeID := make([]int, n)
for i := range edgeID {
edgeID[i] = -1
}
edges := make([]edge, m) // 2*m
for i := 0; i < m; i++ {
var v, w int
Fscan(in, &v, &w)
v--
w--
edges[i] = edge{w, edgeID[v]}
edgeID[v] = i
}
// loop all edges start at v
var v int
for i := edgeID[v]; i != -1; {
e := edges[i]
w := e.to
_ = w // do(w)
i = e.prev
}
}
// https://atcoder.jp/contests/arc111/tasks/arc111_b
// EXTRA: 先染色,再递归 https://codeforces.com/problemset/problem/1470/D
// 无向图后向边定向 https://codeforces.com/problemset/problem/1519/E
// https://codeforces.com/problemset/problem/1176/E
// 与 MST 结合 https://codeforces.com/problemset/problem/1707/C
func (*graph) dfs(n, st int, g [][]int) {
vis := make([]bool, n)
var cntV, cntE int
var f func(int)
f = func(v int) {
vis[v] = true
cntV++
cntE += len(g[v])
for _, w := range g[v] {
if !vis[w] {
f(w)
}
}
}
for i, b := range vis {
if !b { // && len(g[i]) > 0
cntV, cntE = 0, 0
f(i) // 注意自环和重边
cntE /= 2 // 无向图
if cntV-1 == cntE {
// 树
} else {
// 有环
}
}
}
{
// 奇偶标记法
// https://codeforces.com/problemset/problem/936/B
vis := make([][2]bool, n)
var f func(int, int8)
f = func(v int, step int8) {
vis[v][step] = true
// ...
for _, w := range g[v] {
if !vis[w][step^1] {
f(w, step^1)
}
}
}
f(st, 0)
}
{
// 欧拉序列
eulerPath := []int{}
vis := make([]bool, n)
var f func(int)
f = func(v int) {
eulerPath = append(eulerPath, v)
vis[v] = true
for _, w := range g[v] {
if !vis[w] {
f(w)
eulerPath = append(eulerPath, v)
}
}
}
f(st)
}
{
// 有向图的环/回边检测/012染色
//《算法导论》p.353 边的分类
// vis[v] == 0:该顶点未被访问
// vis[v] == 1:该顶点已经被访问,其子树未遍历完
// vis[v] == 2:该顶点已经被访问,其子树已遍历完
// LC802 https://leetcode-cn.com/problems/find-eventual-safe-states/
// http://codeforces.com/problemset/problem/25/D
// https://codeforces.com/problemset/problem/698/B
// https://codeforces.com/problemset/problem/936/B
// https://codeforces.com/problemset/problem/1217/D 给一个有向图着色,使得没有一个环只有一个颜色,求使用的颜色数量的最小值
// https://codeforces.com/problemset/problem/1547/G
color := make([]int8, n)
var f func(int)
f = func(v int) {
color[v] = 1
for _, w := range g[v] {
if c := color[w]; c == 0 { // 未访问过,即 DFS 树上的树边【树枝边】
f(w)
} else if c == 1 { // 后向边,说明有环
} else { // 前向边或横向边,说明有多条路径可以到 w
}
}
color[v] = 2
}
for i, c := range color {
if c == 0 {
f(i)
}
}
}
{
// 无向图分类:无环/自环/一般环
// https://codeforces.com/contest/1770/problem/D
c := 0 // 默认:无环
var f func(int, int)
f = func(v, fa int) {
vis[v] = true
for _, w := range g[v] {
if w != fa {
if w == v {
// 自环
c = 1
} else if vis[w] { // 返祖边或者横向边(v 连向不在子树 v 上的点 w)
// 一般环
c = 2
} else { // 树枝边
f(w, v)
}
}
}
}
_ = c
f(0, -1)
}
{
// 无向图: DFS 找长度至少为 k 的环
// 注:如果只有一个环(基环树),见 pseudotree
// 模板题 https://codeforces.com/problemset/problem/263/D
// https://codeforces.com/problemset/problem/1325/F
var k, end, st int
fa := make([]int, n)
dep := make([]int, n)
var f func(v, p, d int) bool
f = func(v, p, d int) bool {
fa[v] = p
dep[v] = d
for _, w := range g[v] {
if dep[w] == 0 {
if f(w, v, d+1) {
return true
}
} else if d-dep[w] >= k {
end, st = v, w
return true
}
}
return false
}
f(st, -1, 1)
cycle := []interface{}{st + 1} // for print
for v := end; v != st; v = fa[v] {
cycle = append(cycle, v+1)
}
}
// 其它找环题目
// https://codeforces.com/contest/1817/problem/B
}
// DFS 应用:求连通分量以及每个点所属的连通分量 (Connected Component, CC)
// ccIDs 的值从 1 开始
func (*graph) calcCC(n int, g [][]int) (comps [][]int, ccIDs []int) {
ccIDs = make([]int, n)
idCnt := 0 // 也可以去掉,用 len(comps)+1 代替
var comp []int
var f func(int)
f = func(v int) {
ccIDs[v] = idCnt
comp = append(comp, v)
for _, w := range g[v] {
if ccIDs[w] == 0 {
f(w)
}
}
}
for i, id := range ccIDs {
if id == 0 {
idCnt++
comp = []int{}
f(i)
comps = append(comps, comp)
}
}
return
}
// BFS
// 基础题 https://leetcode.cn/problems/keys-and-rooms/
// 建模 https://codeforces.com/problemset/problem/1272/E
// 锻炼分类讨论能力 https://codeforces.com/contest/1790/problem/G
// 带撤销的 BFS https://codeforces.com/problemset/problem/1721/D
func (*graph) bfs(n, st int, g [][]int) {
vis := make([]bool, n)
vis[st] = true
q := []int{st}
for len(q) > 0 {
v := q[0]
q = q[1:]
// do v...
for _, w := range g[v] {
if !vis[w] {
vis[w] = true
q = append(q, w)
}
}
}
{
// 构建深度数组/最短路
dep := make([]int, n)
for i := range dep {
dep[i] = -1
}
dep[st] = 0
q := []int{st}
for len(q) > 0 {
v := q[0]
q = q[1:]
// do(v, dep[v]) ...
for _, w := range g[v] {
if dep[w] == -1 {
dep[w] = dep[v] + 1
q = append(q, w)
}
}
}
}
{
// 全源最短路
dist := make([][]int, n)
for i := range dist {
dist[i] = make([]int, n)
for j := range dist[i] {
dist[i][j] = -1
}
dist[i][i] = 0
q := []int{i}
for len(q) > 0 {
v := q[0]
q = q[1:]
for _, w := range g[v] {
if dist[i][w] == -1 {
dist[i][w] = dist[i][v] + 1
q = append(q, w)
}
}
}
}
}
{
// BFS with rollback
vis = make([]bool, n)
vis[st] = true
vs := []int{st}
type pair struct{ v, fa int }
q := []pair{{st, -1}}
outer:
for len(q) > 0 {
p := q[0]
q = q[1:]
v, fa := p.v, p.fa
for _, w := range g[v] {
if !vis[w] {
vis[w] = true
q = append(q, pair{w, v})
vs = append(vs, w)
} else if w != fa {
// ... (兼容自环和重边)
break outer // 提前退出的情况
}
}
}
for _, v := range vs {
vis[v] = false
}
}
{
// BFS 012 染色
// 0 不在队列,未访问
// 1 在队列,未访问
// 2 不在队列,已访问
// 相关题目 https://codeforces.com/contest/1385/problem/E
vis := make([]int8, n)
vis[st] = 1
q := []int{st}
for len(q) > 0 {
v := q[0]
q = q[1:]
// do v...
for _, w := range g[v] {
if vis[w] == 0 {
vis[w] = 1
q = append(q, w)
}
}
vis[v] = 2
}
}
}
// 字典序最小最短路
// 入门经典第二版 p.173
// 理想路径(NEERC10)https://codeforces.com/gym/101309 I 题
// 从终点倒着 BFS 求最短路,然后从起点开始一层一层向终点走,每一步都选颜色最小的,并记录最小颜色对应的所有节点,供下一层遍历
// 如果求的是字典序最小的顶点,每一步需选择符合 dis[w] == dis[v]-1 的下标最小的顶点
// LC499 https://leetcode.cn/problems/the-maze-iii/
func (*graph) lexicographicallySmallestShortestPath(g [][]struct{ to, color int }, st, end int) []int {
const inf int = 1e9
dis := make([]int, len(g))
for i := range dis {
dis[i] = inf
}
dis[end] = 0
q := []int{end}
for len(q) > 0 {
v := q[0]
q = q[1:]
for _, e := range g[v] {
if w := e.to; dis[v]+1 < dis[w] {
dis[w] = dis[v] + 1
q = append(q, w)
}
}
}
if dis[st] == inf {
return nil
}
colorPath := []int{}
check := []int{st}
inC := make([]bool, len(g))
inC[st] = true
for loop := dis[st]; loop > 0; loop-- {
minC := inf
tmp := check
check = nil
for _, v := range tmp {
for _, e := range g[v] {
if w, c := e.to, e.color; dis[w] == dis[v]-1 {
if c < minC {
for _, w := range check {
inC[w] = false
}
minC, check, inC[w] = c, []int{w}, true
} else if c == minC && !inC[w] {
check = append(check, w)
inC[w] = true
}
}
}
}
colorPath = append(colorPath, minC)
}
return colorPath
}
// BFS 应用:求无向无权图最小环长度
// 好题 https://codeforces.com/problemset/problem/1325/E
// LC2608 https://leetcode.cn/problems/shortest-cycle-in-a-graph/
/* 注意不能提前推出(哪怕是遍历完一个找到环的点的所有邻居)
0 3
0 5
3 4
4 5
1 9
1 11
9 10
11 10
2 6
2 8
6 7
8 7
0 1
0 2
1 2
*/
func (*graph) shortestCycleBFS(n int, g [][]int, min func(int, int) int) int {
const inf int = 1e9
ans := inf
dis := make([]int, n)
for st := range g {
for i := range dis {
dis[i] = -1
}
dis[st] = 0
type pair struct{ v, fa int }
q := []pair{{st, -1}}
for len(q) > 0 {
p := q[0]
q = q[1:]
v, fa := p.v, p.fa
for _, w := range g[v] {
if dis[w] == -1 {
dis[w] = dis[v] + 1
q = append(q, pair{w, v})
} else if w != fa {
ans = min(ans, dis[w]+dis[v]+1)
}
}
}
}
return ans
}
// 欧拉图(欧拉回路) 半欧拉图(欧拉路径)
// 半欧拉图:具有欧拉路径而无欧拉回路的图
// 判别法如下 https://oi-wiki.org/graph/euler/#_3
// 无向图-欧拉回路:连通且没有奇度数点
// 无向图-欧拉路径:连通且恰有 0 或 2 个奇度数点(若有则选择其中一奇度数点为起点)
// 有向图-欧拉回路:SCC 只有一个且每个点的入度和出度相同
// 有向图-欧拉路径:1. 对应的无向图是连通的;2. 若每个点的入度和出度相同则起点任意;否则起点的出度比入度多一,终点的入度比出度多一,且其余点的入度和出度相同
//
// 逐步插入回路法(Hierholzer 算法)https://oi-wiki.org/graph/euler/
// todo 混合图欧拉回路
// https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/EulerianCycle.java.html
// https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/EulerianPath.java.html
// https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/DirectedEulerianCycle.java.html
// https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/DirectedEulerianPath.java.html
// https://algs4.cs.princeton.edu/42digraph/DirectedEulerianCycle.java.html
// NOTE: 递归前对边排序可保证输出的是字典序最小的路径
// 模板题(输出顶点)
// - 无向图 https://www.luogu.com.cn/problem/P2731 https://www.luogu.com.cn/problem/P1341
// - 有向图 https://www.luogu.com.cn/problem/P7771 LC332 https://leetcode-cn.com/problems/reconstruct-itinerary/solution/javadfsjie-fa-by-pwrliang/
// 模板题(输出边)
// - 有向图 LC2097 https://leetcode-cn.com/problems/valid-arrangement-of-pairs/
// 构造 https://ac.nowcoder.com/acm/contest/4010/H
// 构造 https://codeforces.com/problemset/problem/1511/D
// 虚点 https://codeforces.com/problemset/problem/723/E
// 转换 https://codeforces.com/problemset/problem/1361/C
// https://codeforces.com/problemset/problem/1186/F
func (*graph) eulerianPathOnUndirectedGraph(n, m int) []int {
// 无向图
type neighbor struct{ to, eid int }
g := make([][]neighbor, n)
// read g ...
// 排序,保证字典序最小
for _, es := range g {
sort.Slice(es, func(i, j int) bool { return es[i].to < es[j].to })
}
var st int
oddDegCnt := 0
for i := len(g) - 1; i >= 0; i-- { // 倒着遍历保证起点的字典序最小
if deg := len(g[i]); deg > 0 {
if deg&1 == 1 {
st = i
oddDegCnt++
} else if oddDegCnt == 0 {
st = i
}
}
}
if oddDegCnt > 2 {
return nil
}
// NOTE: 若没有奇度数,则返回的是欧拉回路
path := make([]int, 0, len(g)) // m
vis := make([]bool, m)
var f func(int)
f = func(v int) {
for len(g[v]) > 0 {
e := g[v][0]
g[v] = g[v][1:]
i := e.eid
if vis[i] {
continue
}
vis[i] = true
w := e.to
f(w)
// 输出边的写法,注意是倒序
// path = append(path, i)
}
// 输出点的写法,最后需要反转 path
path = append(path, v)
}
f(st) // for i := range g { f(i) }
for i, n := 0, len(path); i < n/2; i++ {
path[i], path[n-1-i] = path[n-1-i], path[i]
}
return path
}
func (*graph) eulerianPathOnDirectedGraph(n, m int) []int {
// 有向图
type neighbor struct{ to, eid int }
g := make([][]neighbor, n)
inDeg := make([]int, n) // 统计入度
// read g ...
// 排序,保证字典序最小
for _, es := range g {
sort.Slice(es, func(i, j int) bool { return es[i].to < es[j].to })
}
st := -1
end := -1
for i, es := range g {
if len(es) == inDeg[i]+1 { // 出度比入度大一,为起点
if st >= 0 {
return nil // 无欧拉路径
}
st = i
//break // 如果保证有欧拉路径就直接 break
}
if len(es)+1 == inDeg[i] { // 入度比出度大一,为终点
if end >= 0 {
return nil // 无欧拉路径
}
end = i
//break
}
}
if st < 0 {
st = 0 // 任选一起点(比如字典序最小),此时返回的是欧拉回路
}
path := make([]int, 0, m+1)
var f func(int)
f = func(v int) {
for len(g[v]) > 0 {
e := g[v][0]
g[v] = g[v][1:]
f(e.to)
// NOTE: 输出边的话移在这里 append e.eid
}
path = append(path, v)
}
f(st)
for i, n := 0, len(path); i < n/2; i++ {
path[i], path[n-1-i] = path[n-1-i], path[i]
}
return path
}
/* Topic - DFS 树
讲解+套题 https://codeforces.com/blog/entry/68138
好题:https://codeforces.com/problemset/problem/1325/F
*/
// 割点(割顶) cut vertices / articulation points
// https://codeforces.com/blog/entry/68138
// https://oi-wiki.org/graph/cut/#_1
// low(v): 在不经过 v 父亲的前提下能到达的最小的时间戳
// 模板题 https://www.luogu.com.cn/problem/P3388
// LC928 https://leetcode-cn.com/problems/minimize-malware-spread-ii/
func (*graph) findCutVertices(n int, g [][]int, min func(int, int) int) (isCut []bool) {
isCut = make([]bool, n)
dfn := make([]int, n) // 值从 1 开始
dfsClock := 0
var f func(v, fa int) int
f = func(v, fa int) int {
dfsClock++
dfn[v] = dfsClock
lowV := dfsClock
childCnt := 0
for _, w := range g[v] {
if dfn[w] == 0 {
childCnt++
lowW := f(w, v)
if lowW >= dfn[v] { // 以 w 为根的子树中没有反向边能连回 v 的祖先(可以连到 v 上,这也算割顶)
isCut[v] = true
}
lowV = min(lowV, lowW)
} else if w != fa { // 找到 v 的反向边 v-w,用 dfn[w] 来更新 lowV
lowV = min(lowV, dfn[w])
}
}
if fa == -1 && childCnt == 1 { // 特判:只有一个儿子的树根,删除后并没有增加连通分量的个数,这种情况下不是割顶
isCut[v] = false
}
return lowV
}
for v, timestamp := range dfn {
if timestamp == 0 {
f(v, -1)
}
}
cuts := []int{}
for v, is := range isCut {
if is {
cuts = append(cuts, v) // v+1
}
}
return
}
// 桥(割边)
// https://oi-wiki.org/graph/cut/#_4
// https://algs4.cs.princeton.edu/41graph/Bridge.java.html
// 模板题 LC1192 https://leetcode-cn.com/problems/critical-connections-in-a-network/
// https://codeforces.com/problemset/problem/1000/E
// 题目推荐 https://cp-algorithms.com/graph/bridge-searching.html#toc-tgt-2
// 与 MST 结合 https://codeforces.com/problemset/problem/160/D
// 与最短路结合 https://codeforces.com/problemset/problem/567/E
// https://codeforces.com/problemset/problem/118/E
// todo 构造 https://codeforces.com/problemset/problem/550/D
func (*graph) findBridges(in io.Reader, n, m int) (isBridge []bool) {
min := func(a, b int) int {
if a < b {
return a
}
return b
}
type neighbor struct{ to, eid int }
type edge struct{ v, w int }
g := make([][]neighbor, n)
edges := make([]edge, m)
for i := 0; i < m; i++ {
var v, w int
Fscan(in, &v, &w)
v--
w--
g[v] = append(g[v], neighbor{w, i})
g[w] = append(g[w], neighbor{v, i})
edges[i] = edge{v, w}
}
isBridge = make([]bool, len(edges))
dfn := make([]int, len(g)) // 值从 1 开始
dfsClock := 0
var f func(int, int) int
f = func(v, fid int) int { // 使用 fid 而不是 fa,可以兼容重边的情况
dfsClock++
dfn[v] = dfsClock
lowV := dfsClock
for _, e := range g[v] {
if w := e.to; dfn[w] == 0 {
lowW := f(w, e.eid)
if lowW > dfn[v] { // 以 w 为根的子树中没有反向边能连回 v 或 v 的祖先,所以 v-w 必定是桥
isBridge[e.eid] = true
}
lowV = min(lowV, lowW)
} else if e.eid != fid { // 找到 v 的反向边 v-w,用 dfn[w] 来更新 lowV
lowV = min(lowV, dfn[w])
}
}
return lowV
}
for v, timestamp := range dfn {
if timestamp == 0 {
f(v, -1)
}
}
// EXTRA: 所有桥边的下标
bridgeEIDs := []int{}
for eid, b := range isBridge {
if b {
bridgeEIDs = append(bridgeEIDs, eid)
}
}
return
}
// 无向图的双连通分量 Biconnected Components (BCC) 也叫重连通图
// v-BCC:任意割点都是至少两个不同 v-BCC 的公共点 广义圆方树
// 每个 v-BCC 的点数就是一个极大环,所有即
// https://oi-wiki.org/graph/bcc/
// https://www.csie.ntu.edu.tw/~hsinmu/courses/_media/dsa_13spring/horowitz_306_311_biconnected.pdf
// 好题 https://codeforces.com/problemset/problem/962/F
// https://leetcode-cn.com/problems/s5kipK/
// 结合树链剖分 https://codeforces.com/problemset/problem/487/E
/*
使用 https://csacademy.com/app/graph_editor/ 显示下面的样例
基础样例 - 一个割点两个简单环
1 2
2 3
3 4
4 1
3 5
5 6
6 7
7 3
基础样例 - 两个割点三个简单环(注意那条含有两个割点的边)
7 3
7 4
1 2
2 3
3 1
3 4
4 5
5 6
6 4
*/
func (G *graph) findVertexBCC(g [][]int, min func(int, int) int) (comps [][]int, bccIDs []int) {
bccIDs = make([]int, len(g)) // ID 从 1 开始编号
idCnt := 0
isCut := make([]bool, len(g))
dfn := make([]int, len(g)) // 值从 1 开始
dfsClock := 0
type edge struct{ v, w int } // eid
stack := []edge{}
var f func(v, fa int) int
f = func(v, fa int) int {
dfsClock++
dfn[v] = dfsClock
lowV := dfsClock
childCnt := 0
for _, w := range g[v] {
e := edge{v, w} // ne.eid
if dfn[w] == 0 {
stack = append(stack, e)
childCnt++
lowW := f(w, v)
if lowW >= dfn[v] {
isCut[v] = true
idCnt++
comp := []int{}
//eids := []int{}
for {
e, stack = stack[len(stack)-1], stack[:len(stack)-1]
if bccIDs[e.v] != idCnt {
bccIDs[e.v] = idCnt
comp = append(comp, e.v)
}
if bccIDs[e.w] != idCnt {
bccIDs[e.w] = idCnt
comp = append(comp, e.w)
}
//eids = append(eids, e.eid)
if e.v == v && e.w == w {
break
}
}
// 点数和边数相同,说明该 v-BCC 是一个简单环,且环上所有的边只属于一个简单环
//if len(comp) == len(eids) {
// for _, eid := range eids {
// onSimpleCycle[eid] = true
// }
//}
comps = append(comps, comp)
}
lowV = min(lowV, lowW)
} else if w != fa && dfn[w] < dfn[v] {
stack = append(stack, e)
lowV = min(lowV, dfn[w])
}
}
if fa == -1 && childCnt == 1 {
isCut[v] = false
}
return lowV
}
for v, timestamp := range dfn {
if timestamp == 0 {
if len(g[v]) == 0 { // 零度,即孤立点(isolated vertex)
idCnt++
bccIDs[v] = idCnt
comps = append(comps, []int{v})
continue
}
f(v, -1)
}
}
// EXTRA: 缩点
// BCC 和割点作为新图中的节点,并在每个割点与包含它的所有 BCC 之间连边
cutIDs := make([]int, len(g))
for i, is := range isCut {
if is {
idCnt++ // 接在 BCC 之后给割点编号
cutIDs[i] = idCnt
}
}
for v, cp := range comps {
v++
for _, w := range cp {
if w = cutIDs[w]; w > 0 {
// add(v,w); add(w,v) ...
}
}
}
return
}
// e-BCC:删除无向图中所有的割边后,剩下的每一个 CC 都是 e-BCC
// 缩点后形成一棵 bridge tree
// 模板题 https://codeforces.com/problemset/problem/1000/E
// 较为综合的一道题 http://codeforces.com/problemset/problem/732/F
func (G *graph) findEdgeBCC(in io.Reader, n, m int) (comps [][]int, bccIDs []int) {
type neighbor struct{ to, eid int }
type edge struct{ v, w int }
g := make([][]neighbor, n)
edges := make([]edge, m)
// *copy* 包含读图
isBridge := G.findBridges(in, n, m)
// 求原图中每个点的 bccID
bccIDs = make([]int, len(g))
idCnt := 0
var comp []int
var f2 func(int)
f2 = func(v int) {
bccIDs[v] = idCnt
comp = append(comp, v)
for _, e := range g[v] {
if w := e.to; !isBridge[e.eid] && bccIDs[w] == 0 {
f2(w)
}
}
}
for i, id := range bccIDs {
if id == 0 {
idCnt++
comp = []int{}
f2(i)
comps = append(comps, comp)
}
}
// EXTRA: 缩点,复杂度 O(M)
// 遍历 edges,若两端点的 bccIDs 不同(割边)则建边
g2 := make([][]int, idCnt)
for _, e := range edges {
if v, w := bccIDs[e.v]-1, bccIDs[e.w]-1; v != w {
g2[v] = append(g2[v], w)
g2[w] = append(g2[w], v)
}
}
// 也可以遍历 isBridge,割边两端点 bccIDs 一定不同