Minimum spanning Tree 2 (Kruskal algorithm)

Source: Internet
Author: User

Kruskal algorithm:

1: In accordance with the weight of the edge of the order from small to large to see again, if you do not produce a circle (the heavy Edge also counted), the current edge is added to the spanning tree, the basic algorithm proved to be the same as prim

2: How to determine whether to create a negative circle, assuming now to join the vertex u and Vertex v of the edge e into the spanning tree, if you and V are not in the same Unicom component before joining, then the addition of e will not produce a negative circle, conversely, if you and V in the same connected component, then will be bound to produce a circle, You can use and check to see if it belongs to the same connected component.

The Ps:kruskal algorithm is time-consuming to sort the edges, and the algorithm complexity is O (| E|log| v|)

struct node{    int u,v,w;} edge[max_v*max_v];bool cmp (node A,node b) {    if (A.W<=B.W) return true;    return false;} int find (int x) {    if (X!=father[x]) return find (Father[x]);     return x;} int Kruskal (int n,int m) {    sort (edge,edge+m,cmp);    int x,y,res=0;    for (int i=0; i<m; i++)    {        x=edge[i].u;        Y=EDGE[I].V;        X=find (x);        Y=find (y);        if (x!=y)        {            res+=edge[i].w;            father[y]=x;        }    }    return res;}

Minimum spanning Tree 2 (Kruskal algorithm)

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.