Minimum spanning tree Kruskal algorithm for greedy algorithm (greedy algorithm) (kruskal& #39; s algorithm)

Source: Internet
Author: User

The Kruskal algorithm (Kruskal's algorithm) is one of the simpler understandings of the two classical minimum spanning tree algorithms. This fully embodies the essence of the greedy algorithm. The approximate process can be represented by a graph. The choice of the map here borrows from Wikipedia. Very clear and intuitive.

First step, we have a graph with several points and edges

For example, as seen in:

The first thing we want to do is to sort the lengths of all the edges, using the sort results as the basis for our selection of edges. This once again embodies the idea of the greedy algorithm. The resources are sorted and the local optimal resources are selected.

After sorting, we are leading the selection of side AD. And then our diagram becomes

Step two, look for the rest of the changes. We found the CE. The weight of the side is also 5.

We found the 6,7,7 in turn. After that, the picture becomes this way.

The next step is the key. Which side is the following selection? BC or EF? None, although today's 8-length edge is the smallest of the selected edges. But now they are connected (for BC to be able to connect via Ce,eb, a similar ef can go through EB, BA, AD, DF). So we don't need to choose them. Similar BD is already connected (here the connecting lines are in red). So the last thing left is eg and FG. Of course we have chosen eg. The final success chart is:

All the edges here have been connected, and a minimal spanning tree has been built.

Suppose to briefly describe this algorithm, the first side of the weight sort. The inference of the cycle (from small to large) is whether you need to select the edges here. The inference is based on whether the two vertices of the edge are connected, assuming that the general rule continues to the next one. If you are not connected, choose to make it connected. The process is still very clear.

But in the realization of the time, the difficult place is how to describe the narrative 2 points are already connected? Here to use and check the set to do auxiliary, as for and check set can come here to see.

The code for the kruscal and the C + + implementations are posted here:

/*** Disjoint_set_forest.h--an implementation for disjoint Set data structure** Created by Ge Chunyuan on 04/09/2009.* * version:0.1*/#pragma once#ifndef _disjoint_set_h_#define _disjoint_set_h_#include <vector>template < TypeName T> class Disjointset{public:disjointset (); ~disjointset (); void MakeSet (const std::vector<t>& s) ; Boolfindset (const t& S, t& parent); Voidunion (const t& s1, const t& s2);p rotected:struct Node{intrank; Tdata; Node*parent; };int m_nelementcnt; int m_nsetcnt; Std::vector<node*> M_nodes; };template< class t> Disjointset<t>::D Isjointset () {m_nelementcnt = 0;m_nsetcnt = 0;} template< class t> Disjointset<t>::~disjointset () {for (int i=0;i<m_nelementcnt;i++) Delete m_Nodes[i];} template< class t> void Disjointset<t>::makeset (const std::vector<t>& s) {m_nelementcnt + = (int) s . Size (); m_nsetcnt + = (int) s.size (); Std::vector<t>::const_iterator it = S.begin (); for (; it! = s). end (); + + it) {node* Pnode = new Node;pnode->data = *it;pnode->parent = Null;pnode->rank = 0;m_nodes.push_back (PNode);}} template< class t> bool Disjointset<t>::findset (const t& S, t& parent) {node* Curnode = Null;bool Find =false;for (int i=0;i< (int) m_nodes.size (); i++) {Curnode = m_nodes[i];if (Curnode->data = = s) {find = True;break;}} if (!find) return false;//find the root node* proot = Curnode;while (proot->parent! = NULL) {proot = proot->parent;} Update all Curnode ' s parent to rootwhile (curnode! = proot) {node* Pnext = Curnode->parent;curnode->parent = PRoot ; curnode = Pnext;} parent = Proot->data;return true;} template< class t> Voiddisjointset<t>::union (const t& s1, const t& s2) {node* pNode1 = NULL; node* PNode2 = Null;int find = 0;for (int i=0;i< (int) m_nodes.size (); ++i) {if (M_nodes[i]->data = = S1 | | m_nodes[i]-&g T;data = = s2) {Find ++;if (M_nodes[i]->data = = S1) pNode1 = M_nodes[i];elsepnode2 = M_nodes[i];}} Not found if (find! = 2) return; if (Pnode1->rank > Pnode2->rank) pnode2->parent = Pnode1;else if (pnode1-& Gt;rank < Pnode2->rank) Pnode1->parent = Pnode2;else{pnode2->parent = pnode1;++ PNode1->rank;} --m_nsetcnt;} #endif//_disjoint_set_h_

 

Kruscal_Algorithm.cpp:Defines the entry point for the console application.//#include "stdafx.h" #include <string&gt ; #include <vector> #include <algorithm> #include <iostream> #include "disjoint_set_forest.h" struct Vertex {Vertex () {}vertex (std::string n) {name = n;} BOOL operator== (const vertex& RHS) {return name = = Rhs.name;} BOOL Operator!= (const vertex& RHS) {return name! = Rhs.name;} std::string name;}; struct Edge {edge () {}edge (Vertex v1, Vertex v2, int w) {this->v1 = V1;this->v2 = V2;this->w = w;} Vertex v1; Vertex v2;int W;}; struct Edgesort{bool operator () (const edge& E1, const edge& E2) {return e1.w<e2.w;}}; struct printedge{void operator () (Edge e) {std::cout<< "Edge start from" <<e.v1.name << "to" <<e.v 2.name << "with length =" &LT;&LT;E.W <<std::endl;;}}; Class Graph{public:void Appendvertex (const vertex& v1) {m_vertexs.push_back (v1);} void Appendedge (const vertex& v1, const VERTEX&AMP V2, int w) {M_edges.push_back (Edge (V1,v2,w));} void Minimumspanningkruskal () {std::vector<edge> Result;std::sort (M_edges.begin (), M_edges.end (), EdgeSort ()) ;D isjointset<vertex> Dv;dv.makeset (m_vertexs); Std::vector<edge>::iterator it = M_edges.begin (); for (; it ! = M_edges.end (); ++it) {Vertex P1; Vertex P2;bool B1 = Dv.findset (It->v1, p1); bool B2 = Dv.findset (It->v2, p2); if (b1&& B2 && (p1! = P2)) {dv. Union (P1, p2); Result.push_back (*it);}} For_each (Result.begin (), Result.end (), Printedge ()); Protected:std::vector<vertex> m_vertexs;std::vector<edge> m_edges;}; int _tmain (int argc, _tchar* argv[]) {Graph gr; Vertex A ("a"); Vertex B ("B"); Vertex C ("C"); Vertex d ("D"); Vertex E ("E"); Vertex F ("F"); Vertex g ("G"); Gr.appendvertex (a); Gr.appendvertex (b); Gr.appendvertex (c); Gr.appendvertex (d); Gr.appendvertex (e); Gr.appendvertex (f); Gr.appendvertex (g); Gr.appendedge (a,b,7); Gr.appendedge (a,d,5); Gr.appendedge (b,c,8); Gr.appendedge (b,d,9); Gr.appendedge (b,e,7);Gr.appendedge (c,e,5); Gr.appendedge (d,e,15); Gr.appendedge (d,f,6); Gr.appendedge (e,f,8); Gr.appendedge (e,g,9); Gr.appendedge (f,g,11); Gr.minimumspanningkruskal (); System ("pause"); return 0;}

Greedy algorithm (greedy algorithm) minimum spanning tree Kruskal algorithm (kruskal& #39; s 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.