不知道为何数据结构书上总是喜欢用伪代码,其实真实代码多不了几行。也许是为了让学生动手的时候可以动动脑子?
最小生成树用贪心算法可以求得最优解,实现起来没啥营养很简单。不过有多个加了限制条件的扩展版是NP完全问题,就没这么容易求解了。
========================================================================
#include <stdio.h>
#include <stdlib.h>
#define VEX_NUM
6
// max vex num
#define ME 0xffffffff
// maximum edge
typedef unsigned int uint;
uint dist[VEX_NUM][VEX_NUM] =
{
{
0,
6, 1,
5, ME, ME},
{
6,
0, 5, ME,
3, ME},
{
1,
5, 0,
5,
6,
4},
{
5, ME, 5,
0, ME,
2},
{ ME,
3, 6, ME,
0,
6},
{ ME, ME, 4,
2,
6,
0}
};
void mst_prim()
{
struct {
int vex;
uint cost;
} closest_edge[VEX_NUM];
int first = rand() % VEX_NUM;
//
随机选择一个点作为集合U的第一个元素
closest_edge[first].cost = 0;
for (int i = 0; i < VEX_NUM; ++ i)
//
辅助数组初始化
{
if (i != first)
{
closest_edge[i].vex = first;
//
此时U集合只有一个元素V[first],所以必然是first
closest_edge[i].cost = dist[i][first];
//
最短距离就是dist[i][first]
}
}
for (int i = 1; i < VEX_NUM; ++ i)
//
每次选择一个点,故需要运行(n-1)次
{
uint min_cost = ME;
int pick = -1;
for (int j = 0; j < VEX_NUM; ++ j)
//
找出最小的cost的点
{
if (closest_edge[j].cost != 0 && closest_edge[j].cost < min_cost)
{
pick = j;
min_cost = closest_edge[j].cost;
}
}
printf("%d - %d\n", closest_edge[pick].vex, pick);
closest_edge[pick].cost = 0;
for (int j =0; j < VEX_NUM; ++ j)
//
刷新辅助数组
{
if (dist[pick][j] < closest_edge[j].cost)
{
closest_edge[j].vex = pick;
closest_edge[j].cost = dist[pick][j];
}
}
}
}
int main()
{
mst_prim();
return 0;
}