-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimscpp.cpp
More file actions
81 lines (63 loc) · 2.54 KB
/
Primscpp.cpp
File metadata and controls
81 lines (63 loc) · 2.54 KB
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
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
// Function to perform Prim's algorithm
pair<vector<pair<int, int>>, int> primMST(vector<vector<pair<int, int>>>& graph, int start) {
int numVertices = graph.size();
vector<bool> visited(numVertices, false);
vector<pair<int, int>> minimumSpanningTree;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> minHeap;
// Start with the given vertex
minHeap.push(make_pair(0, start));
int totalWeight = 0;
while (!minHeap.empty()) {
// Extract the edge with the minimum weight
pair<int, int> currentEdge = minHeap.top();
minHeap.pop();
int currentVertex = currentEdge.second;
int currentWeight = currentEdge.first;
// If the vertex is already visited, skip it
if (visited[currentVertex]) {
continue;
}
// Mark the current vertex as visited
visited[currentVertex] = true;
// Add the current edge to the minimum spanning tree
minimumSpanningTree.push_back(make_pair(currentVertex, currentWeight));
totalWeight += currentWeight;
// Add adjacent edges to the priority queuexa
for (pair<int, int>& neighbor : graph[currentVertex]) {
int neighborVertex = neighbor.first;
int neighborWeight = neighbor.second;
if (!visited[neighborVertex]) {
minHeap.push(make_pair(neighborWeight, neighborVertex));
}
}
}
return make_pair(minimumSpanningTree, totalWeight);
}
int main() {
int numVertices, numEdges;
cout << "Enter the number of vertices and edges: ";
cin >> numVertices >> numEdges;
vector<vector<pair<int, int>>> graph(numVertices);
cout << "Enter the edges in the format (from to weight):" << endl;
for (int i = 0; i < numEdges; ++i) {
int from, to, weight;
cin >> from >> to >> weight;
graph[from].push_back(make_pair(to, weight));
graph[to].push_back(make_pair(from, weight)); // Since the graph is undirected
}
int startVertex;
cout << "Enter the starting vertex: ";
cin >> startVertex;
pair<vector<pair<int, int>>, int> result = primMST(graph, startVertex);
cout << "Minimum Spanning Tree edges:" << endl;
for (const pair<int, int>& edge : result.first) {
cout << edge.first << " -- " << edge.second << " --> " << edge.first << endl;
}
cout << "Total Weight of Minimum Spanning Tree: " << result.second << endl;
return 0;
}