forked from souvikg544/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
primsAlgoMST.cpp
54 lines (36 loc) · 1009 Bytes
/
primsAlgoMST.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
#include<bits/stdc++.h>
using namespace std ;
signed main(){
int n , m ;
cin >> n >> m ;
vector<pair<int,int>> graph(n) ;
int a , b , wt ;
for(int i = 0 ; i < m ; i++){
cin >> a >> b >> wt ;
graph[a].push_back(make_pair(b,wt)) ;
graph[b].push_back(make_pair(a,wt)) ;
}
vector<int> key(n , INT_MAX) ;
vector<int> parent(n) ;
vector<bool> mstSet(n , false) ;
key[0] = 0 ;
parent[0] = -1 ;
priority_queue<pair<int,int> , vector<pair<int,int>> , greater<pair<int,int>>> pq ;
pq.push({0,0}) ;
while (!pq.empty())
{
/* code */
int u = pq.top().second ;
pq.pop() ;
mstSet[u] = true ;
for(auto it : graph[u]){
int v = it.first ;
int weight = it.second ;
if(mstSet[v] == false and weight < key[v]){
key[v] = weight ;
parent[v] = u ;
pq.push({key[v] , v}) ;
}
}
}
}