Advertisement
VladNitu

C++ Prim PQ O((M+N) * logN)

Dec 12th, 2022
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define NMAX 200002
  3. using namespace std;
  4.  
  5. ifstream f ("apm.in");
  6. ofstream g ("apm.out");
  7.  
  8. int N, M, x, y, cost;
  9. long long ans = 0;
  10.  
  11. vector<pair<int, int>> v[NMAX];
  12. int d[NMAX];
  13. priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>> > pq;
  14. unordered_set<int> visited;
  15. unordered_map<int, int> edges; // maps vertex to edge w/ min cost
  16.  
  17. int main() {
  18.  
  19. f >> N >> M;
  20. for (int i = 0; i < M; ++i) {
  21. f >> x >> y >> cost;
  22. v[x].push_back({cost, y});
  23. v[y].push_back({cost, x});
  24. }
  25.  
  26. for (int i = 1; i <= N; ++i)
  27. d[i] = INT_MAX;
  28. d[1] = 0;
  29.  
  30. pq.push({0, 1});
  31.  
  32.  
  33. while (!pq.empty()) {
  34. int node = pq.top().second;
  35. pq.pop();
  36. visited.insert(node);
  37.  
  38.  
  39. for (pair<int, int> neigh_pr: v[node]){
  40. int neigh = neigh_pr.second;
  41. int new_cost = neigh_pr.first;
  42. if (visited.find(neigh) == visited.end() && new_cost < d[neigh])
  43. {
  44. d[neigh] = new_cost;
  45. pq.push({new_cost, neigh});
  46. edges[neigh] = node;
  47. }
  48. }
  49. }
  50.  
  51. for (int i = 1; i <= N; ++i)
  52. ans += d[i];
  53.  
  54. g << ans << '\n';
  55. g << N - 1 << '\n';
  56. for (const auto& edge: edges)
  57. g << edge.first << ' ' << edge.second << '\n';
  58.  
  59. return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement