Introduction to algorithms-minimum spanning tree (Kruskal and prim algorithms) __kruskal

Source: Internet
Author: User

Reprint Please specify the source: Do not build a platform in the floating sand http://blog.csdn.net/luoshixian099/article/details/51908175

A few concept definitions of graphs: connected graphs : in undirected graphs, if any two vertex vi v_i and VJ v_j have paths, then the undirected graph is called the connected graph. strongly connected graph : In the direction graph, if any two vertex vi v_i and the VJ V_j all have the path to connect, then said that the direction graph is the strong connected graph. Connected Network : In the connected graph, if the edge of the graph has a certain meaning, each edge is corresponding to a number, called the right, the right represents the connection to a vertex of the cost, called this connected graph is called connected network. Spanning Tree : a spanning tree of connected graphs refers to a connected subgraph, which contains all n vertices in the graph, but only enough to form a n-1 edge of a tree. A spanning tree with n vertices has only a n-1 edge, and if another edge is added to the spanning tree, it must be a loop. minimum Spanning tree : in all spanning trees of a connected network, the cost of all edges and the smallest spanning tree, called the minimum spanning tree.

Here are two 1.Kruskal algorithms for minimum spanning tree algorithm

This algorithm can be called "Edge method", the initial minimum spanning tree edge number is 0, each iteration selects a minimum cost edge that satisfies the condition, and joins the Edge collection of the smallest spanning tree.
1. All the edges of the graph are sorted by cost from small to large;
2. View the n vertices in the graph as a forest of independent n trees;
3. By weight from small to large selection edge, the selected edge of the two vertex connected to the Ui,vi u_i,v_i, should belong to two different trees, then become a minimum spanning tree side, and the two trees merged as a tree.
4. Repeat (3) until all vertices are in a tree or have n-1 edges.

2.Prim Algorithm

This algorithm can be called "dot method", each iteration to select the lowest cost of the corresponding points, add to the minimum spanning tree. The algorithm starts from a vertex s and grows to cover all vertices of the connected network. The set of all vertices of the graph is v V; the initial order set U={s},v=v−u u=\{s\},v=v-u; In two sets U,v U, V can be composed of edges, select a cost-minimal edge (u0,v0) (U_0,V_0), add to the minimum spanning tree, and incorporate V0 v_0 into the set U. Repeat the above steps until the minimum spanning tree has n-1 or n vertices.

The minimum cost edge must be updated synchronously because it is continually added to the set U, and a secondary array closedge is needed to maintain the minimum cost edge information for each vertex and set u in Set V:

struct
{
  char vertexdata   //representing vertex information in U
  UINT lowestcost   //Minimum cost
}closedge[vexcounts]

3. Complete code

/************************************************************************ CSDN not to build a platform in the floating sand http://blog.csdn.net/ Introduction to luoshixian099 algorithm--minimum spanning tree (Prim, Kruskal) July 14, 2016 ************************************************************** /#include <iostream> #include <vector> #include <queue> #include <algorithm> using
namespace Std; #define INFINITE 0xFFFFFFFF #define VERTEXDATA unsigned int//vertex data #define UINT unsigned int #define VEXCOUNTS 6//Top
Dot quantity char vextex[] = {' A ', ' B ', ' C ', ' D ', ' E ', ' F '};
    struct Node {vertexdata data;
unsigned int lowestcost; }closedge[vexcounts];
    Prim algorithm in the auxiliary information typedef struct {vertexdata u;
    Vertexdata v;  unsigned int cost;  Side of the cost}arc; Edge information of the original graph void Adjmatrix (unsigned int adjmat[][vexcounts])//adjacency matrix notation {for (int i = 0; i < vexcounts; i++)//initialization
        Adjacency matrix for (int j = 0; J < vexcounts J + +) {Adjmat[i][j] = INFINITE; } adjmat[0][1] = 6; ADJMAT[0][2] = 1; adjmat[0][3] = 5; Adjmat[1][0] = 6; ADJMAT[1][2] = 5;
    ADJMAT[1][4] = 3; Adjmat[2][0] = 1; ADJMAT[2][1] = 5; ADJMAT[2][3] = 5; ADJMAT[2][4] = 6;
    ADJMAT[2][5] = 4; Adjmat[3][0] = 5; ADJMAT[3][2] = 5;
    ADJMAT[3][5] = 2; ADJMAT[4][1] = 3; ADJMAT[4][2] = 6;
    ADJMAT[4][5] = 6; ADJMAT[5][2] = 4; ADJMAT[5][3] = 2;
ADJMAT[5][4] = 6;
    int Minmum (struct node * closedge)//return minimum cost edge {unsigned int min = INFINITE;
    int index =-1; for (int i = 0; i < vexcounts;i++) {if (Closedge[i].lowestcost < min && Closedge[i].lowestcost
            !=0) {min = Closedge[i].lowestcost;
        index = i;
} return index; 
        } void Minispantree_prim (unsigned int adjmat[][vexcounts], vertexdata s) {for (int i = 0; i < vexcounts;i++) {
    Closedge[i].lowestcost = INFINITE;      } Closedge[s].data = S;
    Starting from vertex s closedge[s].lowestcost = 0; for (int i = 0; i < vexcounts;i++)//Initialize auxiliary array {if(I!= s)
            {Closedge[i].data = s;
        Closedge[i].lowestcost = Adjmat[s][i];  {int k = Minmum (Closedge) is exited for (int e = 1; e <= vexCounts-1 e++)//n-1 sidebar;
        Select Minimum cost edge cout << Vextex[closedge[k].data] <<--"<< Vextex[k] << endl;//Add to minimum spanning tree Closedge[k].lowestcost = 0; The cost is set to 0 for (int i = 0; i < vexcounts;i++)//update V-vertex minimum cost edge information {if (Adjmat[k][i] < closed
                Ge[i].lowestcost) {closedge[i].data = k;
            Closedge[i].lowestcost = Adjmat[k][i];  "}} void Readarc (unsigned int adjmat[][vexcounts],vector<arc> &vertexarc)//Save the Edge cost information for the diagram {ARC
    * temp = NULL;
            for (unsigned int i = 0, I < vexcounts;i++) {for (unsigned int j = 0; J < i. J +) {
                if (adjmat[i][j]!=infinite) {temp = new Arc; Temp->u = i;
                Temp->v = j;
                Temp->cost = Adjmat[i][j];
            Vertexarc.push_back (*temp); BOOL Compare (Arc A, arc B) {return a.cost < b.cost? True:false} bool Findtree (Vertexdat
    A u, vertexdata v,vector<vector<vertexdata> > &tree) {unsigned int index_u = INFINITE;
    unsigned int index_v = INFINITE;  for (unsigned int i = 0; i < tree.size (); i++)/check u,v belong to which tree {if (Find Tree[i].begin (), Tree[i].end (), u)
        != tree[i].end ()) Index_u = i;
    if (Tree[i].begin (), Tree[i].end (), V)!= tree[i].end ()) Index_v = i; 
        if (Index_u!= index_v)//u,v is not on a tree, merge two trees {for (unsigned int i = 0; i < tree[index_v].size (); i++)
        {Tree[index_u].push_back (tree[index_v][i]);
        } tree[index_v].clear ();
    return true;
return false; } void Minispantree_kruskal (unsigned int Adjmat[][vexcoUnts]) {vector<arc> vertexarc; Readarc (Adjmat, VERTEXARC)//read edge information sort (Vertexarc.begin (), vertexarc.end (), compare);//edge by small to large sort VECTOR&LT;VECTOR&L T vertexdata> > Tree (vexcounts);  6 Independent Trees for (unsigned int i = 0; i < vexcounts; i++) {tree[i].push_back (i); Initialize information for 6 Independent Trees} for (unsigned int i = 0; i < vertexarc.size (); i++)//In turn from small to large to take the minimum price edge {vertexdata U =  
        vertexarc[i].u;
        Vertexdata v = vertexarc[i].v; if (Findtree (U, V, tree))//Check whether the two vertices of this edge are in one of the trees {cout << vextex[u] << "---" << vextex[v
    << endl;//Add this edge to the minimum spanning tree}} int main () {unsigned int adjmat[vexcounts][vexcounts] = {0};   Adjmatrix (Adjmat);
    Adjacency matrix cout << "Prim:" << Endl; Minispantree_prim (adjmat,0);
    Prim algorithm, starting from vertex 0.
    cout << "-------------" << Endl << "Kruskal:" << Endl; Minispantree_kruskal (Adjmat);//kruskal algorithm return 0;
} 

Reference:
Data structure – multi-structure element morphology
Introduction to Algorithms-third edition

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.