Kruskal算法

来源:互联网 发布:法尔廷斯什么级别 知乎 编辑:程序博客网 时间:2024/06/07 02:59
#include "stdafx.h"
#include<iostream>
#include<algorithm>
using namespace std;
#define n 9
#define max 100
typedef struct edge *link;
 struct edge{
int u,v;
int value;
} e[max];
int  p[max];  //用于记录最小生成树的边
int father[n];
int height[n];
 int cmp(const void *a,const void *b)
 {
     return ((*(edge*)a).value > (*(edge*)b).value ? 1:-1);
 }


void makeset()
{
for(int i=0;i<n;i++)
{
 father[i]=i;
 height[i]=0;
}
}


int Find_set(int x)
{
if(x!=father[x])
   father[x]=Find_set(father[x]);
return (father[x]);


}


void  UnionSet(int x,int y)
{
if(height[x]>height[y])
father[y]=x;
else if(height[x]<height[y])
father[x]=y;
else
{
height[y]++;
father[x]=y;
}


}




int _tmain(int argc, _TCHAR* argv[])
{
int i,j,x,y,h=0,sum=0,k=0;
int en[n][n]={{0,4,0,0,0,0,0,8,0},
 {4,0,8,0,0,0,0,11,0},
 {0,8,0,7,0,4,0,0,2},
 {0,0,7,0,9,14,0,0,0},
 {0,0,0,9,0,10,0,0,0},
 {0,0,4,14,10,0,2,0,0},
 {0,0,0,0,0,2,0,1,6},
 {8,11,0,0,0,0,1,0,7},
 {0,0,2,0,0,0,6,7,0}};
 for(i=0;i<n;i++)
 for(j=i;j<n;j++)
  {
  if(en[i][j]!=0)
  {
  e[k].u=i;
  e[k].v=j;
  e[k].value=en[i][j];
  k++;//k边的条数
  }
  }
makeset();
 qsort(e,k,sizeof(struct edge),cmp);
for(i=0;i<k;i++)
{
x=Find_set(e[i].u);
y=Find_set(e[i].v);
if(x!=y)
{
UnionSet(x,y);
sum+=e[i].value;
p[h++]=i;   //存放最小生成树的边


}
else {}
}
printf("最小生成树的代价为:%d\n",sum);
printf("最小生成树的各边及权值依次为:\n");
for(i=0;i<h;i++)
printf("边%c - %c 权值:%d \n",e[p[i]].u+'a',e[p[i]].v+'a',e[p[i]].value);
return 0;
}

0 0