My solution on UVa Online Judge based on Competitive Programming Book