Advertisement
111-111-111

DSU

May 23rd, 2020
519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. //DSU
  2. struct dsu
  3. {
  4.     vector<int> parent;
  5.     vector<int> sz;
  6.    
  7.     dsu(int n)
  8.     {
  9.         parent=vector<int>(n);
  10.         for(int i=0;i<n;i++)parent[i]=i;
  11.         sz=vector<int>(n,1);
  12.     }
  13.    
  14.     int find_(int x)
  15.     {
  16.         int root=x;
  17.         while(root!=parent[root])
  18.             root=parent[root];
  19.        
  20.         //Path compression
  21.         while(parent[x]!=root)
  22.         {
  23.             int p=parent[x];
  24.             parent[x]=root;
  25.             x=p;
  26.         }
  27.         return root;
  28.     }
  29.     bool union_(int x,int y)
  30.     {
  31.         int X=find_(x);
  32.         int Y=find_(y);
  33.         // x and y are already in the same set
  34.         if(X==Y)
  35.             return false;
  36.         // x and y are not in same set, so we merge them
  37.         if(sz[X]<sz[Y])
  38.             swap(X, Y);
  39.         // merge yRoot into xRoot
  40.         parent[Y]=X;
  41.         sz[X]+=sz[Y];
  42.         return true;
  43.     }
  44. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement