Skip to content

Commit d54ddad

Browse files
Merge pull request #264 from harshendram/Algo/PrimsAlgorithm
Algo/prims algorithm
2 parents de17023 + 8d486c2 commit d54ddad

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <queue>
4+
#include <utility>
5+
#include <climits>
6+
7+
using namespace std;
8+
9+
void primMST(int V, vector<vector<pair<int, int>>> &adj)
10+
{
11+
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
12+
13+
vector<int> key(V, INT_MAX);
14+
vector<int> parent(V, -1);
15+
vector<bool> inMST(V, false);
16+
17+
int start_node = 0;
18+
pq.push({0, start_node});
19+
key[start_node] = 0;
20+
21+
while (!pq.empty())
22+
{
23+
int u = pq.top().second;
24+
pq.pop();
25+
26+
if (inMST[u])
27+
{
28+
continue;
29+
}
30+
31+
inMST[u] = true;
32+
33+
for (auto &edge : adj[u])
34+
{
35+
int v = edge.first;
36+
int weight = edge.second;
37+
38+
if (!inMST[v] && key[v] > weight)
39+
{
40+
key[v] = weight;
41+
pq.push({key[v], v});
42+
parent[v] = u;
43+
}
44+
}
45+
}
46+
47+
int total_weight = 0;
48+
cout << "Edges in the Minimum Spanning Tree:" << endl;
49+
for (int i = 1; i < V; ++i)
50+
{
51+
if (parent[i] != -1)
52+
{
53+
cout << parent[i] << " -- " << i << " == " << key[i] << endl;
54+
total_weight += key[i];
55+
}
56+
}
57+
cout << "Total weight of MST: " << total_weight << endl;
58+
}
59+
60+
void addEdge(vector<vector<pair<int, int>>> &adj, int u, int v, int w)
61+
{
62+
adj[u].push_back({v, w});
63+
adj[v].push_back({u, w});
64+
}
65+
66+
int main()
67+
{
68+
int V = 5;
69+
vector<vector<pair<int, int>>> adj(V);
70+
71+
addEdge(adj, 0, 1, 2);
72+
addEdge(adj, 0, 3, 6);
73+
addEdge(adj, 1, 2, 3);
74+
addEdge(adj, 1, 3, 8);
75+
addEdge(adj, 1, 4, 5);
76+
addEdge(adj, 2, 4, 7);
77+
addEdge(adj, 3, 4, 9);
78+
79+
primMST(V, adj);
80+
81+
return 0;
82+
}

0 commit comments

Comments
 (0)