0%

最小生成树

最小生成树

最小生成树(英语:Minimum spanning tree,简称MST)是最小权重生成树(英语:Minimum weight spanning tree)的简称,是一个连通加权无向图中一棵权值最小的生成树

Kruskal算法

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
#include <bits/stdc++.h>
#define int long long
using namespace std;

// Kruskal算法

// 1, 将所有边按权重从小到大排序
// 2, 枚举每条边 a-b, 权重是c
// 如果a, b不连通, 将这条边加入在集合当中

const int N = 1000010;

int n, m;
int p[N];

struct Edge{
int a, b, w;
} edge[N];

bool cmp(Edge x, Edge y) {
return x.w < y.w;
}

int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}

void solve() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int a, b, w;
cin >> a >> b >> w;
edge[i] = {a, b, w};
}
sort(edge, edge + m, cmp);
for (int i = 1; i <= n; i++) p[i] = i;

int ans = 0, cnt = 0;
for (int i = 0; i < m; i++) {
int a = edge[i].a, b = edge[i].b, w = edge[i].w;
a = find(a); b = find(b);
if (a != b) {
p[a] = b;
ans += w;
cnt++;
}
}
if (cnt < n - 1) {
cout << "impossible" << endl;
} else {
cout << ans << endl;
}
}

signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
while (t--) {
solve();
}

return 0;
}

经典例题

口袋的天空

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

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
#include <bits/stdc++.h>
#define int long long
using namespace std;

int n, m, k;
const int N = 1e5;

int p[N];

int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}

struct Edge{
int x, y, l;
} edge[N];

bool cmp(Edge a, Edge b) {
return a.l < b.l;
}

void solve() {
cin >> n >> m >> k;
for (int i = 0; i < m; i++) {
int x, y, l;
cin >> x >> y >> l;
edge[i] = {x, y, l};
}
for (int i = 1; i <= n; i++) {
p[i] = i;
}
sort(edge, edge + m, cmp);
int cnt = 0, ans = 0;
for (int i = 0; i < m; i++) {
int x = edge[i].x, y = edge[i].y, l = edge[i].l;
x = find(x); y = find(y);
if (x != y) {
p[x] = y;
cnt++;
ans += l;
}
if (cnt >= n - k) break;
}
// 棉花糖可以理解为连通块
if (cnt >= n - k) {
cout << ans << endl;
} else {
cout << "No Answer" << endl;
}
}

signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t = 1;
// cin >> t;
while (t--) {
solve();
}

return 0;
}