{"id":27533,"date":"2018-02-06T20:56:45","date_gmt":"2018-02-06T15:26:45","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27533"},"modified":"2018-02-06T20:56:45","modified_gmt":"2018-02-06T15:26:45","slug":"kruskals-minimum-spanning-tree-using-stl-c","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/kruskals-minimum-spanning-tree-using-stl-c\/","title":{"rendered":"Kruskal\u2019s Minimum Spanning Tree using STL in C++"},"content":{"rendered":"<p>Given an undirected, connected and weighted graph, find <strong>M<\/strong>inimum <strong>S<\/strong>panning <strong>T<\/strong>ree (MST) of the graph using Kruskal\u2019s algorithm.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-27542\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Kruskal\u2019s-Minimum-Spanning-Tree-using-STL-in-C.png\" alt=\"Kruskal\u2019s Minimum Spanning Tree using STL in C++\" width=\"714\" height=\"333\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Kruskal\u2019s-Minimum-Spanning-Tree-using-STL-in-C.png 714w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/06\/Kruskal\u2019s-Minimum-Spanning-Tree-using-STL-in-C-300x140.png 300w\" sizes=\"(max-width: 714px) 100vw, 714px\" \/><\/p>\n<pre>Input :   Graph as an array of edges\r\nOutput :  Edges of MST are \r\n          6 - 7\r\n          2 - 8\r\n          5 - 6\r\n          0 - 1\r\n          2 - 5\r\n          2 - 3\r\n          0 - 7\r\n          3 - 4\r\n          \r\n          Weight of MST is 37\r\n\r\n<strong>Note : <\/strong> There are two possible MSTs, the other\r\n        MST includes edge 1-2 in place of 0-7.<\/pre>\n<p>We have discussed below Kruskal\u2019s MST implementations.<\/p>\n<p>Greedy Algorithms | Set 2 (Kruskal\u2019s Minimum Spanning Tree Algorithm)<\/p>\n<p>Below are the steps for finding MST using Kruskal\u2019s algorithm<\/p>\n<ol>\n<li>Sort all the edges in non-decreasing order of their weight.<\/li>\n<li>Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it.<\/li>\n<li>Repeat step#2 until there are (V-1) edges in the spanning tree.<\/li>\n<\/ol>\n<p>Here are some key points which will be useful for us in implementing the Kruskal\u2019s algorithm using STL.<\/p>\n<ol>\n<li>Use a vector of edges which consist of all the edges in the graph and each item of a vector will contain 3 parameters: source, destination and the cost of an edge between the source and destination.\n<pre>vector&lt;pair&lt;int, pair&lt;int, int&gt; &gt; &gt; edges;<\/pre>\n<p>Here in the outer pair (i.e pair&lt;int,pair&lt;int,int&gt; &gt; ) the first element corresponds to the cost of a edge while the second element is itself a pair, and it contains two vertices of edge.<\/li>\n<li>Use the inbuilt std::sort to sort the edges in the non-decreasing order; by default the sort function sort in non-decreasing order.<\/li>\n<li>We use the Union Find Algorithm to check if it the current edge forms a cycle if it is added in the current MST. If yes discard it, else include it (union).<\/li>\n<\/ol>\n<p><strong>Pseudo Code:<\/strong><\/p>\n<pre>\/\/ Initialize result\r\nmst_weight = 0\r\n\r\n\/\/ Create V single item sets\r\n<strong>for<\/strong> <strong>each<\/strong> vertex v\r\n\tparent[v] = v;\r\n\trank[v] = 0;\r\n\r\n<strong>Sort<\/strong> all edges into non decreasing \r\norder by weight w\r\n\r\n<strong>for<\/strong> each (u, v) taken from the sorted list  E\r\n    <strong>do if<\/strong> <strong>FIND-SET<\/strong>(u) != <strong>FIND-SET<\/strong>(v)\r\n        <strong>print<\/strong> edge(u, v)\r\n        mst_weight += weight of edge(u, v)\r\n        <strong>UNION<\/strong>(u, v)<\/pre>\n<p>Below is C++ implementation of above algorithm.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program for Kruskal&#039;s algorithm to find Minimum<br\/>\/\/ Spanning Tree of a given connected, undirected and<br\/>\/\/ weighted graph<br\/>#include&lt;bits\/stdc++.h&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ Creating shortcut for an integer pair<br\/>typedef  pair&lt;int, int&gt; iPair;<br\/> <br\/>\/\/ Structure to represent a graph<br\/>struct Graph<br\/>{<br\/>    int V, E;<br\/>    vector&lt; pair&lt;int, iPair&gt; &gt; edges;<br\/> <br\/>    \/\/ Constructor<br\/>    Graph(int V, int E)<br\/>    {<br\/>        this-&gt;V = V;<br\/>        this-&gt;E = E;<br\/>    }<br\/> <br\/>    \/\/ Utility function to add an edge<br\/>    void addEdge(int u, int v, int w)<br\/>    {<br\/>        edges.push_back({w, {u, v}});<br\/>    }<br\/> <br\/>    \/\/ Function to find MST using Kruskal&#039;s<br\/>    \/\/ MST algorithm<br\/>    int kruskalMST();<br\/>};<br\/> <br\/>\/\/ To represent Disjoint Sets<br\/>struct DisjointSets<br\/>{<br\/>    int *parent, *rnk;<br\/>    int n;<br\/> <br\/>    \/\/ Constructor.<br\/>    DisjointSets(int n)<br\/>    {<br\/>        \/\/ Allocate memory<br\/>        this-&gt;n = n;<br\/>        parent = new int[n+1];<br\/>        rnk = new int[n+1];<br\/> <br\/>        \/\/ Initially, all vertices are in<br\/>        \/\/ different sets and have rank 0.<br\/>        for (int i = 0; i &lt;= n; i++)<br\/>        {<br\/>            rnk[i] = 0;<br\/> <br\/>            \/\/every element is parent of itself<br\/>            parent[i] = i;<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Find the parent of a node &#039;u&#039;<br\/>    \/\/ Path Compression<br\/>    int find(int u)<br\/>    {<br\/>        \/* Make the parent of the nodes in the path<br\/>           from u--&gt; parent[u] point to parent[u] *\/<br\/>        if (u != parent[u])<br\/>            parent[u] = find(parent[u]);<br\/>        return parent[u];<br\/>    }<br\/> <br\/>    \/\/ Union by rank<br\/>    void merge(int x, int y)<br\/>    {<br\/>        x = find(x), y = find(y);<br\/> <br\/>        \/* Make tree with smaller height<br\/>           a subtree of the other tree  *\/<br\/>        if (rnk[x] &gt; rnk[y])<br\/>            parent[y] = x;<br\/>        else \/\/ If rnk[x] &lt;= rnk[y]<br\/>            parent[x] = y;<br\/> <br\/>        if (rnk[x] == rnk[y])<br\/>            rnk[y]++;<br\/>    }<br\/>};<br\/> <br\/> \/* Functions returns weight of the MST*\/<br\/> <br\/>int Graph::kruskalMST()<br\/>{<br\/>    int mst_wt = 0; \/\/ Initialize result<br\/> <br\/>    \/\/ Sort edges in increasing order on basis of cost<br\/>    sort(edges.begin(), edges.end());<br\/> <br\/>    \/\/ Create disjoint sets<br\/>    DisjointSets ds(V);<br\/> <br\/>    \/\/ Iterate through all sorted edges<br\/>    vector&lt; pair&lt;int, iPair&gt; &gt;::iterator it;<br\/>    for (it=edges.begin(); it!=edges.end(); it++)<br\/>    {<br\/>        int u = it-&gt;second.first;<br\/>        int v = it-&gt;second.second;<br\/> <br\/>        int set_u = ds.find(u);<br\/>        int set_v = ds.find(v);<br\/> <br\/>        \/\/ Check if the selected edge is creating<br\/>        \/\/ a cycle or not (Cycle is created if u<br\/>        \/\/ and v belong to same set)<br\/>        if (set_u != set_v)<br\/>        {<br\/>            \/\/ Current edge will be in the MST<br\/>            \/\/ so print it<br\/>            cout &lt;&lt; u &lt;&lt; &quot; - &quot; &lt;&lt; v &lt;&lt; endl;<br\/> <br\/>            \/\/ Update MST weight<br\/>            mst_wt += it-&gt;first;<br\/> <br\/>            \/\/ Merge two sets<br\/>            ds.merge(set_u, set_v);<br\/>        }<br\/>    }<br\/> <br\/>    return mst_wt;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/* Let us create above shown weighted<br\/>       and unidrected graph *\/<br\/>    int V = 9, E = 14;<br\/>    Graph g(V, E);<br\/> <br\/>    \/\/  making above shown graph<br\/>    g.addEdge(0, 1, 4);<br\/>    g.addEdge(0, 7, 8);<br\/>    g.addEdge(1, 2, 8);<br\/>    g.addEdge(1, 7, 11);<br\/>    g.addEdge(2, 3, 7);<br\/>    g.addEdge(2, 8, 2);<br\/>    g.addEdge(2, 5, 4);<br\/>    g.addEdge(3, 4, 9);<br\/>    g.addEdge(3, 5, 14);<br\/>    g.addEdge(4, 5, 10);<br\/>    g.addEdge(5, 6, 2);<br\/>    g.addEdge(6, 7, 1);<br\/>    g.addEdge(6, 8, 6);<br\/>    g.addEdge(7, 8, 7);<br\/> <br\/>    cout &lt;&lt; &quot;Edges of MST are \\n&quot;;<br\/>    int mst_wt = g.kruskalMST();<br\/> <br\/>    cout &lt;&lt; &quot;\\nWeight of MST is &quot; &lt;&lt; mst_wt;<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre>Edges of MST are \r\n          6 - 7\r\n          2 - 8\r\n          5 - 6\r\n          0 - 1\r\n          2 - 5\r\n          2 - 3\r\n          0 - 7\r\n          3 - 4\r\n          \r\n          Weight of MST is 37<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Kruskal\u2019s Minimum Spanning Tree using STL in C++ &#8211; STL Implementation of Algorithms &#8211; Use a vector of edges which consist of all the edges in the graph.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[81350,81360],"tags":[81743,70802,71248,70796,70799,81745,70769,70783,70784,70774,81746,70794,70781,70772,70789,70785,70801,70771,81744],"class_list":["post-27533","post","type-post","status-publish","format-standard","hentry","category-graph","category-stl-implementation-of-algorithms","tag-c-program-to-implement-minimum-spanning-tree-using-kruskal-algorithm","tag-complexity-of-kruskal-algorithm","tag-difference-between-prims-and-kruskal-algorithm","tag-kruskal","tag-kruskal-algo","tag-kruskal-algorithm-c-adjacency-matrix","tag-kruskal-algorithm-example","tag-kruskal-algorithm-in-c","tag-kruskal-program-in-c","tag-kruskals-algorithm-c","tag-kruskals-algorithm-c-disjoint-set","tag-kruskals-algorithm-example","tag-kruskals-algorithm-in-c","tag-kruskals-algorithm-minimum-spanning-tree","tag-kruskals-algorithm-pdf","tag-prims-algorithm-in-c","tag-prims-and-kruskal-algorithm","tag-time-complexity-of-kruskal-algorithm","tag-write-a-program-for-minimum-spanning-trees-using-kruskals-algorithm"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27533","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27533"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27533\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}