https://codeforces.com/contest/1360/problem/H

Can you please explain to me the logic behind to solve this problem