-
Notifications
You must be signed in to change notification settings - Fork 575
/
graph.go
5483 lines (5095 loc) · 176 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"
"slices"
"sort"
)
/*
本页面的力扣题目已整理至【题单】图论算法(DFS/BFS/拓扑排序/最短路/最小生成树/二分图/基环树/欧拉路径)
https://leetcode.cn/circle/discuss/01LUak/
### DFS 基础
找连通块、判断是否有环等。部分题目做法不止一种。
- [547. 省份数量](https://leetcode.cn/problems/number-of-provinces/)
- [1971. 寻找图中是否存在路径](https://leetcode.cn/problems/find-if-path-exists-in-graph/)
- [797. 所有可能的路径](https://leetcode.cn/problems/all-paths-from-source-to-target/) 1383
- [841. 钥匙和房间](https://leetcode.cn/problems/keys-and-rooms/) 1412
- [2316. 统计无向图中无法互相到达点对数](https://leetcode.cn/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/) 1604
- [1319. 连通网络的操作次数](https://leetcode.cn/problems/number-of-operations-to-make-network-connected/) 1633
- [2492. 两个城市间路径的最小分数](https://leetcode.cn/problems/minimum-score-of-a-path-between-two-cities/) 1680
- [2685. 统计完全连通分量的数量](https://leetcode.cn/problems/count-the-number-of-complete-components/) 1769
- [2192. 有向无环图中一个节点的所有祖先](https://leetcode.cn/problems/all-ancestors-of-a-node-in-a-directed-acyclic-graph/) 1788
- [924. 尽量减少恶意软件的传播](https://leetcode.cn/problems/minimize-malware-spread/) 1869
- [2101. 引爆最多的炸弹](https://leetcode.cn/problems/detonate-the-maximum-bombs/) 1880
- [802. 找到最终的安全状态](https://leetcode.cn/problems/find-eventual-safe-states/) 1962 三色标记法
- [2092. 找出知晓秘密的所有专家](https://leetcode.cn/problems/find-all-people-with-secret/) 2004
- [261. 以图判树](https://leetcode.cn/problems/graph-valid-tree/)(会员题)
- [323. 无向图中连通分量的数目](https://leetcode.cn/problems/number-of-connected-components-in-an-undirected-graph/)(会员题)
### BFS 基础
求最短路等。
- [1311. 获取你好友已观看的视频](https://leetcode.cn/problems/get-watched-videos-by-your-friends/) 1653
- [1129. 颜色交替的最短路径](https://leetcode.cn/problems/shortest-path-with-alternating-colors/) 1780
- [1298. 你能从盒子里获得的最大糖果数](https://leetcode.cn/problems/maximum-candies-you-can-get-from-boxes/) 1825
- [2039. 网络空闲的时刻](https://leetcode.cn/problems/the-time-when-the-network-becomes-idle/) 1865
- [2608. 图中的最短环](https://leetcode.cn/problems/shortest-cycle-in-a-graph/) 1904
### 拓扑排序
学习拓扑排序前,请先完成 [1557. 可以到达所有点的最少点数目](https://leetcode.cn/problems/minimum-number-of-vertices-to-reach-all-nodes/)
- [207. 课程表](https://leetcode.cn/problems/course-schedule/)
- [210. 课程表 II](https://leetcode.cn/problems/course-schedule-ii/)
- [1462. 课程表 IV](https://leetcode.cn/problems/course-schedule-iv/) 1693
- [2115. 从给定原材料中找到所有可以做出的菜](https://leetcode.cn/problems/find-all-possible-recipes-from-given-supplies/) 1679
- [310. 最小高度树](https://leetcode.cn/problems/minimum-height-trees/)
- [802. 找到最终的安全状态](https://leetcode.cn/problems/find-eventual-safe-states/) 1962
- [1203. 项目管理](https://leetcode.cn/problems/sort-items-by-groups-respecting-dependencies/) 2419
- [2603. 收集树中金币](https://leetcode.cn/problems/collect-coins-in-a-tree/) 2712
- [269. 火星词典](https://leetcode.cn/problems/alien-dictionary/)(会员题)
- [444. 序列重建](https://leetcode.cn/problems/sequence-reconstruction/)(会员题)
- [1059. 从始点到终点的所有路径](https://leetcode.cn/problems/all-paths-from-source-lead-to-destination/)(会员题)
- [1136. 并行课程](https://leetcode.cn/problems/parallel-courses/)(会员题)
### 在拓扑序上 DP
- [2050. 并行课程 III](https://leetcode.cn/problems/parallel-courses-iii/) 2084
- [1857. 有向图中最大颜色值](https://leetcode.cn/problems/largest-color-value-in-a-directed-graph/) 2313
### 基环树
[基环树介绍](https://leetcode.cn/problems/maximum-employees-to-be-invited-to-a-meeting/solution/nei-xiang-ji-huan-shu-tuo-bu-pai-xu-fen-c1i1b/)
- [684. 冗余连接](https://leetcode.cn/problems/redundant-connection/) 做法不止一种
- [2359. 找到离给定两个节点最近的节点](https://leetcode.cn/problems/find-closest-node-to-given-two-nodes/) 1715
- [2360. 图中的最长环](https://leetcode.cn/problems/longest-cycle-in-a-graph/) 1897
- [2876. 有向图访问计数](https://leetcode.cn/problems/count-visited-nodes-in-a-directed-graph/) 2210
- [2127. 参加会议的最多员工数](https://leetcode.cn/problems/maximum-employees-to-be-invited-to-a-meeting/) 2449
- [2836. 在传球游戏中最大化函数值](https://leetcode.cn/problems/maximize-value-of-function-in-a-ball-passing-game) 2769
- [2204. 无向图中到环的距离](https://leetcode.cn/problems/distance-to-a-cycle-in-undirected-graph/)(会员题)
- [LCP 21. 追逐游戏](https://leetcode.cn/problems/Za25hA/)
### 单源最短路:Dijkstra
[Dijkstra 算法介绍](https://leetcode.cn/problems/network-delay-time/solution/liang-chong-dijkstra-xie-fa-fu-ti-dan-py-ooe8/)
- [743. 网络延迟时间](https://leetcode.cn/problems/network-delay-time/)
- [2642. 设计可以求最短路径的图类](https://leetcode.cn/problems/design-graph-with-shortest-path-calculator/) 1811
- [1514. 概率最大的路径](https://leetcode.cn/problems/path-with-maximum-probability/) 1846
- [1631. 最小体力消耗路径](https://leetcode.cn/problems/path-with-minimum-effort/) 1948 做法不止一种
- [1368. 使网格图至少有一条有效路径的最小代价](https://leetcode.cn/problems/minimum-cost-to-make-at-least-one-valid-path-in-a-grid/) 2069 也可以 0-1 BFS
- [1786. 从第一个节点出发到最后一个节点的受限路径数](https://leetcode.cn/problems/number-of-restricted-paths-from-first-to-last-node/) 2079
- [1976. 到达目的地的方案数](https://leetcode.cn/problems/number-of-ways-to-arrive-at-destination/) 2095
- [2662. 前往目标的最小代价](https://leetcode.cn/problems/minimum-cost-of-a-path-with-special-roads/) 2154
- [2045. 到达目的地的第二短时间](https://leetcode.cn/problems/second-minimum-time-to-reach-destination/) 2202 也可以 BFS
- [882. 细分图中的可到达节点](https://leetcode.cn/problems/reachable-nodes-in-subdivided-graph/) 2328
- [2203. 得到要求路径的最小带权子图](https://leetcode.cn/problems/minimum-weighted-subgraph-with-the-required-paths/) 2364
- [2577. 在网格图中访问一个格子的最少时间](https://leetcode.cn/problems/minimum-time-to-visit-a-cell-in-a-grid/) 2382
- [2699. 修改图中的边权](https://leetcode.cn/problems/modify-graph-edge-weights/) 2874
- [2093. 前往目标城市的最小费用](https://leetcode.cn/problems/minimum-cost-to-reach-city-with-discounts/)(会员题)
- [2473. 购买苹果的最低成本](https://leetcode.cn/problems/minimum-cost-to-buy-apples/)(会员题)
- [2714. 找到最短路径的 K 次跨越](https://leetcode.cn/problems/find-shortest-path-with-k-hops/)(会员题)
- [2737. 找到最近的标记节点](https://leetcode.cn/problems/find-the-closest-marked-node/)(会员题)
- [LCP 35. 电动车游城市](https://leetcode.cn/problems/DFPeFJ/)
- [LCP 56. 信物传送](https://leetcode.cn/problems/6UEx57/) 也可以 0-1 BFS
### 全源最短路:Floyd
[带你发明 Floyd 算法:从记忆化搜索到递推](https://leetcode.cn/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/solution/dai-ni-fa-ming-floyd-suan-fa-cong-ji-yi-m8s51/)
- [2642. 设计可以求最短路径的图类](https://leetcode.cn/problems/design-graph-with-shortest-path-calculator/) 1811
- [1334. 阈值距离内邻居最少的城市](https://leetcode.cn/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance/) 1855
- [2976. 转换字符串的最小成本 I](https://leetcode.cn/problems/minimum-cost-to-convert-string-i/) 1882
- [2959. 关闭分部的可行集合数目](https://leetcode.cn/problems/number-of-possible-sets-of-closing-branches/) 2077
- [2977. 转换字符串的最小成本 II](https://leetcode.cn/problems/minimum-cost-to-convert-string-ii/) 2696
### 最小生成树:Kruskal/Prim
- [1584. 连接所有点的最小费用](https://leetcode.cn/problems/min-cost-to-connect-all-points/) 1858
- [1489. 找到最小生成树里的关键边和伪关键边](https://leetcode.cn/problems/find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree/) 2572
- [1135. 最低成本连通所有城市](https://leetcode.cn/problems/connecting-cities-with-minimum-cost/)(会员题)
- [1168. 水资源分配优化](https://leetcode.cn/problems/optimize-water-distribution-in-a-village/)(会员题)
### 欧拉路径/欧拉回路:Hierholzer
- [332. 重新安排行程](https://leetcode.cn/problems/reconstruct-itinerary/)
- [753. 破解保险箱](https://leetcode.cn/problems/cracking-the-safe/) 2274
- [2097. 合法重新排列数对](https://leetcode.cn/problems/valid-arrangement-of-pairs/) 2651
### 强连通分量/双连通分量:Tarjan
- [928. 尽量减少恶意软件的传播 II](https://leetcode.cn/problems/minimize-malware-spread-ii/) 1985
- [1192. 查找集群内的关键连接](https://leetcode.cn/problems/critical-connections-in-a-network/) 2085
- [1568. 使陆地分离的最少天数](https://leetcode.cn/problems/minimum-number-of-days-to-disconnect-island/) 2209
- [LCP 54. 夺回据点](https://leetcode.cn/problems/s5kipK/)
### 二分图(染色判定、最大匹配)
部分题目做法不止一种。难度仅供参考。
- [785. 判断二分图](https://leetcode.cn/problems/is-graph-bipartite/) 1625
- [886. 可能的二分法](https://leetcode.cn/problems/possible-bipartition/) 1795
- [1947. 最大兼容性评分和](https://leetcode.cn/problems/maximum-compatibility-score-sum/)
- [1879. 两个数组最小的异或值之和](https://leetcode.cn/problems/minimum-xor-sum-of-two-arrays/) 2145
- [1349. 参加考试的最大学生数](https://leetcode.cn/problems/maximum-students-taking-exam/) 2386
- [2172. 数组的最大与和](https://leetcode.cn/problems/maximum-and-sum-of-array/) 2392
- [1595. 连通两组点的最小成本](https://leetcode.cn/problems/minimum-cost-to-connect-two-groups-of-points/) 2538
- [1066. 校园自行车分配 II](https://leetcode.cn/problems/campus-bikes-ii/)(会员题)
- [1820. 最多邀请的个数](https://leetcode.cn/problems/maximum-number-of-accepted-invitations/)(会员题)
- [2123. 使矩阵中的 1 互不相邻的最小操作数](https://leetcode.cn/problems/minimum-operations-to-remove-adjacent-ones-in-matrix/)(会员题)
- [2403. 杀死所有怪物的最短时间](https://leetcode.cn/problems/minimum-time-to-kill-all-monsters/)(会员题)
- [LCP 04. 覆盖](https://leetcode.cn/problems/broken-board-dominoes/)
### 网络流
做法不止一种。难度仅供参考。
- [2850. 将石头分散到网格图的最少移动次数](https://leetcode.cn/problems/minimum-moves-to-spread-stones-over-grid/) 2001
- [1349. 参加考试的最大学生数](https://leetcode.cn/problems/maximum-students-taking-exam/) 2386
- [2172. 数组的最大与和](https://leetcode.cn/problems/maximum-and-sum-of-array/) 2392
- [LCP 38. 守卫城堡](https://leetcode.cn/problems/7rLGCR/)
### 其它
- [1042. 不邻接植花](https://leetcode.cn/problems/flower-planting-with-no-adjacent/) 1712
- [787. K 站中转内最便宜的航班](https://leetcode.cn/problems/cheapest-flights-within-k-stops/) 1786
- [1761. 一个图中连通三元组的最小度数](https://leetcode.cn/problems/minimum-degree-of-a-connected-trio-in-a-graph/) 2005
- [2508. 添加边使所有节点度数都为偶数](https://leetcode.cn/problems/add-edges-to-make-degrees-of-all-nodes-even/) 2060
- [1579. 保证图可完全遍历](https://leetcode.cn/problems/remove-max-number-of-edges-to-keep-graph-fully-traversable/) 2132
- [2065. 最大化一张图中的路径价值](https://leetcode.cn/problems/maximum-path-quality-of-a-graph/) 2178
- [1697. 检查边长度限制的路径是否存在](https://leetcode.cn/problems/checking-existence-of-edge-length-limited-paths/) 2300
- [2242. 节点序列的最大得分](https://leetcode.cn/problems/maximum-score-of-a-node-sequence/) 2304
- [1928. 规定时间内到达终点的最小花费](https://leetcode.cn/problems/minimum-cost-to-reach-destination-in-time/) 2413
- [2493. 将节点分成尽可能多的组](https://leetcode.cn/problems/divide-nodes-into-the-maximum-number-of-groups/) 2415 **推荐**
- [1782. 统计点对的数目](https://leetcode.cn/problems/count-pairs-of-nodes/) 2457
- [277. 搜寻名人](https://leetcode.cn/problems/find-the-celebrity/)(会员题)
- [1724. 检查边长度限制的路径是否存在 II](https://leetcode.cn/problems/checking-existence-of-edge-length-limited-paths-ii/)(会员题)
- [2077. 殊途同归](https://leetcode.cn/problems/paths-in-maze-that-lead-to-same-room/)(会员题)
- [LCP 16. 游乐园的游览计划](https://leetcode.cn/problems/you-le-yuan-de-you-lan-ji-hua/)
有关【网格图】的题目,见 search.go
### 建图
https://codeforces.com/problemset/problem/765/D 1700
https://codeforces.com/problemset/problem/1635/E 2200
题单 https://www.luogu.com.cn/training/81272#problems
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 等价转换 https://codeforces.com/problemset/problem/915/F
#### 数学归纳法
https://codeforces.com/problemset/problem/1515/F 2600
#### 平面图最小割转最短路
https://www.luogu.com.cn/problem/P4001
https://www.luogu.com.cn/problem/P7916
https://codeforces.com/contest/1749/problem/E 2400
https://codeforces.com/gym/104821/problem/E
TIPS: 使用一个 fa 数组(初始化为 -1)记录搜索树中的节点的父节点,这样对每个节点都有一条到根的路径(根的 fa 为 -1)
NOTE: 独立集相关问题,可以从染色的角度考虑
NOTE: 度数大于 √M 的点不超过 2√M 个
相关题目 & 无向图定向 https://leetcode.cn/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/41/E 1900 构造
https://codeforces.com/problemset/problem/412/D 2000 归纳
https://codeforces.com/problemset/problem/788/B 2100 转换
https://codeforces.com/problemset/problem/723/E 2200 加边
https://codeforces.com/problemset/problem/1196/F 2200 第k小路径
https://codeforces.com/problemset/problem/788/C 2300 转换
https://codeforces.com/problemset/problem/632/F 2400 转换
给一无向图,从中删除恰好一条边,求可以让图变成二分图的所有边的下标 https://codeforces.com/problemset/problem/19/E 2900
倒水问题 https://www.luogu.com.cn/problem/P1432
顶点有限制的生成树 https://codeforces.com/problemset/problem/723/F
辅助证明 https://codeforces.com/contest/1839/problem/E
https://ac.nowcoder.com/acm/contest/68572/H
https://www.luogu.com.cn/problem/P10247
- https://www.luogu.com.cn/contest/157761
集合哈希 set hashing https://codeforces.com/problemset/problem/154/C
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
竞赛图
竞赛图的一些性质 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{}
// 建图:邻接表写法
// g[v] 表示 v 的邻居
func (*graph) readGraph(in io.Reader, n, m int) {
type neighbor struct{ to, wt int }
g := make([][]neighbor, n)
for i := 0; i < m; i++ {
var v, w, wt int
fmt.Fscan(in, &v, &w, &wt)
v--
w--
g[v] = append(g[v], neighbor{w, wt})
g[w] = append(g[w], neighbor{v, wt})
}
}
// 建图:链表写法(链式前向星)
// 节点 v 的邻居形成一条链表(用数组下标代替指针)
// 添加 v 的一个邻居 w 时,用链表的【头插法】把 w 插入到链表的头节点之前
func (*graph) readGraphList(in io.Reader, n, m int) {
type node struct{ to, next int }
head := make([]int, n) // head[i] 表示 i 的邻居链表的头节点
for i := range head {
head[i] = -1 // -1 表示 nil
}
nodes := make([]node, m) // 无向图是 m*2
for i := 0; i < m; i++ {
var v, w int
fmt.Fscan(in, &v, &w)
v--
w--
nodes[i] = node{w, head[v]} // 头插法
head[v] = i
}
// 遍历 v 的所有邻居 w
// 和遍历链表是一样的
var v int
for cur := head[v]; cur != -1; cur = nodes[cur].next {
w := nodes[cur].to
_ = w // do(w) ...
}
}
/* 图上的 DFS
https://codeforces.com/problemset/problem/659/E 1600
https://codeforces.com/problemset/problem/1176/E 1700
https://codeforces.com/contest/1927/problem/F 1900 找包含指定边的环
https://codeforces.com/contest/1547/problem/G 2100 对每个点 i,判断 1 到 i 有多少条路径(0/1/>=2/∞)
https://codeforces.com/problemset/problem/1470/D 2200 先染色,再递归
https://codeforces.com/problemset/problem/1707/C 2400 与 MST 结合
https://codeforces.com/problemset/problem/1519/E 2700 无向图后向边定向
https://atcoder.jp/contests/arc111/tasks/arc111_b
*/
func (*graph) dfs(g [][]int, st int) {
// 代码来自 https://codeforces.com/problemset/problem/659/E
vis := make([]bool, len(g))
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 {
// 有环
}
}
}
// 返回一个以 start 为起点和终点的简单环
// !必须保证 start 在一个环中
// 例如 cycle=[1,2,3] 表示一个 1->2->3->1 的环
// https://codeforces.com/contest/1927/problem/F 先用 tarjan 去掉所有割边
cycleAt := func(start int) []int {
vis := make([]bool, len(g))
cycle := []int{}
var dfs func(int, int) bool
dfs = func(v, fa int) bool {
vis[v] = true
cycle = append(cycle, v) // v+1
for _, w := range g[v] {
if w != fa && (w == start || !vis[w] && dfs(w, v)) {
return true
}
}
cycle = cycle[:len(cycle)-1]
return false
}
dfs(start, -1)
return cycle
}
_ = cycleAt
{
// 奇偶标记法
// https://codeforces.com/problemset/problem/936/B
vis := make([][2]bool, len(g))
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, len(g))
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/problems/find-eventual-safe-states/
// https://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 2100
// 与 AC 自动机结合 https://www.luogu.com.cn/problem/P2444
color := make([]int8, len(g))
var f func(int) bool
f = func(v int) bool {
color[v] = 1
for _, w := range g[v] {
c := color[w]
if c == 0 { // 未访问过,即 DFS 树上的树边【树枝边】
if f(w) {
return true
}
} else if c == 1 { // 后向边,说明有环
return true
} // else: 前向边或横向边,说明有多条路径可以到 w
}
color[v] = 2
return false
}
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 {
continue
}
if w == v {
// 自环
c = 1
} else if vis[w] { // 返祖边 v-anc 或者 anc-v(反向返祖边),例如 1-2-3-1,其中 3-1 和 1-3 都是 vis 状态
// 一般环
c = 2
} else { // 树枝边
f(w, v)
}
}
}
_ = c
f(0, -1)
}
{
// 无向图找长度 >= k 的环
// 注:如果只有一个环(基环树),见 pseudotree
// 模板题 https://codeforces.com/problemset/problem/263/D
// https://codeforces.com/problemset/problem/1325/F
var k, end, begin int
fa := make([]int, len(g))
dep := make([]int, len(g))
var f func(int, int, 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, begin = v, w
return true
}
}
return false
}
f(0, -1, 1)
cycle := []any{begin + 1} // for print
for v := end; v != begin; 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://codeforces.com/problemset/problem/689/B 1600 最短路模板题
https://codeforces.com/problemset/problem/601/A 1600 脑筋急转弯
https://codeforces.com/problemset/problem/1721/D 1800 带撤销的 BFS
https://codeforces.com/problemset/problem/1851/F 1800 带撤销的 BFS
https://codeforces.com/problemset/problem/1272/E 1900 建模
https://codeforces.com/problemset/problem/1790/G 2300 锻炼分类讨论能力
https://codeforces.com/problemset/problem/1874/B 2400
*/
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
}
}
}
// 字典序最小最短路 · 其一
// 路径的点权序列的字典序最小(边权为 1)
// https://codeforces.com/problemset/problem/1209/F 2600
// https://ac.nowcoder.com/acm/contest/76652/B
func (*graph) lexicographicallySmallestShortestPath(g [][]struct{ to, color int }, st, end int) []int {
dis := make([]int, len(g))
from := make([]int, len(g)) // 可选(输出具体路径用)
vis := make([]bool, len(g))
vis[st] = true
q := [][]int{{st}}
for len(q) > 0 {
vs := q[0]
q = q[1:]
type edge struct{ from, to int }
nxt := map[int][]edge{}
for _, v := range vs {
for _, e := range g[v] {
nxt[e.color] = append(nxt[e.color], edge{v, e.to})
}
}
_keys := make([]int, 0, len(nxt))
for k := range nxt {
_keys = append(_keys, k)
}
slices.Sort(_keys)
// 优先走 color 小的边
for _, color := range _keys {
ws := []int{}
for _, e := range nxt[color] {
w := e.to
if !vis[w] {
vis[w] = true
from[w] = e.from // 记录每个节点的前驱
dis[w] = dis[e.from] ^ color
ws = append(ws, w)
}
}
if len(ws) > 0 {
q = append(q, ws)
}
}
}
{
// EXTRA:输出从起点到终点的字典序最小最短路
path := []int{}
for v := end; v != st; v = from[v] {
path = append(path, v)
}
path = append(path, st)
slices.Reverse(path)
}
return dis
}
// 字典序最小最短路 · 其二
// 上面(其一)的做法需要排序,如何避免排序呢?
// 入门经典第二版 p.173:理想路径(NEERC10)https://codeforces.com/gym/101309 I 题
// - 从终点倒着 BFS 求最短路,然后从起点开始一层一层向终点走,每一步都选颜色最小的,并记录最小颜色对应的所有节点,供下一层遍历
// EXTRA: 如果要求路径节点编号的字典序最小,每一步需选择符合 dis[w] == dis[v]-1 的编号最小的顶点
// LC499 https://leetcode.cn/problems/the-maze-iii/
func (*graph) lexicographicallySmallestShortestPath2(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) 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
}
// 欧拉图(欧拉回路) 半欧拉图(欧拉路径)
// 通过图中每条边恰好一次
// 半欧拉图:具有欧拉路径而无欧拉回路的图
// 判定方法:
// 无向图欧拉回路:连通且没有奇度数点(全为偶度数点)
// 无向图欧拉路径:连通且恰有 0 或 2 个奇度数点(若有 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/problems/reconstruct-itinerary/
// 模板题(输出边)
// - 有向图 LC2097 https://leetcode.cn/problems/valid-arrangement-of-pairs/ 2651
// LC753 https://leetcode.cn/problems/cracking-the-safe/ 2274
// https://codeforces.com/problemset/problem/1511/D 1600 构造
// https://codeforces.com/problemset/problem/723/E 2200 虚点
// https://codeforces.com/problemset/problem/209/C 2400 添加边使得图存在欧拉回路
// https://codeforces.com/problemset/problem/1186/F 2400
// https://codeforces.com/problemset/problem/1361/C 2500 转换
// https://codeforces.com/problemset/problem/527/E 2600
// https://ac.nowcoder.com/acm/contest/4010/H 构造
//
// BEST 定理
// https://en.wikipedia.org/wiki/BEST_theorem
// https://cmwqf.github.io/2020/09/12/%E6%B5%85%E8%B0%88BEST%E5%AE%9A%E7%90%86/
// https://luckyglass.github.io/2020/20Nov24thArt1/
// https://www.luogu.com.cn/problem/P5807
// https://atcoder.jp/contests/abc336/tasks/abc336_g
// 无向图欧拉回路/欧拉路径(有向图见下面)
func (*graph) eulerianPathOnUndirectedGraph(m int, g [][]struct{ to, eid int }) []int {
// 排序,保证字典序最小
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: 若没有奇度数,则返回的是欧拉回路
// 注意:如果 m~1e6,建议把 dfs 写在外面,防止 MLE
path := make([]int, 0, len(g)) // m
vis := make([]bool, m)
var dfs func(int)
dfs = 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
dfs(w)
// 输出边的写法,注意是倒序
// path = append(path, i) [2]int{v, w}
}
// 输出点的写法(最后需要反转 path)
path = append(path, v)
}
dfs(st) // for i := range g { dfs(i) }
slices.Reverse(path) // 如果输出的是点
return path
}
// 无向【完全图】欧拉回路/欧拉路径
// 如果 n 是偶数,会去掉一些边
// https://codeforces.com/contest/1981/problem/D 2400
func (*graph) eulerianPathOnUndirectedCompleteGraph(n int) []int {
g := make([]int, n)
vis := make([][]bool, n)
for i := range vis {
vis[i] = make([]bool, n)
}
if n%2 == 0 {
// 去掉 n/2-1 条边,保证至多两个奇度数点
// 如果要求欧拉回路的话,i 改成从 1 开始(去掉 n/2 条边,保证所有点度数都是偶数)
for i := 2; i < n; i += 2 {
vis[i-1][i] = true
vis[i][i-1] = true
}
}
// 不允许自环的话,加上这个 for 循环(注意自环不影响度数的奇偶性)
for i, r := range vis {
r[i] = true
}
// 注意:如果 n~1e3,会导致递归深度 ~1e6,建议把 dfs 写在外面,防止 MLE
path := []int{}
var dfs func(int)
dfs = func(v int) {
for ; g[v] < n; g[v]++ {
w := g[v]
if vis[v][w] {
continue
}
vis[v][w] = true
vis[w][v] = true
dfs(w)
}
path = append(path, v) // 记录节点
}
dfs(0)
slices.Reverse(path)
return path
}
// 有向图欧拉回路/欧拉路径
func (*graph) eulerianPathOnDirectedGraph(m int, g [][]struct{ to, eid int }) []int {
// 读图的时候,统计入度 ...
inDeg := make([]int, len(g))
// 排序,保证字典序最小
for _, es := range g {
sort.Slice(es, func(i, j int) bool { return es[i].to < es[j].to })
}
st := -1
end := -1