Optimizing with union-find