In C++ Minimum Spanning Tree DescriptioI theMinimam Spanning Tree problem, we ar
ID: 3720841 • Letter: I
Question
In C++
Minimum Spanning Tree DescriptioI theMinimam Spanning Tree problem, we are given as input an undirected graph G (V. E) together with weight u (Lu) on each edge (u,r) € E. The goal is to find a minium spanning tree for G. Recall that we learned two algorithms, Krusal's and Prim's in class. In this assignment, you are asked to implement Prim's algorithm. The following is a peeudo-code of Prim's algorithm. Initialize a min-ppriority que for all e V do Q Insert (Q.u). end for Decrease-key(Q.r,0) while Q * 0 do uExtract-Min(Q). for all e Ad[u] do if v Q and u, )Explanation / Answer
We have used kruskal's Minimum spanning tree algorithm to solve the problem. It uses disjoint set data structure.
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> iPair;
// Graph Structure
struct Graph
{
int V, E;
vector< pair<int, iPair> > edges;
// To initialize the graph
Graph(int V, int E)
{
this->V = V;
this->E = E;
}
// To add an edge
void addEdge(int u, int v, int w)
{
edges.push_back({w, {u, v}});
}
void kruskalMST();
};
struct DisjointSets
{
int *parent, *rnk;
int n;
DisjointSets(int n)
{
this->n = n;
parent = new int[n+1];
rnk = new int[n+1];
// Initially, all vertices are in
// different sets and have rank 0.
for (int i = 0; i <= n; i++)
{
rnk[i] = 0;
//every element is parent of itself
parent[i] = i;
}
}
// Path Compression
int find(int u)
{
/* Make the parent of the nodes in the path
from u--> parent[u] point to parent[u] */
if (u != parent[u])
parent[u] = find(parent[u]);
return parent[u];
}
// Applying Union by rank
void merge(int x, int y)
{
x = find(x), y = find(y);
if (rnk[x] > rnk[y])
parent[y] = x;
else // If rnk[x] <= rnk[y]
parent[x] = y;
if (rnk[x] == rnk[y])
rnk[y]++;
}
};
void Graph::kruskalMST()
{
int mst_wt = 0; // Initialize result
int *parent = new int[V-1];
// Sort edges in increasing order on basis of cost
sort(edges.begin(), edges.end());
// Create disjoint sets
DisjointSets ds(V);
// Iterate through all sorted edges
vector< pair<int, iPair> >::iterator it;
for (it=edges.begin(); it!=edges.end(); it++)
{
int u = it->second.first;
int v = it->second.second;
int set_u = ds.find(u);
int set_v = ds.find(v);
if (set_u != set_v)
{
parent[v-1] = u;
// Update MST weight
mst_wt += it->first;
// Merge two sets
ds.merge(set_u, set_v);
}
}
for(int i=0; i<V-1; i++) {
cout<<parent[i]<<endl;
}
}
// Main function
int main()
{
int V, E, a, b, w;
//Inputing number of vertex and edges
cin>>V>>E;
Graph g(V, E);
// Inputing the edges
for(int i=0; i<E; i++) {
cin>>a>>b>>w;
g.addEdge(a, b, w);
}
g.kruskalMST();
return 0;
}
Output: