-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPrimsAlgo.cpp
More file actions
59 lines (47 loc) · 1.14 KB
/
Copy pathPrimsAlgo.cpp
File metadata and controls
59 lines (47 loc) · 1.14 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
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
void Prims(int v, map<int,set<pair<int,int>>> adj){
int source=0;
vector<int> key(v,INT_MAX);
vector<bool> mst(v,false);
vector<int> parent(v,-1);
key[source]=0;
parent[source]=-1;
for(int i=0;i<v;i++){
int minnode=INT_MAX;
int parentnode;
for(int j=1;j<v;j++){
if(mst[j]==false && key[j]<minnode){
parentnode=j;
minnode=key[j];
}
}
mst[parentnode]=true;
for(auto it:adj[parentnode]){
int nextnode = it.first;
int nextweight =it.second;
if(mst[nextnode]==false && nextweight<key[nextnode]){
parent[nextnode]=parentnode;
key[nextnode]=nextweight;
}
}
}
int mincost=0;
for(auto i: key){
mincost+=i;
}
cout<<mincost<<endl;
}
int main(){
int n,m;
cin>>n>>m;
map<int, set<pair<int,int>>>adj;
for(int i=0;i<m;i++){
int u,v,wt;
cin>>u>>v>>wt;
adj[u].insert({v,wt});
}
Prims(n, adj);
return 0;
}