Official

B - Range Argmax Editorial by evima


Multiple \(p\)s corresponds to an \(x\), so it looks hard to count them at first sight. Let us handle it by making exactly one \(p\) correspond to an \(x\).

For a given \(x\), we will construct the corresponding \(p\) as follows.

  • Let \(p=(-1,-1,\cdots,-1)\).
  • For each \(v=N,N-1,\cdots,1\), do the following.
    • Look for positions in \(p\) where \(v\) can be put. Make the leftmost such element \(v\).

Let us count \(p\)s that can be generated this way.

We will fix the index \(m\) such that \(p_m=N\). For all intervals \(i\) that straddle \(m\), we have \(x_i=m\). Thus, we can handle the part to the left of \(m\) and the part to the right of \(m\) separately. The part to the right is easy: we just need to solve a problem in the same format as the original.

Consider the left part. Let \(k\) be the index with the largest element in the left part. If there is no interval that contains both \(k\) and \(m\), it would be valid to let \(p_k=N\), which contradict with the assumption \(p_m=N\). On the other hand, it can be seen that if there is an interval that contains both \(k\) and \(m\), there is no contradiction. In the end, to determine the left part, we need to solve the same problem with the new restriction that the index with the largest element must lie in some range.

Now we have a DP solution: for each \(l \leq m \leq r\), count the number of ways to set \(p\), only considering the segment \([l,r]\), such that the index with the largest element is \(m\) or greater. We can implement this DP in \(O(N^3)\).

posted:
last update: