Preprocessing takes to compute sizes and depths, to decompose into chains, and to build the segment tree. Total preprocessing: . Each query walks chains and does work per chain via segment tree queries.
Total per query: . With queries, total time is . Space is for arrays and the segment tree. This handles easily within time limits.
Space complexity is for the data structures used.