Advertisement
urmisaha

Prim's Implementation

Oct 22nd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define maxm 3001
  3. #define pii pair<int, int>
  4. #define vii vector<pii>
  5. #define pb push_back
  6. #define mp make_pair
  7.  
  8. using namespace std;
  9.  
  10. int n, m, x, y, r, start, cost;
  11. vector<int> vis(maxm);
  12. vector<pii> g[maxm];
  13.  
  14. // Complete the prims function below.
  15. void prims() {
  16.     priority_queue<pii, vii, greater<pii> > pq;
  17.     pq.push(mp(0, start));
  18.     while(!pq.empty()){
  19.         int x = pq.top().second;
  20.         int c = pq.top().first;
  21.         pq.pop();
  22.         if(vis[x])
  23.             continue;
  24.         vis[x] = 1;
  25.         cost += c;
  26.         for(int i=0; i<g[x].size(); ++i)
  27.             if(!vis[g[x][i].second])
  28.                 pq.push(g[x][i]);
  29.     }
  30.     cout<<cost;
  31. }
  32.  
  33. int main()
  34. {
  35.     ios_base::sync_with_stdio(false);
  36.     cin>>n>>m;
  37.     for(int i=0; i<m; ++i){
  38.         cin>>x>>y>>r;
  39.         g[x].pb(mp(r, y));
  40.         g[y].pb(mp(r, x));
  41.     }
  42.     cin>>start;
  43.     prims();
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement