-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprims_algorithm_mst.cpp
92 lines (72 loc) · 2.1 KB
/
prims_algorithm_mst.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
82
83
84
85
86
87
88
89
90
91
92
class Compare
{
public:
bool operator() (vector<int> edge1, vector<int> edge2)
{
return (edge1[2] > edge2[2]);
}
};
class Solution {
private:
void visit(priority_queue<
vector<int>,
vector<vector<int>>,
Compare
>& pq,
vector<vector<vector<int>>>& graph,
vector<bool>& visited, int vertex){
visited[vertex] = true;
for(auto edge: graph[vertex]){
int u = edge[0];
int v = edge[1];
int w = edge[2];
if(u != vertex and !visited[u]){
pq.push(edge);
}
else if(v != vertex and !visited[v]){
pq.push(edge);
}
}
}
public:
int minimumCost(int n, vector<vector<int>>& connections) {
vector<bool> visited(n+1, false);
vector<vector<vector<int>>> graph(n+1);
for(auto edge: connections){
int u = edge[0];
int v = edge[1];
int w = edge[2];
graph[u].push_back(edge);
graph[v].push_back(edge);
}
priority_queue<
vector<int>,
vector<vector<int>>,
Compare
> pq;
bool possible = true;
int cost = 0;
int mst_edge_count = 0;
visit(pq, graph, visited, 1);
while(!pq.empty() and (mst_edge_count<(n-1))){
auto edge = pq.top();
pq.pop();
if(visited[edge[0]] and visited[edge[1]]){
continue;
}
if(!visited[edge[0]]){
visit(pq, graph, visited, edge[0]);
}
if(!visited[edge[1]]){
visit(pq, graph, visited, edge[1]);
}
cost += edge[2];
mst_edge_count++;
}
int retval = -1;
if(mst_edge_count == n-1){
retval = cost;
}
return retval;
}
};