Minimum Spanning Tree Tutorials & Notes - Algorithms - HackerEarth
Minimum Spanning Tree Tutorials & Notes - Algorithms - HackerEarth
Signup and get free access to 100+ Tutorials and Practice Problems Start Now
Algorithms
Given an undirected and connected graph , a spanning tree of the graph is a tree that
spans (that is, it includes every vertex of ) and is a subgraph of (every edge in the tree belongs
to )
The cost of the spanning tree is the sum of the weights of all the edges in the tree. There can be
many spanning trees. Minimum spanning tree is the spanning tree where the cost is minimum among
all the spanning trees. There also can be many minimum spanning trees.
Minimum spanning tree has direct application in the design of networks. It is used in algorithms
approximating the travelling salesman problem, multi-terminal minimum cut problem and minimum-
cost weighted perfect matching. Other practical applications are: ?
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 1/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
1. Cluster Analysis
2. Handwriting recognition
3. Image segmentation
There are two famous algorithms for finding the Minimum Spanning Tree:
Kruskal’s Algorithm
Kruskal’s Algorithm builds the spanning tree by adding edges one by one into a growing spanning
tree. Kruskal's algorithm follows greedy approach as in each iteration it finds an edge which has least
weight and add it to the growing spanning tree.
Algorithm Steps:
This could be done using DFS which starts from the first vertex, then check if the second vertex is
visited or not. But DFS will make time complexity large as it has an order of where is
the number of vertices, is the number of edges. So the best solution is "Disjoint Sets":
Disjoint sets are sets whose intersection is the empty set so it means that they don't have any
element in common.
?
Consider following example:
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 2/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
In Kruskal’s algorithm, at each iteration we will select the edge with the lowest weight. So, we will start
with the lowest weighted edge first i.e., the edges with weight 1. After that we will select the second
lowest weighted edge i.e., edge with weight 2. Notice these two edges are totally disjoint. Now, the
?
next edge will be the third lowest weighted edge i.e., edge with weight 3, which connects the two
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 3/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
disjoint pieces of the graph. Now, we are not allowed to pick the edge with weight 4, that will create a
cycle and we can’t have any cycles. So we will select the fifth lowest weighted edge i.e., edge with
weight 5. Now the other two edges will create cycles so we will ignore them. In the end, we end up
with a minimum spanning tree with total cost 11 ( = 1 + 2 + 3 + 5).
Implementation:
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
void initialize()
{
for(int i = 0;i < MAX;++i)
id[i] = i;
}
int root(int x)
{
while(id[x] != x)
{
id[x] = id[id[x]];
x = id[x];
}
return x;
}
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 4/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
int main()
{
int x, y;
long long weight, cost, minimumCost;
initialize();
cin >> nodes >> edges;
for(int i = 0;i < edges;++i)
{
cin >> x >> y >> weight;
p[i] = make_pair(weight, make_pair(x, y));
}
// Sort the edges in the ascending order
sort(p, p + edges);
minimumCost = kruskal(p);
cout << minimumCost << endl;
return 0;
}
Time Complexity:
In Kruskal’s algorithm, most time consuming operation is sorting because the total complexity of the
Disjoint-Set operations will be , which is the overall Time Complexity of the algorithm.
Prim’s Algorithm
Prim’s Algorithm also use Greedy approach to find the minimum spanning tree. In Prim’s Algorithm ?
we grow the spanning tree from a starting position. Unlike an edge in Kruskal's, we add vertex to the
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 5/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
Algorithm Steps:
Maintain two disjoint sets of vertices. One containing vertices that are in the growing spanning
tree and other that are not in the growing spanning tree.
Select the cheapest vertex that is connected to the growing spanning tree and is not in the
growing spanning tree and add it into the growing spanning tree. This can be done using
Priority Queues. Insert the vertices, that are connected to growing spanning tree, into the
Priority Queue.
Check for cycles. To do that, mark the nodes which have been already selected and insert only
those nodes in the Priority Queue that are not marked.
In Prim’s Algorithm, we will start with an arbitrary node (it doesn’t matter which one) and mark it. In
each iteration we will mark a new vertex that is adjacent to the one that we have already marked. As
a greedy algorithm, Prim’s algorithm will select the cheapest edge and mark the vertex. So we will
simply choose the edge with weight 1. In the next iteration we have three options, edges with weight?
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 6/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
2, 3 and 4. So, we will select the edge with weight 2 and mark the vertex. Now again we have three
options, edges with weight 3, 4 and 5. But we can’t choose edge with weight 3 as it is creating a cycle.
So we will select the edge with weight 4 and we end up with the minimum spanning tree of total cost
7 ( = 1 + 2 +4).
Implementation:
#include <iostream>
#include <vector>
#include <queue>
#include <functional>
#include <utility>
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 7/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
return minimumCost;
}
int main()
{
int nodes, edges, x, y;
long long weight, minimumCost;
cin >> nodes >> edges;
for(int i = 0;i < edges;++i)
{
cin >> x >> y >> weight;
adj[x].push_back(make_pair(weight, y));
adj[y].push_back(make_pair(weight, x));
}
// Selecting 1 as the starting node
minimumCost = prim(1);
cout << minimumCost << endl;
return 0;
}
Time Complexity:
The time complexity of the Prim’s Algorithm is because each vertex is inserted in
the priority queue only once and insertion in priority queue take logarithmic time.
Given a weighted undirected graph. Find the sum of weights of edges of a Minimum Spanning Tree.
Input:
Given 2 integers N and M. N represents the number of vertices in the graph. M represents the
number of edges between any 2 vertices.
Then M lines follow, each line has 3 space separated integers , , where and represents
?
an edge from a vertex to a vertex and respresents the weight of that edge.
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 8/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
Output:
Print the summation of edges weights in the MST.
Constraints:
SAMPLE INPUT
4 5
1 2 7
1 4 6
4 2 9
4 3 8
2 3 6
SAMPLE OUTPUT
19
Enter your code or Upload your code as file. Save C (gcc 5.4.0)
1 /*
2 // Sample code to perform I/O:
3 #include <stdio.h>
4
5 int main(){
6 int num;
7 scanf("%d", &num); // Reading input from
STDIN
8 printf("Input number is %d.\n", num); // Writing output to
STDOUT
9 }
10
11 // Warning: Printing unwanted or ill-formatted data to output will
cause the test cases to fail
12 */
13
14 // Write your code here
15
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 9/10
9/10/21, 5:36 PM Minimum Spanning Tree Tutorials & Notes | Algorithms | HackerEarth
1:1 vscode
https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/ 10/10