Kruskal algorithm (template)

Source: Internet
Author: User

/*INPUT6101 2 3 each 4 3 5 4 5 6 6 6 6output15*/#include<iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespacestd;Const intn=1e5;structnode{intu,v,w; BOOL operator< (ConstNode &c)Const    {        returnw<c.w;//indicates a sort with w from small to large}}t[n];intn,m;intp[1001];intChaintx) {    //return X==p[x]?p[x]:cha (P[x]);    if(x!=P[x]) {P[x]=cha (P[x]);//always find ancestors .    }    returnp[x];}intcl () {intsum=0, top=0;  for(intI=0; i<m;i++)//start traversing from the first edge    {        intx=t[i].u; inty=t[i].v; X=cha (x); Y=cha (y); if(x!=y)//if not the same ancestor{p[x]=y;//One of the points as the ancestor of another, in order to prevent the formation of loopssum+=T[I].W; Top++;//number of bars of the cumulative connection line        }        if(top==n-1)returnSum//to make n points all connected, at least n-1 edges are required    }    return-1;//Unable to connect}intMain () { while(SCANF ("%d%d", &n,&m)!=eof)//n points, M edge    {         for(intI=1; i<=n;i++) P[i]=i;//and check the set start all initialized to itself         for(intI=0; i<m;i++) {scanf ("%d%d%d", &AMP;T[I].U,&AMP;T[I].V,&AMP;T[I].W//represent the starting point, the end point, the weights respectively} sort (T,t+M);//ensure that the trailing numbers are the smallest of the currentprintf"%d\n", Cl ()); }    return 0;}

Kruskal algorithm (template)

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.