Official

F - Second Largest Query Editorial by en_translator


For simplicity, we denote the subsequence \(A_x, A_{x+1}, \ldots, A_{y-1}\) by segment \([x,y)\).

For \(l < m < r\), the second largest value in the segment \([l,r)\) is one of the following: the largest value among the segment \([l, m)\), the second largest value among the segment \([m, r)\), or the second largest value among the segment \([m, r)\).

Likewise, the maximum value among the segment \([l,r)\) is either the maximum value among the segment \([l,m)\), or that among the segment \([m,r)\).

Therefore, if we know (the largest value, the number of its occurrence, the second largest value, the number of its occurrence) for segments \([l,m)\) and \([m,r)\), they can also be found for the segment \([l,r)\), which enables us to solve the problem in a total of \(O(N + Q\log N)\) time using a segment tree.

posted:
last update: