Please provide solution for this problem asked in COW conducted by MNIT(JAIPUR).
Link to Solution: https://codeforces.com/blog/entry/51068 ,In the link 771D is the solution .