-
Notifications
You must be signed in to change notification settings - Fork 0
/
Prims.cpp
50 lines (49 loc) · 978 Bytes
/
Prims.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
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
const int n =1e5;
vector<pii> adj[n];
#define ss second
#define ff first
int cost;
int prims(int src)
{
bool vis[n+1]={0};
priority_queue<pii,vector<pii>,greater<pii> > pq;
pq.push({0,src});
int counter = 0;
while( !pq.empty() )
{
pii p = pq.top();
pq.pop();
int u = p.ss;
int ct=p.ff;
if(!vis[u])
{
vis[u] = 1 ;
cost = cost+ct;
for(auto v : adj[u])
{
cout <<u <<" "<< v.second<< endl;
if( ! vis[v.ss])
{
pq.push(v);
}
}
}
}
return cost;
}
int main()
{
int v ,e ;
cin >> v >>e ;
for(int i =0 ; i<e ;i++)
{
int a, b , c;
cin >> a >> b >> c;
adj[a].push_back( {c,b} ) ;
adj[b].push_back({c,a }) ;
}
cout << prims(1);
}