'commit'
This commit is contained in:
50
TangDou/AcWing_TiGao/T3/MinialSpanningTree/1142_Kruskal.cpp
Normal file
50
TangDou/AcWing_TiGao/T3/MinialSpanningTree/1142_Kruskal.cpp
Normal file
@@ -0,0 +1,50 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
const int N = 310, M = 8010;
|
||||
|
||||
// Kruskal用到的结构体
|
||||
struct Node {
|
||||
int a, b, c;
|
||||
bool const operator<(const Node &t) const {
|
||||
return c < t.c; // 边权小的在前
|
||||
}
|
||||
} edge[M];
|
||||
|
||||
int n, m;
|
||||
int p[N];
|
||||
|
||||
int find(int x) {
|
||||
if (p[x] != x) p[x] = find(p[x]);
|
||||
return p[x];
|
||||
}
|
||||
|
||||
int res;
|
||||
|
||||
// Kruskal算法
|
||||
void kruskal() {
|
||||
// 1、按边权由小到大排序
|
||||
sort(edge, edge + m);
|
||||
// 2、并查集初始化
|
||||
for (int i = 1; i <= n; i++) p[i] = i;
|
||||
// 3、迭代m次
|
||||
for (int i = 0; i < m; i++) {
|
||||
int a = edge[i].a, b = edge[i].b, c = edge[i].c;
|
||||
a = find(a), b = find(b);
|
||||
if (a != b)
|
||||
p[a] = b, res = c; // 越往后越大
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
cin >> n >> m;
|
||||
|
||||
for (int i = 0; i < m; i++) {
|
||||
int a, b, c;
|
||||
cin >> a >> b >> c;
|
||||
edge[i] = {a, b, c};
|
||||
}
|
||||
kruskal();
|
||||
printf("%d %d\n", n - 1, res);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user