Advertisement
Sourav_CSE

Prims Cpp

Nov 26th, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. //prims
  2. // Mohsin Riad
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5. #define pii pair<int ,long long>
  6. vector< pii >v[100007];
  7. bool vis[100007];
  8. long long solve(int x)
  9. {
  10. int y;
  11. long long min_cost=0;
  12. priority_queue<pii>p;
  13. p.push({x,0});
  14. while(!p.empty())
  15. {
  16. pii p1=p.top();
  17. p.pop();
  18. x=p1.first;
  19. if(vis[x]) continue;
  20. min_cost-=p1.second;
  21. vis[x]=true;
  22. for(int i=0;i<v[x].size();i++)
  23. {
  24. if(!vis[v[x][i].first])
  25. {
  26. p.push({v[x][i].first,-1*v[x][i].second});
  27. }
  28. }
  29. }
  30. return min_cost;
  31. }
  32. int main()
  33. {
  34. int x,y,nodes,edges;
  35. long long cost;
  36. cin>>nodes>>edges;
  37. for(int i=0;i<edges;i++)
  38. {
  39. cin>>x>>y>>cost;
  40. v[x].push_back({y,cost});
  41. v[y].push_back({x,cost});
  42. }
  43. cout<<solve(1)<<endl;
  44. return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement