问题:关键还是定义数据结构问题,还有如何把两个集合合并成一个。
代码:
#include#include using namespace std;#define MAXV 20#define INFINITY 65535typedef 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 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< edges<<" "< vexs< edges;i++) { cout<<"("< arr[i].from<<","< arr[i].to<<" "< arr[i].weight<<")"< edges;i++) { set[i]=i; } for(j=0;j vexs-1;j++) //共有n-1条边 { min=INFINITY; for(k=0;k edges;k++) //查找最小边 { if(set[map->arr[k].from]!=set[map->arr[k].to]) { if(map->arr[k].weight arr[k].weight; temp=k; } } } flag=set[map->arr[temp].to]; for(s=0;s edges;s++) //把两个集合合并成一个集合 { if(set[s]==flag) set[s]=set[map->arr[temp].from]; } cout<<"("< arr[temp].from<<","< arr[temp].to<<","< arr[temp].weight<<")"<
运行截图: