求解最小生成树
Kruskal算法(并查集的应用)
参考来自
#include <bits/stdc++.h>
using namespace std;
class Pre
{
int n, pre[1000];
bool path_zip = false;
public:
Pre(int n, bool Path_zip = true)
{
this->n = n;
for (int i = 0; i < n; ++i)
pre[i] = i;
this->path_zip = Path_zip;
}
int find(int x)
{
int r = x;
while (pre[r] != r)
r = pre[r];
int i = x, j;
if (path_zip)
{
while (i != r)
{
j = pre[i];
pre[i] = r;
i = j;
}
}
return r;
}
bool join(int x, int y)
{
int fx = find(x), fy = find(y);
if (fx != fy)
{
pre[fx] = fy;
return true;
}
return false;
}
void Show()
{
for (int i = 0; i < n; ++i)
{
printf("节点%d的父节点为%d\n", i, pre[i]);
}
}
};
struct Node
{
int x, y;
int value;
};
bool Function(Node A, Node B)
{
return A.value < B.value;
}
int main()
{
Node Map[1000];
int n, x, y, value, m;
bool Success = false;
cout << "输入边数:";
cin >> m;
cout << "输入节点数:";
cin >> n;
Pre SET = Pre(n, false);
for (int i = 0; i < m; ++i)
{
cin >> x >> y >> value;
Map[i].x = x;
Map[i].y = y;
Map[i].value = value;
}
int Count = 0;
sort(Map, Map + m, Function);
for (int i = 0; i < m; ++i)
{
if (SET.join(Map[i].x, Map[i].y))
Count += Map[i].value;
else
{
printf("节点:%d与节点:%d重复链接,权重:%d\n", Map[i].x, Map[i].y, Map[i].value);
}
}
SET.Show();
cout << "最短连通路径和:" << Count;
system("pause");
}