More of an informatics question, rather than applied mathematics -
Source - Zonal Informatics Olympiad 2011 Question Paper
Although, I've tried a few brute methods, I haven't really understood the actual logic with which it was meant to be solved.