Luogu P2764 最小路径覆盖问题

题目描述

https://www.luogu.com.cn/problem/P2764

简要题解:给定一张 $DAG$,求其最小路径覆盖

$n\le 150,m\le 6000$

Solution

我们考虑这样一个建图:

将原图中的所有点拆成两个点 $u$ 和 $u’$,对于原图中的有向边,$u$ 连 $v’$

然后我们考虑这张二分图的一条匹配,匹配中的每一条边都意味着原图两个路径并到了一起,即总路径数减一

所以我们要让匹配尽量大,也就是求最大匹配

至于输出方案,左边没有匹配上的点是一条路径的终点,右边没有匹配上的点是一条路径的起点

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
#include <iostream>
#include <cstdio>
#include <queue>
#define maxn 310
#define maxm 6010
#define INF 1000000000
using namespace std;

int n, m;

struct Edge {
int to, next, w;
} e[2 * maxn + 2 * maxm]; int c1, head[maxn];
inline void add_edge(int u, int v, int w) {
e[c1].to = v; e[c1].w = w;
e[c1].next = head[u]; head[u] = c1++;
}

inline void Add_edge(int u, int v, int w) {
add_edge(u, v, w); add_edge(v, u, 0);
}

int dep[maxn], s, t;
bool bfs() {
fill(dep, dep + maxn, 0); dep[s] = 1;
queue<int> Q; Q.push(s);
while (!Q.empty()) {
int u = Q.front(); Q.pop();
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (w > 0 && !dep[v]) {
dep[v] = dep[u] + 1;
Q.push(v); if (v == t) return 1;
}
}
}
return 0;
}

int dfs(int u, int _w) {
if (u == t || !_w) return _w;
int s = 0;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (w > 0 && dep[v] == dep[u] + 1) {
int di = dfs(v, min(_w - s, w));
e[i].w -= di; e[i ^ 1].w += di;
s += di; if (s == _w) break;
}
}
if (s < _w) dep[u] = 0;
return s;
}

int mf;
void dinic() {
while (bfs()) mf += dfs(s, INF);
}

int nxt[maxn];
int main() { fill(head, head + maxn, -1);
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

cin >> n >> m; s = 0; t = 2 * n + 1;
for (int i = 1; i <= n; ++i)
Add_edge(s, i, 1), Add_edge(i + n, t, 1);
for (int i = 1; i <= m; ++i) {
int x, y; cin >> x >> y;
Add_edge(x, y + n, 1);
} dinic(); vector<int> ans;
for (int u = 1; u <= n; ++u) {
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (v != s && !w) nxt[u] = v - n;
}
for (int i = head[u + n]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i].w;
if (w && v == t) ans.push_back(u);
}
}
for (auto u : ans) {
while (u) cout << u << " ", u = nxt[u];
cout << "\n";
} cout << n - mf << "\n";
return 0;
}