In C++ Minimum Spanning Tree DescriptioI theMinimam Spanning Tree problem, we ar
ID: 3721719 • 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
Excutable code:
#include <stdio.h>
#include <limits.h>
#include<iostream>
using namespace std;
#define V 4
int minKey(int key[], bool mstSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
int printMST(int parent[], int n, int graph[V][V])
{
cout<<"Edge Weight ";
for (int i = 1; i < V; i++)
{
printf("%d - %d %d ", parent[i], i, graph[i][parent[i]]);
cout<<parent[i]<<" ";
}
}
void primMST(int graph[V][V])
{
int parent[V];
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V-1; count++)
{
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, V, graph);
}
int main()
{
int graph[V][V]={0};
int n,m,k,c;
int i,j;
cout <<"enterno of vertices";
cin >> n;
cout <<"ente no of edges";
cin >> m;
cout <<" EDGES Cost ";
for(k=1;k<=m;k++)
{
cin >>i>>j>>c;
graph[i][j]=c;
graph[j][i]=c;
}
primMST(graph);
return 0;
}