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; - } - } -}
Input:
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