I am not able to come up with a strategy to solve this problem.

https://www.codechef.com/problems/SEGDIR

The editorial is not given.

Given testcases do pass but gives error on submission. Since one hour, I have been trying but all in vain. Can someone give any strategy for this?

I know this is easy section problem but I am a beginner.

Thank you.