Need help in A2. Burenka and Traditions

I was trying to solve this question from codeforces, solved the easier one , but had trouble understanding the editorial for the harder version. Thanks in advance : )