#include <stdio.h> #include <stdlib.h>struct edge{int u;int v;int w;//in order to conveniently sort through a structure here to store the relationship of the edge}e[10];int n,m int f[10]={0},sum=0,count=0;//and check set some variables need to get//f array size is set according to the actual situation, to be larger than the maximum value of n 1//sort int cmp (const void *a,const void *b) {return ((struct edge *) a)->w-((struct edge *) b)->w);} int getf (int u) {if (f[u]==u) return U;ELSE{F[U]=GETF (F[u]); return f[u];}} int merge (int u,int v) {int t1,t2;t1=getf (u);//Search for ancestor node t2=getf (v);//Find Ancestor node if (T1!=T2)//Determine whether two points are in the same set {F[t2]=t1;return 1 ;//If the value of the ancestor node is different, the}elsereturn 0;//is the same in a collection}int main () {int i;//reads N and m,n represents the number of vertices, m represents the number of edges of the bar scanf ("%d%d", &n,&m );//Read into the edge, where a struct is used to store the relationship for the Edge for (i=1;i<=m;i++) scanf ("%d%d%d", &E[I].U,&E[I].V,&E[I].W); Qsort (E,m+1, sizeof (E[0]), CMP);//and set initialization for (i=1;i<=n;i++) {f[i]=i;} Kruskal algorithm core for (i=1;i<=m;i++) {if (merge (E[I].U,E[I].V) ==1)//two points not in one set {count++;//plus number of edges sum=sum+e[i].w;// Calculate the minimum and}if (count==n-1)//Know the selection of n-1 jump after exiting the loop break;} for (i=1;i<=m;i++) {printf ("%d%d%d\n", E[I].U,E[I].V,E[I].W);} printf ("%d\n", sum);//output minimumPath return 0;}
Minimum spanning tree and check set shortest path