-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathprims_algorithm.cpp
More file actions
82 lines (67 loc) · 1.67 KB
/
prims_algorithm.cpp
File metadata and controls
82 lines (67 loc) · 1.67 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
82
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
#include <climits>
using namespace std;
void primMST(int V, vector<vector<pair<int, int>>> &adj)
{
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
vector<int> key(V, INT_MAX);
vector<int> parent(V, -1);
vector<bool> inMST(V, false);
int start_node = 0;
pq.push({0, start_node});
key[start_node] = 0;
while (!pq.empty())
{
int u = pq.top().second;
pq.pop();
if (inMST[u])
{
continue;
}
inMST[u] = true;
for (auto &edge : adj[u])
{
int v = edge.first;
int weight = edge.second;
if (!inMST[v] && key[v] > weight)
{
key[v] = weight;
pq.push({key[v], v});
parent[v] = u;
}
}
}
int total_weight = 0;
cout << "Edges in the Minimum Spanning Tree:" << endl;
for (int i = 1; i < V; ++i)
{
if (parent[i] != -1)
{
cout << parent[i] << " -- " << i << " == " << key[i] << endl;
total_weight += key[i];
}
}
cout << "Total weight of MST: " << total_weight << endl;
}
void addEdge(vector<vector<pair<int, int>>> &adj, int u, int v, int w)
{
adj[u].push_back({v, w});
adj[v].push_back({u, w});
}
int main()
{
int V = 5;
vector<vector<pair<int, int>>> adj(V);
addEdge(adj, 0, 1, 2);
addEdge(adj, 0, 3, 6);
addEdge(adj, 1, 2, 3);
addEdge(adj, 1, 3, 8);
addEdge(adj, 1, 4, 5);
addEdge(adj, 2, 4, 7);
addEdge(adj, 3, 4, 9);
primMST(V, adj);
return 0;
}