Kruskal algorithm + and check set

Source: Internet
Author: User

Algorithm Essentials: the most difficult point of the Kruskal algorithm is how to determine whether to join the edge (x, Y) after the formation of a ring.

The problem can be as follows: judging the two vertices x, y of the Edge (x, Y) is the most connected in the graph (actually forest) Mst. If it is already connected, the joining Edge will form a ring;

In the Kruskal algorithm, the merging and finding of the set is Used.

and check the Set:

1 intGETFA (intK//find the most ancestors2 {3     if(fa[k]==k)returnk;4fa[k]=GETFA (fa[k]);5     returnfa[k];6 }7 8 voidMergeintXintY//Merging Ancestors9 {Ten     intfx=GETFA (x); one     intfy=GETFA (y); afa[fx]=fy; - } -  the BOOLJudgeintXintY//judgment is not an ancestor - { -     intfx=GETFA (x); -     intfy=GETFA (y); +     returnfx==fy; -}

Kruskal algorithm Core:

1  for(intI=1; i<=n;i++)2fa[i]=i;3Sort (e+1, e+1+len,mys);4 intCal=0;5  for(intI=1; i<=len;i++)6 {7     intv=GETFA (e[i].x);8     intu=GETFA (e[i].y);9     if(v!=U)Ten     { one Merge (v,u); a                 //Add according to test instructions -         if(++cal==n-1) -         { the              break; -         } -     } -}


1 intfa[maxn];2 intlen=0;3 structnode4 {5     intx,y,v;6 }e[maxn];7 8 voidInitintXxintYyintVv)9 {Ten     if(yy<0|| Yy>n*m)return; onee[++len].y=yy; ae[len].x=xx;e[len].v=vv; - } -  the intMain () - { -Memset (e,0,sizeof(e)); -Cin>>n>>m; +      for(intI=1; i<=m;i++) -     { +         intxx,yy,vv; aCin>>xx>>yy>>vv; at Init (xx,yy,vv); - Init (yy,xx,vv); -}

Kruskal algorithm + and check set

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: 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.