task from http://www.ntnu.edu.tw/acm/ProblemSetArchive/A_FINALS/1991/prob_c.html