Use union-find structure