Luogu P5934 [清华集训2012]最小生成树

题目描述

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

简要题意:给定一个 $n$ 个点 $m$ 条正权边的无向连通图,同时再给定一条边 $(u,v,w)$,求最少删除多少条边才能使这条边既有可能出现在最小生成树上,也有可能出现在最大生成树上

$n\le 20000,m\le 2\times 10^5$

Solution

我们考虑对于一条边 $(u,v,w)$,它怎样才可能出现在最小生成树上

显然是当添加完边权小于 $w$ 的边之后,$u$ 和 $v$ 仍然不连通

也就是说我们只需要求一个以 $u$ 为源点,$v$ 为汇点的最小割即可

对于最大生成树,我们只需要把边权大于 $w$ 的边拿出来做一遍即可

两次答案相加就是最终答案

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

int n, m;

struct node {
int u, v, w;
} a[maxm];

struct Edge {
int to, next, w;
} e[1000010]; 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, w;
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;
if (v == t) return 1; Q.push(v);
}
}
}
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 dinic() {
int mf = 0;
while (bfs()) mf += dfs(s, INF);
return mf;
}

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

cin >> n >> m;
for (int i = 1; i <= m; ++i) cin >> a[i].u >> a[i].v >> a[i].w;
cin >> s >> t >> w; int ans = 0;
for (int i = 1; i <= m; ++i) {
int u = a[i].u, v = a[i].v, w = a[i].w;
if (w < ::w) Add_edge(u, v, 1), Add_edge(v, u, 1);
} ans += dinic();
fill(head, head + maxn, -1); c1 = 0;
for (int i = 1; i <= m; ++i) {
int u = a[i].u, v = a[i].v, w = a[i].w;
if (w > ::w) Add_edge(u, v, 1), Add_edge(v, u, 1);
} ans += dinic();
cout << ans << "\n";
return 0;
}