Solved UVa Problem 10360 using book approach