-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path169. PrimsMST.cpp
82 lines (61 loc) · 1.91 KB
/
169. PrimsMST.cpp
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 <limits.h>
#include <queue>
vector<pair<pair<int, int>,int>> primsMST(vector<pair<int, int>> *adjList, int n)
{
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
int src = 0;
int *weight = new int[n];
int *parent = new int[n];
bool *inMST = new bool[n];
for (int i = 0; i < n; i++)
{
weight[i] = INT_MAX;
parent[i] = -1;
inMST[i] = false;
}
inMST[src] = true;
// 0 weight for current source.
pq.push(make_pair(0, src));
// Weight from source to source.
weight[src] = 0;
while (!pq.empty())
{
// The first vertex int pair is the minimum weight vertex ,extract it from priority queue and node name is stored at the second of pair( it has to be done this way to keep the vertices sorted order with respect weight) weight must be first item in pair.
int u = pq.top().second;
pq.pop();
// Include u to in our MST.
inMST[u] = true;
// Explore all adjacent of u and if not visited the relax them.
for (auto x : adjList[u])
{
int v = x.first;
int wt = x.second;
// If v is not in mst and weight of (u,v) is smaller then the current weight of v.
if (!inMST[v] && weight[v] > wt)
{
// Update weight of v.
weight[v] = wt;
// Insert it into the priority queue.
pq.push(make_pair(weight[v], v));
parent[v] = u;
}
}
}
delete[] adjList;
vector<pair<pair<int, int>, int>> result;
for (int i = 1; i < n; i++)
{
result.push_back({{min(parent[i]+1, i+1),max(parent[i]+1, i+1)}, weight[i]});
}
return result;
}
vector<pair<pair<int, int>, int>> calculatePrimsMST(int n, int m, vector<pair<pair<int, int>, int>> &g)
{
vector<pair<int, int>> *adjList = new vector<pair<int, int>>[n];
for (int i = 0; i < m; i++)
{
adjList[g[i].first.first-1].push_back(make_pair(g[i].first.second-1, g[i].second));
adjList[g[i].first.second-1].push_back(make_pair(g[i].first.first-1, g[i].second));
}
return primsMST(adjList, n);
}