This is a competition problem from Russia. Kindly share alternative strategies to the one I used if there are. I am also not sure if there are other solutions.