I'm trying to solve the problem: http://acm.timus.ru/problem.aspx?space=1&num=1439 I tryed to code a dynamic segment tree to solve in O(m*logn²) of time, as follows: https://ideone.com/e.js/bk8fVq. However, it gave MLE. So, I want to know what I can do to improve the memory used. Thanks in advance