I spent really a lot of time during the today's contest trying to make my E solution faster, even though it should have O($$${n^2}logn$$$) complexity, which is with n <= 5000 should pass the 3 second limit. The only thing that helped me was changing long long to int, but even so, it's still very slow. Does anyone have any idea why my E solution is so slow (below is the final one)? And a similar question is about D as well, because I can't see any clear reasons why it is so slow:
Sorry about how code in E looks like, I don't know why it shifted, because for me it was totally normal when I was sending it.