Advertisement
nikunjsoni

947

Apr 27th, 2021
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. class Solution {
  2. int components=0;
  3. unordered_map<int, int> parent, rank;
  4. public:
  5.     int findParent(int x){
  6.         if(!parent.count(x)){
  7.             parent[x] = x;
  8.             rank[x] = 0;
  9.             components++;
  10.         }
  11.         return (parent[x] == x) ? x : (parent[x] = findParent(parent[x]));
  12.     }
  13.    
  14.     void unionSet(int x, int y){
  15.         int px = findParent(x);
  16.         int py = findParent(y);
  17.         if(px != py){
  18.             components--;
  19.             if(rank[x] > rank[y]){
  20.                 parent[py] = px;
  21.             }
  22.             else{
  23.                 parent[px] = py;
  24.                 rank[y]++;
  25.             }
  26.         }
  27.     }
  28.    
  29.     int removeStones(vector<vector<int>>& stones) {
  30.         for(vector<int> stone: stones)
  31.             unionSet(stone[0], ~stone[1]);
  32.         return stones.size()-components;
  33.     }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement