PROGRAM 9
Aim:
To implement Prim’s Algorithm to find the Minimum Cost Spanning Tree (MST) of a given
connected undirected graph using a priority queue (min-heap).
CODE:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
// Structure to represent an edge
struct Edge {
int dest, weight;
};
// Custom comparator for priority queue (min-heap)
struct Compare {
bool operator()(pair<int, int> a, pair<int, int> b) {
return a.second > b.second; // Min-heap based on weight
}
};
// Function to implement Prim's Algorithm
void primMST(vector<vector<Edge>>& graph, int V) {
vector<int> key(V, INT_MAX); // Store minimum edge weight to reach each vertex
vector<int> parent(V, -1); // Store MST edges
vector<bool> inMST(V, false); // Track visited nodes
priority_queue<pair<int, int>, vector<pair<int, int>>, Compare> pq;
// Start from vertex 0
key[0] = 0;
pq.push({0, 0}); // (vertex, weight)
while (!pq.empty()) {
int u = pq.top().first;
pq.pop();
inMST[u] = true; // Include vertex in MST
// Explore all adjacent edges
for (auto& edge : graph[u]) {
int v = edge.dest, weight = edge.weight;
if (!inMST[v] && weight < key[v]) { // If new edge has smaller weight
key[v] = weight;
pq.push({v, key[v]});
parent[v] = u;
}
// Print the MST
cout << "Minimum Cost Spanning Tree (Prim's Algorithm):\n";
int totalCost = 0;
for (int i = 1; i < V; i++) {
cout << parent[i] << " - " << i << " : " << key[i] << endl;
totalCost += key[i];
}
cout << "Total Cost: " << totalCost << endl;
// Main function
int main() {
int V, E;
cout << "Enter number of vertices and edges: ";
cin >> V >> E;
vector<vector<Edge>> graph(V);
cout << "Enter edges (src dest weight):\n";
for (int i = 0; i < E; i++) {
int src, dest, weight;
cin >> src >> dest >> weight;
graph[src].push_back({dest, weight});
graph[dest].push_back({src, weight}); // Undirected graph
primMST(graph, V);
return 0;