Advertisement
Josif_tepe

Untitled

Oct 24th, 2023
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. using namespace std;
  5. const int maxn = 1e5 + 10;
  6. const int INF = 1e9;
  7. vector<pair<int, int> > graph[maxn];
  8. int n, m;
  9. struct node {
  10.     int idx;
  11.     int cost;
  12.     node () {}
  13.     node(int _idx, int _cost) {
  14.         idx = _idx;
  15.         cost = _cost;
  16.     }
  17.     bool operator < (const node &tmp) const {
  18.         return cost > tmp.cost;
  19.     }
  20. };
  21.  
  22. int prim() {
  23.     priority_queue<node> pq;
  24.     pq.push(node(0, 0));
  25.     vector<int> dist(n, INF);
  26.     vector<bool> visited(n, false);
  27.     dist[0] = 0;
  28.     int mst = 0;
  29.     while(!pq.empty()) {
  30.         node c = pq.top();
  31.         pq.pop();
  32.        
  33.         if(visited[c.idx]) continue;
  34.         visited[c.idx] = true;
  35.        
  36.         mst += c.cost;
  37.         for(int i = 0; i < (int) graph[c.idx].size(); i++) {
  38.             int neighbour = graph[c.idx][i].first;
  39.             int weight = graph[c.idx][i].second;
  40.             if(!visited[neighbour] and weight < dist[neighbour]) {
  41.                 pq.push(node(neighbour, weight));
  42.                 dist[neighbour] = weight;
  43.             }
  44.         }
  45.     }
  46.     return mst;
  47. }
  48. int main() {
  49.     cin >> n >> m;
  50.     for(int i = 0; i < m; i++) {
  51.         int a, b, c;
  52.         cin >> a >> b >> c;
  53.         a--;
  54.         b--;
  55.         graph[a].push_back(make_pair(b, c));
  56.         graph[b].push_back(make_pair(a, c));
  57.     }
  58.     cout << prim() << endl;
  59.     return 0;
  60. }
  61.  
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement