Search code examples
algorithmdata-structuressetunion-find

How can we choose which element to be representative in a Union-find data structure?


When we merge two sets for example A={1,2,3} and B={6,7,8},let 1,8 be the representatives of both the sets respectively,now if we merge both the sets what will be the representative of the resultant set? can we choose based on our choice ? In my code below

#include<iostream>
#define MAX 10001
int rank[MAX];int parent[MAX];
void swap(int x,int y)
{
int temp=0;
temp=x;
x=y;
y=temp;
 }
void make_set (int v) {
parent[v] = v;
rank[v] = 0;
 }

 int find_set (int v) {
 if (v == parent[v])
    return v;
 return parent[v] = find_set (parent[v]);
 }

  void union_sets (int a, int b) {
 a = find_set (a);
 b = find_set (b);
 if (a != b) {
    if (rank[a] < rank[b])
        swap (a, b);
    parent[b] = a;
    if (rank[a] == rank[b])
        ++rank[a];
   }
      }
  int main()
  {
    for(int i=1;i<=3;i++)
  {
  make_set(i);
    }
   std::cout<<find_set(1)<<"\n";
   union_sets(1,2);
   union_sets(2,3);
   std::cout<<find_set(2)<<"\n"; 
 return 0;
  }

I am getting answer as 1? what if we want it to change to another representative?


Solution

  • Your implementation of DSU is good as you are using rank array to union two sets that is something to keep in mind that merging is done due to the rank of each set to make the merged sets balanced.
    but if two sets are being joined which have the same rank then joining will be according to the order of your union_sets function parameters.
    so to answer your question: if you want to change from 1 (which is only possible if target sets have the same rank) all what you have to do is to reverse you parameters when calling union_sets.