Maruf_Hasan

Prims Algo from HackerEarth

Sep 18th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <functional>
  5. #include <utility>
  6.  
  7. using namespace std;
  8. const int MAX = 1e4 + 5;
  9. typedef pair<long long, int> PII;
  10. bool marked[MAX];
  11. vector <PII> adj[MAX];
  12.  
  13. long long prim(int x)
  14. {
  15. priority_queue<PII, vector<PII>, greater<PII> > Q;
  16. int y;
  17. long long minimumCost = 0;
  18. PII p;
  19. Q.push(make_pair(0, x));
  20. while(!Q.empty())
  21. {
  22. // Select the edge with minimum weight
  23. p = Q.top();
  24. Q.pop();
  25. x = p.second;
  26. // Checking for cycle
  27. if(marked[x] == true)
  28. continue;
  29. minimumCost += p.first;
  30. marked[x] = true;
  31. for(int i = 0;i < adj[x].size();++i)
  32. {
  33. y = adj[x][i].second;
  34. if(marked[y] == false)
  35. Q.push(adj[x][i]);
  36. }
  37. }
  38. return minimumCost;
  39. }
  40.  
  41. int main()
  42. {
  43. int nodes, edges, x, y;
  44. long long weight, minimumCost;
  45. cin >> nodes >> edges;
  46. for(int i = 0;i < edges;++i)
  47. {
  48. cin >> x >> y >> weight;
  49. adj[x].push_back(make_pair(weight, y));
  50. adj[y].push_back(make_pair(weight, x));
  51. }
  52. // Selecting 1 as the starting node
  53. minimumCost = prim(1);
  54. cout << minimumCost << endl;
  55. return 0;
  56. }
Add Comment
Please, Sign In to add comment