#include<iostream>
#include<algorithm>
using namespace std;
#define Max_Size 0xffffffff
#define cout 6
char Vex[]={'A','B','C','D','E','F'};//储存顶点信息
struct node{
int data;//保存权值最小的顶点信息
int lowst;//保存最小权值
}closedge[cout];
void Fill(unsigned int tree[][cout]){
for(int i=0;i<cout;i++){
for(int j=0;j<cout;j++){
tree[i][j]=Max_Size;//一开始将全部权值都赋值为无穷大
}
}
tree[0][1] = 6; tree[0][2] = 1; tree[0][3] = 5;
tree[1][0] = 6; tree[1][2] = 5; tree[1][4] = 3;
tree[2][0] = 1; tree[2][1] = 5; tree[2][3] = 5;
tree[2][4] = 6; tree[2][5] = 4;tree[3][0] = 5;
tree[3][2] = 5; tree[3][5] = 2;
tree[4][1] = 3; tree[4][2] = 6; tree[4][5] = 6;
tree[5][2] = 4; tree[5][3] = 2; tree[5][4] = 6;//存入无向图顶点权值信息
}
int Min_Edge(struct node*closedge){//寻找最小权值
unsigned int min=Max_Size;
int flag=-1;
for(int i=0;i<cout;i++){
if(closedge[i].lowst<min&&closedge[i].lowst!=0){
min=closedge[i].lowst;
flag=i;
}
}
return flag;//返回权值最小的下一个顶点
}
void Tree_Prim(unsigned int tree[][cout],int s){
for(int i=0;i<cout;i++){
closedge[i].lowst=Max_Size;//一开始将所有点的连接到的最小权值都赋值为无穷大
}
closedge[s].data=s; //假设从s点开始
closedge[s].lowst=0;
for(int i=0;i<cout;i++){//第一次遍历closedge的顶点和权值全部更新与s起始点相关
if(i!=s){
closedge[i].data=s;
closedge[i].lowst=tree[s][i];
}
}
for(int e=1;e<=cout-1;e++){//开始遍历,边数比顶点数少2
int k=Min_Edge(closedge);//每一次遍历都寻找最小权值的下个点
printf("%c---%c\n",Vex[closedge[k].data],Vex[k]);
closedge[k].lowst=0;
for(int i=0;i<cout;i++){
if(tree[k][i]<closedge[i].lowst){//更新接下来的点的最小权值信息
closedge[i].data=k;
closedge[i].lowst=tree[k][i];
}
}
}
}
int main(){
unsigned int tree[cout][cout]={0};
Fill(tree);
printf("Prim:\n");
Tree_Prim(tree,0);
}
算法分析与设计(实验1Prim算法)
最新推荐文章于 2023-05-29 13:10:45 发布