Kruskal
作者:刘伟
#include <iostream>
#include <algorithm>
using namespace std;
/* 定义边(x,y),权为w */
struct edge
{
int x, y;
int w;
};
const int MAX = 26;
edge e[MAX * MAX];
int rank[MAX];/* rank[x]表示x的秩 */
int father[MAX];/* father[x]表示x的父节点 */
int sum; /*存储最小生成树的总权重 */
/* 比较函数,按权值非降序排序 */
bool cmp(const edge a, const edge b)
{
return a.w < b.w;
}
/* 初始化集合 */
void make_set(int x)
{
father[x] = x;
rank[x] = 0;
}
/* 查找x元素所在的集合,回溯时压缩路径 */
int find_set(int x)
{
if (x != father[x])
{
father[x] = find_set(father[x]);
}
return father[x];
}
/* 合并x,y所在的集合 */
int union_set(int x, int y, int w)
{
if (x == y) return 0;
if (rank[x] > rank[y])
{
father[y] = x;
}
else
{
if (rank[x] == rank[y])
{
rank[y]++;
}
father[x] = y;
}
sum += w; //记录权重
return 1;
}
int main()
{
int i, j, k, m, n, t;
char ch;
while(cin >> m && m != 0)
{
k = 0;
for (i = 0; i < m; i++) make_set(i); //初始化集合,m为顶点个数
//对后m-1进行逐行处理
for (i = 0; i < m - 1; i++)
{
cin >> ch >> n; //获取字符(顶点)
for (j = 0; j < n; j++)
{
cin >> ch >> e[k].w; //获取权重
e[k].x = i;
e[k].y = ch - 'A';
k++;
}
}
sort(e, e + k, cmp); //STL中的函数,直接对数组进行排序
sum = 0;
for (i = 0; i < k; i++)
{
int result = union_set(find_set(e[i].x), find_set(e[i].y), e[i].w);
if(result) cout<< e[i].x + 1<< "," << e[i].y + 1 <<endl;
}
cout << sum << endl;
}
system("pause");
return 0;
}