Implement algorithm for codejame 2014 qual B.