COJ problem 1000 solution.