3

Can someone check with me if I'm using the rule right in the last step (7)?

UPDATE:

Numbers inside the parentheses are the number of elements (weight(?)) of each set that takes part in the Union. Uppercase letters are names of sets.

As I understand this: we are using as our rank the number of elements? This is getting confusing, each one is using different terms for the same stuff.

We have Unions:

  1. U(1,2,A)
  2. U(3,4,B)
  3. U(A,B,C)
  4. U(5,6,D)
  5. U(7,8,E)
  6. U(D,C,F)
  7. U(E,F,G)

enter image description here

user2692669
  • 461
  • 8
  • 23

2 Answers2

1

Step 7 (and the others) looks correct, but step 6 doesn't.

In step 6, 4 should be the root, as that's the bigger tree.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
  • 1+2+3+4=10 and 5+6=11 , shouldn't 6 be the root in step 6? (cause of the weight) – user2692669 Feb 15 '14 at 19:25
  • 1
    I've never seen a union-find algorithm that uses the nodes' values as the weight - this won't make a whole lot of sense either, as the nodes' values don't really correspond to the running time of operations. It usually uses the height / depth of the tree. – Bernhard Barker Feb 15 '14 at 19:38
  • I updated my problem as you instructed, I think it's correct now(?). – user2692669 Feb 15 '14 at 19:47
  • Sorry, there is a catch in the problem I did an edit. These things are very tricky! – user2692669 Feb 15 '14 at 22:26
0
void combine(int x,int y)
{
    int xroot=find(x),yroot=find(y);
    if(rank[xroot]<rank[yroot]) 
        parent[xroot]=yroot;
    else if(rank[xroot]>rank[yroot]) 
    parent[yroot]=xroot;
    else 
    {///rank of both is equal..
        parent[yroot]=xroot;
        rank[xroot]++;
    }
}

Using rank, you see the size of set, not sum of vertices, so step 6 is wrong.

But why the size?
Because if we make root of bigger set the root of smaller set , we need to update parents of smaller number of nodes.

For the best explanation, I would recommend CLRS (Introduction to Algorithms).

Hope it helps you!

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Aseem Goyal
  • 2,683
  • 3
  • 31
  • 48