Advertisement
nikunjsoni

1168

May 3rd, 2021
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. class UnionFind{
  2. public:
  3.     vector<int> parent, rank;
  4.     UnionFind(int n){
  5.         parent.resize(n+1);
  6.         rank.resize(n+1, 0);
  7.         for(int i=0; i<=n; i++)
  8.             parent[i] = i;
  9.     }
  10.    
  11.     int find(int x){
  12.         return (x == parent[x]) ? x : (parent[x] = find(parent[x]));
  13.     }
  14.    
  15.     bool unionSet(int x, int y){
  16.         int px = find(x);
  17.         int py = find(y);
  18.         if(px != py){
  19.             if(rank[px] > rank[py]){
  20.                 parent[py] = px;
  21.             }
  22.             else{
  23.                 parent[px] = py;
  24.                 rank[py]++;
  25.             }
  26.             return true;
  27.         }
  28.         return false;
  29.     }
  30. };
  31.  
  32. class Solution {
  33. public:
  34.     int minCostToSupplyWater(int n, vector<int>& wells, vector<vector<int>>& pipes) {
  35.         UnionFind uf = UnionFind(n);
  36.        
  37.         for(int i=1; i<=n; i++)
  38.             pipes.push_back({0, i, wells[i-1]});
  39.        
  40.         sort(pipes.begin(), pipes.end(), [](const vector<int> &a, const vector<int> &b){return a[2] < b[2];});
  41.        
  42.         int ans = 0;
  43.         for(auto pipe: pipes){
  44.             if(uf.unionSet(pipe[0], pipe[1])){
  45.                 ans += pipe[2];
  46.             }
  47.         }
  48.         return ans;
  49.     }
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement