#define MAX 2000 //最大顶点数量
#define INFINITY 999999 //无穷大
typedef struct MinHeap{
int num;//存储顶点序号
int w; //存储顶点到最小生成树的距离
} MinHeap; //最小堆结构体
int map[MAX][MAX] = {0};//邻接矩阵存储图信息
void CreatGraph(int m, int n);//创建邻接矩阵图
void CreatGraph_2(int m, int n);//创建邻接矩阵图(随机图)
void PrintGraph(int n);//输出图
void Prime(int n, int v0);//Prime算法求最小生成树(原始版本)
void Prime_MinHeap(int n, int v0);//Prime算法求最小生成树(优先队列版本)
void BuildMinHeap(MinHeap que[], int n);
void MinHeapSiftDown(MinHeap que[], int n, int pos);
void MinHeapSiftUp(MinHeap que[], int n, int pos);
void ChangeKey(MinHeap que[], int pos, int weight);//将第pos个元素的关键字值改为weight
int SearchKey(MinHeap que[], int pos, int weight);//查找最小堆中关键字值为k的元素下标,未找到则返回-1(非递归)
int ExtractMin(MinHeap que[]);//删除并返回最小堆中具有最小关键字的元素
void CreatGraph(int m, int n)//创建邻接矩阵图
{
int i, j, a, b, c;
for (i=0; i<n; i++) //初始化顶点数据
{
for (j=0; j<n; j++)
{
map[i][j] = (i == j) ? 0 : INFINITY;
}
}
printf("\n请按照a b c格式输入边信息:\n");
for (i=0; i<m; i++)
{
scanf("%d%d%d", &a,&b,&c);
map[a][b] = map[b][a] = c;
}
}
void CreatGraph_2(int m, int n)//创建邻接矩阵图(随机图)
{
int i, j, a, b, c;
for (i=0; i<n; i++) //初始化顶点数据
{
for (j=0; j<n; j++)
{
map[i][j] = (i == j) ? 0 : INFINITY;
}
}
for (i=1; i<n; i++)//确保是连通图
{
map[i][0] = map[0][i] = rand() % 100 + 1;
}
m -= n - 1;
while (m > 0)
{
for (i=0; i<n; i++)
{
for (j=i+1; j<n; j++)
{
if (rand()%10 == 0) //有10%的概率出现边
{ if (map[j][i] == INFINITY) { map[i][j] = map[j][i] = rand() % 100 + 1; m--; if (m == 0) return; }
}
}
}
}
}
void PrintGraph(int n)//输出图
{
int i, j;
for (i=0; i<n; i++)
{
printf("G[%d] = %d: ", i, i);
for (j=0; j<n; j++)
{
if (map[i][j] != 0 && map[i][j] != INFINITY)
printf("<%d, %d> = %d", i, j, map[i][j]);
}
printf("\n");
}
printf("\n");
}
void Prime(int n, int v0)//Prime算法求最小生成树(原始版本)
{
int book[MAX] = {0}; //标记该顶点是否已经在路径中
int dic[MAX] = {0}; //存储顶点到最小生成树的距离
int adj[MAX] = {0}; //存储顶点在最小生成树树中的邻接点序号
int min, i, j, k;
for (i=1; i<n; i++) //每趟确定一个新顶点,共n-1趟
{
min = INFINITY;
k = v0;
for (j=0; j<n; j++)//找出离最小生成树最近的顶点k
{
if (book[j] == 0 && dic[j] < min)
{
min = dic[j];
k = j;
}
}
min = 0;
for (i=0; i<n; i++) //输出各顶点在最小生成树中的邻接点及边的长度
{
//printf("<%d, %d> = %d\n", adj[i], i, dic[i]);
min += dic[i];
}
printf("最小生成树总长度(权值)为 %d\n", min);
}
void Prime_MinHeap(int n, int v0)//Prime算法求最小生成树(优先队列版本)
{
int book[MAX] = {0}; //标记该城市是否已经在路径中
int dic[MAX] = {0}; //存储顶点到最小生成树的距离
int adj[MAX] = {0}; //存储顶点在最小生成树树中的邻接点序号
MinHeap que[MAX+1];//最小堆用来存储顶点序号和到最小生成树的距离
int min, i, j, k, pos, K;