A union-find type of problem