MAGCARI

Prim

Jul 29th, 2022
1,072
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. /*
  2.     Task    : Prim
  3.     Author  : Phumipat C. [MAGCARI]
  4.     Language: C++
  5.     Created : 30 July 2022 [09:03]
  6. */
  7. #include<bits/stdc++.h>
  8. using namespace std;
  9. struct A{
  10.     int v,w;
  11.     bool operator < (const A&o) const{
  12.         return w>o.w;
  13.     }
  14. };
  15. priority_queue<A > heap;
  16. vector<A > g[100010];
  17. int mark[100010];
  18. int main(){
  19.     cin.tie(0)->sync_with_stdio(0);
  20.     cin.exceptions(cin.failbit);
  21.  
  22.     int n,m,u,v,w;
  23.     cin >> n >> m;
  24.    
  25.     for(int i=1;i<=m;i++){
  26.         cin >> u >> v >> w;
  27.         g[u].push_back({v,w});
  28.         g[v].push_back({u,w});
  29.     }
  30.  
  31.     mark[1] = 1;
  32.     for(auto x:g[1])
  33.         heap.push(x);
  34.  
  35.     int sum = 0;
  36.     while(!heap.empty()){
  37.         A now = heap.top();
  38.         heap.pop();
  39.         if(mark[now.v]) continue;
  40.         sum+=now.w;
  41.         mark[now.v] = 1;
  42.         for(auto x:g[now.v]){
  43.             if(mark[x.v])   continue;
  44.             heap.push(x);
  45.         }
  46.     }
  47.  
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment