克鲁斯卡尔(Kruskal)算法(只与边相关)
Kruskal算法通过每次向当前最小代价生成树T中加入一条边的方法构造最终的最小生成树T。算法按照边的权值非递减顺序选取边,并将其加入T中。如果所选取的边与T中的边不形成环路,则这条边加入T中。由于图G是联通的,且具有n个顶点(n>0),所以最终恰好选取n-1条边加入T中。
实现代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;
#define MAX 50
int parent[MAX], family[MAX];
int vertex_num, edge_num;
typedef struct Edge //Edge info storage
{
int a;
int b;
int weight;
};
bool cmp(const Edge & a, const Edge & b)
{
return a.weight < b.weight;
}
int find(int x)
{
/* if vertex x is single : parent[x] = x family[x] = 1
if vertex x is attached to another vertex y:
parent[x] = y , family[y] = family[y] + family[x] */
for(;parent[x]!=x;x=parent[x])
;
return x;
}
bool join(int x, int y) //join two vertex set
{
/* vertex set join : if parent[x] = parent[y]
vertex x and vertex y are in the same set */
int root1, root2;
root1 = find(x);
root2 = find(y);
if(root1 == root2) //in the same vertex set
return false;
else if(family[root1] >= family[root2])
{
parent[root2] = root1;
family[root1] += family[root2];
}
else
{
parent[root1] = root2;
family[root2] += family[root1];
}
return true;
}
int main()
{
int ltotal, sum, flag;
Edge edge[MAX];
scanf("%d%d", &vertex_num, &edge_num);
ltotal = 0, sum = 0, flag = 0;
for(int i = 1; i <= vertex_num; ++i) //initialize parent[] and family[]
{
parent[i] = i;
family[i] = 1;
}
for(int i = 1; i <= edge_num ; ++i)
{
scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].weight);
}
sort(edge + 1, edge + 1 + edge_num, cmp); //sort edge by weight of each edge
for(int i = 1; i <= edge_num; ++i)
{
if(join(edge[i].a, edge[i].b))
{
ltotal++; // edge num increment by 1
sum += edge[i].weight; //total weight
cout<<edge[i].a<<"->"<<edge[i].b<<endl;
}
if(ltotal == vertex_num - 1) //MST if edge num = vertex num - 1
{
flag = 1;
break;
}
}
if(flag) printf("%d\n", sum);
else printf("data error.\n");
return 0;
}
输入数据:
7 9
1 2 28
1 6 10
2 3 16
2 7 14
3 4 12
4 5 22
4 7 18
5 6 25
5 7 24
输入数据代表的图及Kruskal算法的结果图:
输出数据:
1->6
3->4
2->7
2->3
4->5
5->6
99
REF:
1,http://blog.csdn.net/niushuai666/article/details/6689285
2,数据结构(C语言版) Ellis Horowitz