Implementation of Kruskal algorithm

Source: Internet
Author: User

1#include"stdio.h"2#include"stdlib.h"3 structEdge4 {5     intm;6     intN;7     intD;8}a[5010];9 intcmpConst void*a,Const void*B)//sort in ascending orderTen { One     return((structedge*) a)->d-((structedge*) b)D; A } - intMainvoid) - { the     inti,n,t,num,min,k,g,x[ -]; -printf"Please enter the number of vertices:"); -scanf"%d",&n); -t = n * (n-1) /2; +      for(i=1; i<=n;i++) -x[i]=i; +printf"Please enter the starting endpoint and weight for each edge: \ n"); A      for(i=0; i<t;i++) atscanf"%d%d%d", &AMP;A[I].M,&AMP;A[I].N,&AMP;A[I].D);//enter weights for each edge -Qsort (A,t,sizeof(a[0]), CMP); -min=num=0; -          for(i=0; i<t && num < n-1; i++) -         { -              for(K=a[i].m;x[k]!=k;k=x[k])//determines the set where the starting point of a segment is located inx[k]=X[x[k]]; -              for(G=a[i].n;x[g]!=g;g=x[g])//determines the collection where the end point of a segment is located tox[g]=X[x[g]]; +             if(k!=g)//if the two endpoints of a line segment are in a different set -             { thex[g]=K; *min+=a[i].d; $num++;Panax Notoginsengprintf"join edge in minimum spanning tree:%d%d\n", A[I].M,A[I].N); -             } the         } +printf"the weight of the minimum spanning tree is:%d\n", min); A     return 0; the}

Implementation of Kruskal algorithm

Related Article

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.