Naxocist

Battery (Kruskal + DSU)

Apr 14th, 2022
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using pi = pair<int, int>;
  5. using pii = pair<int, pi>;
  6.  
  7. const int N = 1e6;
  8. vector<pii> edgeList;
  9. int p[N];
  10.  
  11.  
  12. int root(int x){
  13.     if(p[x] == x) return x;
  14.     return p[x] = root(p[x]);
  15. }
  16.  
  17.  
  18. void un(int u, int v){
  19.     if(root(u) == root(v)) return ;
  20.  
  21.     int x = root(u), y = root(v);
  22.     p[x] = y;
  23. }
  24.  
  25. int main(){
  26.  
  27.     int n, m; scanf("%d %d", &n, &m);
  28.     int u, v, w;
  29.  
  30.     for(int i=0; i<=n; ++i) p[i] = i;
  31.  
  32.     for(int i=0; i<m; ++i){
  33.         scanf("%d %d %d", &u, &v, &w);
  34.         edgeList.push_back({w, {u, v}});
  35.     }
  36.  
  37.     sort(edgeList.begin(), edgeList.end());
  38.  
  39.     int cost = -1e9;
  40.     for(auto x : edgeList){
  41.         u = x.second.first, v = x.second.second, w = x.first;
  42.         if(root(u) != root(v)){
  43.             cost = max(cost, w);
  44.             un(u, v);
  45.         }
  46.     }
  47.  
  48.     printf("%d", cost);
  49.  
  50.     return 0;
  51. }
  52.  
  53. /*
  54. 5 6
  55. 0 1 30
  56. 1 2 10
  57. 1 3 50
  58. 3 2 30
  59. 2 5 20
  60. 5 2 10
  61. */
  62.  
Advertisement
Add Comment
Please, Sign In to add comment