How can i solve http://www.spoj.com/problems/LEGO/ problem on spoj using DSU?

I kinda have this feeling that by sorting the boxes in some way and then applynig DSU can do the task bu t I can’t think of a way to actually solve it.
@pkacprzak if u can help?