Solving a question from ACM-ICPC SCUSA 2013  http://ld2013.scusa.lsu.edu/problems-regional/prb.php?prob=4