标签:
从边考虑,
给一些输入,
9 15
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #define MAXEDGE 100 #define MAXVEX 100 #define INFINITY 65535 using namespace std; typedef struct Edge{ int begin; int end; int weight; bool operator < (const struct Edge &a)const{ //排序,sort。。c++的,忘了 return weight<a.weight; } }Edge; typedef struct { Edge edges[MAXVEX]; int numVextexes,numEdges; }MGraph; void CreateGraph(MGraph *G){ //c创建图 int i,j,k,w; printf("输入顶点数和边数:\n"); scanf("%d %d",&j,&k); G->numEdges = k; G->numVextexes = j; for(i=0;i<G->numEdges;i++){ scanf("%d %d %d",&G->edges[i].begin,&G->edges[i].end,&G->edges[i].weight); } sort(G->edges,G->edges+G->numEdges); return; } int Find(int *parent,int f){ //介个.....类似并查集 while(parent[f] > 0){ f = parent[f]; } return f; } void MiniSpanTree_Kruskal(MGraph G){ int i,n,m; CreateGraph(&G); int parent[MAXVEX]; for(i=0;i<G.numVextexes;i++){ parent[i] = 0; } for(i=0;i<G.numEdges;i++){ n = Find(parent,G.edges[i].begin); m = Find(parent,G.edges[i].end); if(n!=m){ //回路? parent[n] = m; printf("(%d,%d),%d ",G.edges[i].begin,G.edges[i].end,G.edges[i].weight); } } } int main(){ MGraph G; MiniSpanTree_Kruskal(G); return 0; }
标签:
原文地址:http://www.cnblogs.com/zhuozhuo/p/5409192.html