Skip to content

CF2147F

Step 1

For every \(i\), there is a set of items it can be exchanged for in \(p\) and \(q\). These form a contiguous prefix. Therefore we are trying to find the minimum contiguous prefix that contains \(i\).

Step 2

By minimum, I mean \(p^{-1}\) and \(q^{-1}\) contains a contiguous prefix permutation of \((1 \dots m)\) such that \(m \ge i\) and is the smallest. Then we have the answer: $\(\sum{m_i (m_i - m_{i-1})}\)$

Step 3

We can use a segment tree for maintaining the answer. We can rephrase \(m\) to be: $\(m = \min_{1 \le i \le m}{t_i}\)$ where \(t\) is the relative order of \(p\) and \(q\).