My solution to the problem: http://www.codechef.com/problems/ORDERS