#include <iostream>
#include <string>
using namespace std;
typedef struct Edge//边集数组
{
int begin;//边起始下标
int end;//边终止下标
int weight;//边权重
}Edge;
typedef struct Graph
{
string vertex[10];
Edge edge[10];
int num_vertex;
int num_edge;
}Graph;
int get_location(Graph g, string s)
{
int i;
for(i=0;i<g.num_vertex;i++)
{
if(s == g.vertex[i])
return i;
}
return -1;
}
void create_graph(Graph &g)
{
cout<<"请输入顶点数和边数:";
cin>>g.num_vertex>>g.num_edge;
cout<<"请输入顶点:";
int i,j,k;
string s1,s2;
for(i=0;i<g.num_vertex;i++)
cin>>g.vertex[i];
cout<<"请输入边及其对应的权值:"<<endl;
for(k=0;k<g.num_edge;k++)
{
cin>>s1>>s2>>g.edge[k].weight;
i = get_location(g,s1);
j = get_location(g,s2);
g.edge[k].begin = i;
g.edge[k].end = j;
}
}
int cmp(const void *a, const void *b)
{
return ((Edge*)a)->weight - ((Edge*)b)->weight;
}
void minspantree_kruskal(Graph g)
{
cout<<"最小生成树的边为:"<<endl;
int i,j,n=0;
int set[10];//存储每个顶点的father
for(i=0;i<g.num_vertex;i++)
set[i] = i;
qsort(g.edge,g.num_edge,sizeof(g.edge[0]),cmp);
for(i=0;i<g.num_vertex && n<g.num_vertex-1;i++)//n<g.num_vertex-1指最小生成树的边为顶点数减1
{
int p = g.edge[i].begin;
int q = g.edge[i].end;
if(set[p]!=set[q])//如果两个顶点的father不同,说明没有形成环路
{
cout<<g.vertex[p]<<"->"<<g.vertex[q]<<endl;
n++;
for(j=0;j<g.num_vertex;j++)
{
if(set[j] == set[q])//更新顶点的father
set[j]=set[p];
}
}
}
}
int main()
{
Graph g;
create_graph(g);
minspantree_kruskal(g);
return 0;
}