QOJ964
Step 1
The problem is equivalent to asking for the largest \(x\) such that the number of \(a[l \dots r] < x\) is at least \(x\).
Step 2
Obviously this is doable with Mo's algorithm. Time complexity \(O(n \sqrt{n} \log n)\).
Step 3
But there is a better approach.
Rather than solving the problem in the \(i\) direction, we instead solve it in the \(x\) direction. We can iterate over \(x\) from large to small. If we check each range naively, it will be \(\mathcal{O}(n^2)\).
But we realize that after reducing \(x\) by \(1\), only certain positions will be changed, and it won't be changed back. This allows us to use amortized complexity. Furthermore, we find that if one interval contains another, the contained interval has an answer at most as large the containing interval.
After reducing \(x\), we can first binary search all the positions that became invalid and invalidate them. Then we also binary search out the first interval that needs to change. After deleting it, we also need to add in the ranges that it contains.
Note that the segment tree is build on the queries. When we find a position that is invalid, it's containing intervals for a continuous range. This is because the query intervals' \(l\) and \(r\) are both monotonic (after removing contained intervals).
This is \(\mathcal{O}(n \log n)\) amortized.
Step 4
We can build a persistent segment tree in the value range (we can cut off at n, > n values won't effect the answer), and we do a sort of prefix modification. This allows us to query the number of elements < t in any range. and because the problem is monotonic, we can binary search the answer. \(\mathcal{O}(n \log^2 n)\).