Need help with ACM-ICPC Arab Regionals 2017 Problem A

I’m practicing for ACM ICPC and I came on this problem from 2017 ACM ICPC Arab Regionals:

I am already stuck on it for two days and I really don’t have idea how approach it. I couldn’t find editorial anywhere.
Can somebody please tell me how to solve it? Big thanks in advance.