Problem A of CodeForces Round #257.

Solved using a queue, and a custom Pair data structure