BotByte

Prim.cpp

Feb 22nd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. /* Minimum Spanning Tree - Prim */
  2. /* Author : M. A. Rafsan Mazumder */
  3.  
  4. #include <bits/stdc++.h>
  5.  
  6. using namespace std;
  7.  
  8. typedef pair<long long, int> PII;
  9. #define MAX 1000
  10. vector<PII> adj[MAX];
  11. bool marked[MAX];
  12.  
  13. long long prim(int x)
  14. {
  15. priority_queue<PII, vector<PII>, greater<PII> > pq;
  16.  
  17. PII p;
  18. pq.push(make_pair(0, x));
  19. long long minCost = 0;
  20.  
  21. while(!pq.empty()){
  22. p = pq.top();
  23. pq.pop();
  24.  
  25. int x = p.second;
  26. int cost = p.first;
  27. if(marked[x]) continue;
  28. minCost += cost;
  29.  
  30. marked[x] = true;
  31. for(int i=0; i<adj[x].size(); i++){
  32. int y = adj[x][i].second;
  33. if(!marked[y]) pq.push(adj[x][i]);
  34. }
  35. }
  36. return minCost;
  37. }
  38.  
  39. int main()
  40. {
  41. int nodes, edges;
  42. scanf("%d %d", &nodes, &edges);
  43. memset(marked, false, sizeof marked);
  44. for(int i=1; i<=edges; i++){
  45. int x, y, weight;
  46. scanf("%d %d %d", &x, &y, &weight);
  47. adj[x].push_back(make_pair(weight, y));
  48. adj[y].push_back(make_pair(weight, x));
  49. }
  50. printf("%d", prim(1));
  51. }
Advertisement
Add Comment
Please, Sign In to add comment