Kruskal (Kruskal) minimum spanning tree algorithm detailed + template

Source: Internet
Author: User
Tags min printf
minimum Spanning Tree

Selecting the n-1 edge in a connected graph with n vertices, constituting a minimal connected sub-graph, and minimizing the sum of the weights of the n-1 bars in the connected sub-graph, it is called the smallest spanning tree of the connected net.

For example, for a connected network as shown in Figure G4 above, you can have multiple spanning trees with different weights.


Kruskal Algorithm Introduction
Kruskal (Kruskal) algorithm is used to calculate the minimum spanning tree of weighted connected graphs.

basic idea: according to the weight of the order from small to large selection n-1 edge, and ensure that this n-1 edge does not constitute a loop.
How to do this : first construct a forest containing only n vertices, then choose the edge from the connected network from small to large in the weight to join the forest, and make no loop in the forest until the forest becomes a tree.
Kruskal algorithm diagram
The above figure G4, for example, to demonstrate the Kruskal (assuming that the most niche tree result is saved with the array R).

1th Step:The Edge(e,f)JoinRIn
Side(e,f)Has the lowest weight, so it is added to the minimum spanning tree result R.
2nd Step:The Edge(c,d)JoinRIn
After the previous operation, the Edge(c,d)is minimized, so it is added to the minimum spanning tree resultRIn
3rd Step:The Edge(d,e)JoinRIn
After the previous operation, the Edge(d,e)is minimized, so it is added to the minimum spanning tree resultRIn
Fourth Step:The Edge(b,f)JoinRIn
After the previous operation, the Edge(c,e)The weights are minimal, but(c,e)And the existing edges to form a loop; therefore, skip edges(c,e)。 In the same vein, skip the edge.(c,f)。 The Edge(b,f)Add to minimum spanning tree resultsRIn
5th step:The Edge(e,g)JoinRIn
After the previous operation, the Edge(e,g)is minimized, so it is added to the minimum spanning tree resultRIn
6th step:The Edge(A, b)JoinRIn
After the previous operation, the Edge(f,g)The weights are minimal, but(f,g)And the existing edges to form a loop; therefore, skip edges(f,g)。 In the same vein, skip the edge.(b,c)。 The Edge(A, b)Add to minimum spanning tree resultsRIn

At this point, the minimum spanning tree construct is complete. The edges that it includes are:(e,f) (c,d) (d,e) (b,f) (e,g)(A, B).
Kruskal Algorithm Analysis
Based on the basic ideas and practices of the Kruskal algorithm described earlier, we are able to understand that the Kruskal algorithm focuses on the following two issues that need to be addressed:
The problem is sorted by weight size for all edges of the graph.
question two how to determine if a loop is formed when adding edges to the minimum spanning tree.

Problem a good solution, using sorting algorithm to sort.

Problem two is handled by recording the end point of the vertex in the minimum spanning tree, and the end point of the vertex is the largest vertex connected to it in the smallest spanning tree (which is explained later in the picture). Then each time you need to add an edge to the minimum survival tree, determine whether the end of the two vertices of the edge is coincident, coincident words will constitute a loop. The following diagram illustrates:

When you add (e,f) (c,d) (d,e) to the minimum spanning tree R, the vertices of these edges all have an end point:

* * The end point of C is f.
(c) The end of D is F.
The end point of E is F.
The end of F is f. **

The end point is that all vertices are arranged in order from small to large, and the end point of a vertex is "the largest vertex connected to it". So, Next, although (C,e) is the least weighted edge. But the emphasis of C and E is F, that is, they have the same end point, so if you add (c,e) to the minimum spanning tree, it will form a loop. This is how the loop is judged.
Code description for the Kruskal algorithm

With the previous algorithm analysis, let's look at the specific code below. Here the "adjacency matrix" to illustrate, the "adjacency table" Implementation of the diagram in the following source code will give the corresponding source code.

1. Basic definition

adjacency matrix
typedef struct _GRAPH
{
    char vexs[max];       Vertex set
    int vexnum;           Vertex number
    int edgnum;           Number of sides
    int Matrix[max][max];//adjacency Matrix
}graph, *pgraph;

The structure of the side of the
typedef struct _EDGEDATA
{
    char start;//The Beginning of the Edge
    char end;   The end of the edge
    int weight;//edge weight
}edata;

Graph is the corresponding structure of the adjacency matrix.
Vexs is used to save vertices, Vexnum is the number of vertices, edgnum is the number of edges, and the matrix is a two-dimensional array to hold the matrix information. For example, matrix[i][j]=1 means "vertex I (i.e. vexs[i])" and "Vertex J (i.e. Vexs[j])" are adjacency points; matrix[i][j]=0, they are not adjacency points.
Edata are the structures that correspond to the edges of adjacent matrices.
Transfer from http://www.cnblogs.com/skywang12345/
2. Kruskal algorithm
Template 1

/* * Kruskal (Kruskal) minimum spanning tree */void Kruskal (Graph G) {int i,m,n,p1,p2;
    int length;          int index = 0;     Index of the rets array int vends[max]={0};
    Used to save the end point of each vertex in the existing minimum spanning tree in the smallest tree.        EData Rets[max];           The result array, preserving the edge EData *edges of the Kruskal minimum spanning tree;
    All sides of the graph corresponding//get "all sides in the graph" edges = get_edges (G);

    The edge is sorted by the size of "weight" (from small to large) sorted_edges (edges, g.edgnum);   for (i=0; i<g.edgnum; i++) {p1 = Get_position (G, Edges[i].start);     Gets the ordinal number of the "start" of the edge of the P2 = get_position (G, edges[i].end);                 Gets the ordinal number M = Get_end (Vends, p1) of the "end point" of the section I edge;                 Gets the end point of P1 in the "Existing minimum spanning tree" n = get_end (vends, p2);  Gets the end point of the P2 in the "Existing minimum spanning tree"//if m!=n, means "Edge i" and "vertices that have been added to the minimum spanning tree" do not form a loop if (m! = N) {vends[m]                       = N;           Set m at the end of "existing minimum spanning tree" to n rets[index++] = edges[i];

    Save Results}} free (edges);
    Statistics and printing of "Kruskal minimum spanning tree" information length = 0; For (i = 0; i < index; i++) length + = Rets[i].weight;
    printf ("kruskal=%d:", length);
    for (i = 0; i < index; i++) printf ("(%c,%c)", Rets[i].start, Rets[i].end);
printf ("\ n"); }

Template 2

#include <stdio.h> #include <string.h> #define INF 0x3f3f3f3f int map[110][110],dis[110],visit[110];
/* About three arrays: The map array is stored as point edge information, such as map[1][2]=3, indicating that the distance between point 1th and point 2nd is 3 dis array is the shortest distance from the starting point to each point, such as dis[3]=5, which indicates the shortest distance from the starting point to the 3rd point is 5
The visit array is 0 or the same as the one that has passed this point.
*/int n,m;
    int Dijstra () {int i,j,pos=1,min,sum=0;
    memset (visit,0,sizeof (visit));//initialized to., indicating that the start did not pass for (I=1; i<=n; ++i) {dis[i]=map[1][i];
    } visit[1]=1;
    dis[1]=0;
        for (I=1; i<n; i++) {min=inf; for (j=1; j<=n; ++j) {if (Visit[j]==0&&min>dis[j]) {min=dis[
                J];
            Pos=j; }} visit[pos]=1;//indicates that this point has traversed for (j=1; j<=n; ++j) {if (visit[j]==0&&
        DIS[J]&GT;DIS[POS]+MAP[POS][J])//update dis value dis[j]=dis[pos]+map[pos][j];
}} return dis[n];
    } int main () {int i,j; while (~SCANF ("%d%d", &n,&m), n| |
   m)//n represents n points, m represents M-edge {     For (I=1, i<=n; ++i) {for (j=1; j<=n; ++j) {map[i][j]=inf;//start
        Assigns each edge to the maximum value}} int a,b,c;
            for (I=1; i<=m; ++i) {scanf ("%d%d%d", &a,&b,&c);
        if (C<map[a][b])//Prevent having heavy edge map[a][b]=map[b][a]=c;
        } int Count=dijstra ();
    printf ("%d\n", count);
} return 0; }

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.