Sorting Railway Cars

CodeForces - 606C