Advertisement
Araf_12

Prims's algorithm

Feb 9th, 2023 (edited)
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N = 1e5 + 5;
  4.  
  5. int n, m;
  6. vector<pair<int, int>> adj[N];
  7. bool vis[N];
  8. int dis[N];
  9.  
  10. void prim(int s) {
  11.     memset(dis, 0x3f, sizeof dis);
  12.     memset(vis, false, sizeof vis);
  13.     priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
  14.     q.push({0, s});
  15.     dis[s] = 0;
  16.  
  17.     while (!q.empty()) {
  18.         int u = q.top().second;
  19.         q.pop();
  20.         if (vis[u]) continue;
  21.         vis[u] = true;
  22.         for (auto& e : adj[u]) {
  23.             int v = e.first, w = e.second;
  24.             if (dis[v] > w) {
  25.                 dis[v] = w;
  26.                 q.push({w, v});
  27.             }
  28.         }
  29.     }
  30. }
  31.  
  32. int main() {
  33.     cin >> n >> m;
  34.     for (int i = 0; i < m; i++) {
  35.         int a, b, w;
  36.         cin >> a >> b >> w;
  37.         adj[a].push_back({b, w});
  38.         adj[b].push_back({a, w});
  39.     }
  40.     prim(1);
  41.     int ans = 0;
  42.     for (int i = 2; i <= n; i++) ans += dis[i];
  43.     cout << ans << endl;
  44.     return 0;
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement