G - Minimum Permutation Editorial by en_translator
For the \(B\) to be printed, we first try to determine \(B _ 1\).
Let \(f(x)\ (1\leq x\leq M)\) maximum \(i\) such that \(A _ i=x\).
For \(\displaystyle r\coloneqq\min _ {1\leq x\leq M}f(x)\), we can show that \(B _ 1\) is one of \(A _ 1,A _ 2,\ldots,A _ r\)
(otherwise, \(B\) is a subsequence of \(A _ {\gt r}\coloneqq(A _ {r+1},A _ {r+2},\ldots,A _ N)\), but \(A _ {\gt r}\) does not contain \(A _ r\), which violates the condition of \(B\)).
Conversely, there exists a length-\(M\) subsequence whose first element is one of \(A _ i\ (1\leq i\leq r)\) that contains \(1,2,\ldots,M\) once each. In particular, the subsequence that contains \(A _ {f(x)}\) for all \(x\neq A _ i\) satisfies the condition.
Thus, \(B _ 1=A _ l=\displaystyle\min _ {1\leq i\leq r}A _ i\). We can let \(l\) be the minimum integer \(j\) such that \(A _ j=\displaystyle\min _ {1\leq i\leq r}A _ i\).
One can determine all the elements of \(B\) by repeating similar problem against the following sequence (with an appropriate replacement of element):
- the sequence obtained by removing the first \(l\) terms and all elements such that \(A _ i=B _ 1\) from \(A\).
The operations against a sequence can be simulated using a priority queue or a segment tree.
In case of using a priority queue to manage \((A _ i,i)\),
- We can find the minimum value of the first \(r\) elements by putting the first \(r\) terms and finding their minimum value.
- Removing the first \(l\) elements of \(A\) and removing \(A _ i\) that has the same value as something can be achieved by repeatedly removing an element from the priority queue as long as the top element of the queue satisfies a condition.
In case of a segment tree, we can do similarly.
- Removing \(A_i\) that has the same value as something can be achieved by replacing that \(A _ i\) with \(\infty\) when removing.
- The minimum value of the first \(r\) elements is a segment minimum after the replacements.
The time complexity is \(O(N\log N)\) for both approaches, which is fast enough.
posted:
last update: