1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include <iostream>
#include <vector>
#include <limits>
// Function to find the minimum key value from the set of vertices
// not yet included in MST
int findMinKey(const std::vector<int>& key, const std::vector<bool>& mstSet) {
int minKey = std::numeric_limits<int>::max();
int minIndex = -1;
for (int i = 0; i < key.size(); ++i) {
if (!mstSet[i] && key[i] < minKey) {
minKey = key[i];
minIndex = i;
}
}
return minIndex;
}
// Function to print the MST
void printMST(const std::vector<int>& parent, const std::vector<std::vector<int>>& graph) {
std::cout << "Edge \tWeight\n";
for (int i = 1; i < graph.size(); ++i) {
std::cout << parent[i] << " - " << i << "\t" << graph[i][parent[i]] << "\n";
}
}
// Function to implement Prim's algorithm using ADT
void primMST(const std::vector<std::vector<int>>& graph) {
int numVertices = graph.size();
std::vector<int> parent(numVertices); // Array to store constructed MST
std::vector<int> key(numVertices); // Key values used to pick minimum weight edge in cut
std::vector<bool> mstSet(numVertices); // To represent set of vertices included in MST
// Initialize all keys as infinite and mstSet[] as false
for (int i = 0; i < numVertices; ++i) {
key[i] = std::numeric_limits<int>::max();
mstSet[i] = false;
}
// Always include first vertex in MST
key[0] = 0; // Make key 0 so that this vertex is picked as first vertex
parent[0] = -1; // First node is always root of MST
// The MST will have V vertices
for (int count = 0; count < numVertices - 1; ++count) {
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = findMinKey(key, mstSet);
// Add the picked vertex to the MST set
mstSet[u] = true;
// Update key value and parent index of the adjacent vertices of the picked vertex
for (int v = 0; v < numVertices; ++v) {
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Print the constructed MST
printMST(parent, graph);
}
int main() {
// Example usage
std::vector<std::vector<int>> graph = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}
|