Problem D from round 186 - Codeforces