Minimum spanning tree and check set shortest path

Source: Internet
Author: User

#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", &AMP;E[I].U,&AMP;E[I].V,&AMP;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.