Updated UnionFind to weighted quick-find with optimizations