Previous C++ submission (Much slower as I forgot to use fast IO):
https://www.codechef.com/viewsolution/29909032
C++ submission link: CodeChef: Practical coding for everyone
Python submission link: CodeChef: Practical coding for everyone
The above codes don’t use segment trees or any other data-structures (An O(N^2) solution).
If you have any questions, please feel free to ask in the comments
Official editorial: UWCOI20D - Base Plans - Editorial