/**
* @Author: 郑潮安yyds
* @Time: 2021/12/2 16:30.
* @Filename: union_find_set.cpp
* @Software: CLion
*/
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1060;
int n, m, conedEdge, sumLength, s[MAXN], height[MAXN];
int usedEdgeIndex[MAXN];
struct node {
int from, to, dis;
} edge[MAXN];
void init_set() {
for (int i = 0; i <= MAXN; i++) {
s[i] = i;
height[i] = 0;
}
}
/* 查询的递归写法
int find_set(int x) {
if(x!=s[x]) s[x]=find_set(s[x]);
return s[x];
}
*/
int find_set(int x) {
int r = x;
while (s[r] != r) r = s[r];
int i = x, j;
while (i != r) {
j = s[i];
s[i] = r;
i = j;
}
return r;
}
void union_set(int x, int y) {
x = find_set(x);
y = find_set(y);
if (height[x] == height[y]) {
height[x] = height[x] + 1;
s[y] = x;
} else {
if (height[x] < height[y]) s[x] = y;
else s[y] = x;
}
}
void test() {
for (int i = 0; i < 20; i++) {
cout << "The value of no." << i << " is: " << s[i] << endl;
}
}
bool cmp(const node &a, const node &b) {
return a.dis < b.dis;
}
int main() {
freopen("C:\\Users\\30414\\Desktop\\LuoguWeek3\\input.in", "r", stdin);
int t;
t = 1;
//cin >> t;
while (t--) {
cin >> n >> m;
init_set();
for (int i = 1; i <= m; i++)
cin >> edge[i].from >> edge[i].to >> edge[i].dis;
sort(edge + 1, edge + 1 + m, cmp);
for (int i = 1; i <= m; i++) {
if (conedEdge == n - 1) break;
if (find_set(edge[i].from) != find_set(edge[i].to)) {
usedEdgeIndex[i] = i;
union_set(edge[i].from, edge[i].to);
sumLength += edge[i].dis;
conedEdge++;
}
}
for (int i = 1; i <= conedEdge; i++)
cout << "第 " << i << " 条边是从 " << edge[usedEdgeIndex[i]].from << " 到 " << edge[usedEdgeIndex[i]].to
<< "权值为: " << edge[usedEdgeIndex[i]].dis << endl;
cout << "总长度为:" << sumLength << endl;
}
return 0;
}
6_Kruskal算法
最新推荐文章于 2024-08-22 21:24:01 发布