0

S represents the set of integers from 1 to n. Consider the union-find data structure where - besides the operations union(A, B) and find(x) - you are interested in returning the minimum element of the set to which x belongs.

Suggest a data structure that allows you to efficiently implement these operations and analyze the running time for a sequence of m find, p findMin and at most (n - 1) unions.

I know that I should somehow sort the elements of the set to which x belongs (so, I first find the set, then I sort it and that should take O(nlogn) plus the time used by the find operation, which depends on the data structure...). Should I use the Union-find with balanced unions and path compression? Sorry, but I'm very confused!

pippi2424
  • 21
  • 5

1 Answers1

0

Well all you need to do is store minimum element in the root of disjoin set.

To implement that you just need to modify Union() so that after merging 2 sets, it will also update the minimum element for the disjoint set.

So all operations are still O(log n) (if using path compression or union by rank)

or even O(inverse_ackerman) (if using both optimizations)

Pseudocode (Using path compression only, so all operations are O(log n)):

const int N = 10;

int P[N+1]; //stores parent of each set, initially all elements set to -1 to indicate no parent
int Min[N+1];//stores min element of each set

int Find(int u)
{
    return P[u] < 0 ? u : P[u] = Find(P[u]);
}

void Union(int u, int v)
{
    u = Find(u);
    v = Find(v);
    if(u == v)return;
    Min[u] = Min[u] < Min[v] ? Min[u] : Min[v]; 
    P[v] = u; 
}

int FindMin(int u)
{
    return Min[Find(u)];
}
Photon
  • 2,717
  • 1
  • 18
  • 22