Advertisement
nikunjsoni

765

Apr 27th, 2021
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.61 KB | None | 0 0
  1. class Solution {
  2. int ans = 0;
  3. vector<int> p;
  4. public:
  5.     int find(int x){
  6.         return (x == p[x]) ? x : (p[x] = find(p[x]));
  7.     }
  8.    
  9.     void unionSet(int x, int y){
  10.         int px = find(x);
  11.         int py = find(y);
  12.         if(px != py){
  13.             p[py] = px;
  14.             ans++;
  15.         }
  16.     }
  17.    
  18.     int minSwapsCouples(vector<int>& row) {
  19.         p.resize(row.size());
  20.         for(int i=0; i<row.size(); i+=2){
  21.             p[row[i]] = row[i];
  22.             p[row[i+1]] = row[i];
  23.         }
  24.         for(int i=0; i<row.size(); i+=2)
  25.             unionSet(i,i+1);
  26.         return ans;
  27.     }
  28. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement