sanket407's blog

By sanket407, history, 7 years ago, In English

I am sure most of you must be familiar with union find data structure and the recursive findParent() in it. I usually use array par[] for it. But today i couldnt use array due to large range of values. So i used HashMaps instead. So foll. code was malfunctioning :

return par.get(x) < 0 ? x : (par.put(x, root(par.get(x)))); it was returning x even if par.get(x) > 0.

So i converted it to :

if(par.get(x) < 0)
    {  
             return x;
             }
    else
    {
       int p  = root(par.get(x));
       par.put(x, p);
       return p;
    }

And it worked fine . So what why did the first code fail ?? any inputs ??

  • Vote: I like it
  • -5
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it +1 Vote: I do not like it

If there are only a limited number of large values, try compressing them instead of using weird map tricks.

»
7 years ago, # |
  Vote: I like it +1 Vote: I do not like it

Note that Map.put(key, newValue) returns the old value associated with the key, not the new value.