最小生成树之Kruskal算法
问题:关键还是定义数据结构问题,还有如何把两个集合合并成一个。
代码:
#include <iostream> #include <cstdlib> using namespace std; #define MAXV 20 #define INFINITY 65535 typedef struct node { int from; int to; int weight; }WGraph; typedef struct map { WGraph arr[MAXV]; int vexs,edges; }*Map; void createGraph(Map &map) //创建图 { int i; cout<<"please input the edges and vexs:"; cin>>map->edges>>map->vexs; for(i=0;i<map->edges;i++) { cout<<"please input from,to,weight of graph:"; cin>>map->arr[i].from>>map->arr[i].to>>map->arr[i].weight; } } void showGraph(Map wg) { int i; cout<<"the num of edges and vexs:"; cout<<wg->edges<<" "<<wg->vexs<<endl; for(i=0;i<wg->edges;i++) { cout<<"("<<wg->arr[i].from<<","<<wg->arr[i].to<<" "<<wg->arr[i].weight<<")"<<endl; } cout<<endl; } void MST_Kruskal(Map map) { int set[MAXV]; int min; int i,j,k,s; int temp; int flag; //访问标志 for(i=0;i<map->edges;i++) { set[i]=i; } for(j=0;j<map->vexs-1;j++) //共有n-1条边 { min=INFINITY; for(k=0;k<map->edges;k++) //查找最小边 { if(set[map->arr[k].from]!=set[map->arr[k].to]) { if(map->arr[k].weight<min) { min=map->arr[k].weight; temp=k; } } } flag=set[map->arr[temp].to]; for(s=0;s<map->edges;s++) //把两个集合合并成一个集合 { if(set[s]==flag) set[s]=set[map->arr[temp].from]; } cout<<"("<<map->arr[temp].from<<","<<map->arr[temp].to<<","<<map->arr[temp].weight<<")"<<endl; //输出最小生成树 } } int main() { Map map; map=(Map)malloc(MAXV*sizeof(struct map)); cout<<"create the map:"<<endl; createGraph(map); cout<<"output the map"; showGraph(map); cout<<"mst_kruskal :"<<endl; MST_Kruskal(map); cout<<endl; return 0; }
运行截图: