0

I'm using union-find algorithm to find all the connected components of an un-directed graph. For some unknown reasons it gives a wrong answer. The input graph that I give is connected and yet it outputs 2 different labels for that graph.

I would be glad if someone can explain this anomaly. Are there some special undirected graphs where Union-Find may not work?

** The graph is a little big, so I added a picture for better readability of the graph. couldn't trim the graph or the essence of the question will vanish. **

Here, p and rk are parent and rank respectively.

Code

Union function

 void union_find(int x, int y, int *p, int *rk)
{
    int px = find(x, p);
    int py = find(y, p);
    if(px != py)
    {
        if(rk[px] < rk[py])
        {
            p[px] = py;
        }
        else
        {
            p[py] = px;
            if(rk[px] == rk[py]) rk[px]++;
        }
    }
}

Find function

int find(int x , int *p)
{
    return (p[x] == x) ? x : p[x] = find(p[x], p);
}

Sample Input

37 51
4 5
4 10
5 7
5 8
5 9
6 7
6 16
7 8
7 15
8 9
8 10
10 11
10 14
11 12
12 21
13 14
13 32
14 15
14 22
15 16
15 22
16 17
17 22
17 19
19 24
19 27
20 30
20 32
21 31
22 23
22 36
23 24
23 36
24 25
25 26
26 36
26 27
27 28
27 29
27 32
27 37
28 29
29 30
31 32
32 33
32 35
33 34
33 35
34 35
35 36
36 37

Photo of the graph

Please note that, I'm not considering the nodes 1,2,3 and 18 and their edges.

Undirected Graph

user3811219
  • 93
  • 1
  • 8
  • Why do you think it's wrong? It's giving correct output [here](http://ideone.com/iNJQwV). – Anmol Singh Jaggi Apr 14 '16 at 20:03
  • @AnmolSinghJaggi: It's wrong because I know this entire graph is connected. You can look at the picture with my question. In the output, we have two labels (4,20) instead of one. – user3811219 Apr 14 '16 at 20:22
  • What makes you think it's two labels? It clearly shows that the parent of `4` is `20`. – Anmol Singh Jaggi Apr 14 '16 at 20:28
  • yeah you are right but shouldn't the array make everything 20? Because the parent of 4 is 20 , then all the elements whose parent is 4 should be set to 20. Thanks for your comment though. – user3811219 Apr 14 '16 at 20:39
  • That's not necessary. That only means that `find()` wasn't called on them after `p[4]` became `20`. That's why they still *think* that their parent is `4` rather than `20`. – Anmol Singh Jaggi Apr 14 '16 at 20:45
  • To get the state I wanted. I had to perform the find(i) for i = 1 to V. It didn't reduce it for some reason. I wonder why. – user3811219 Apr 14 '16 at 20:49
  • Thanks for the insight @AnmolSinghJaggi – user3811219 Apr 14 '16 at 20:49
  • No problem. Just remember that to find the number of distinct connected components, just count the number of instances where `p[i] == i`. – Anmol Singh Jaggi Apr 14 '16 at 21:01

0 Answers0