B - Near Assignment Editorial by evima
If \(A = B\), it is clearly possible, so we consider other cases.
Consider two cases based on the value of \(K\).
Case \(K = 1\):
Considering the result of run-length encoding of the elements in \(A\), it can “decrease” through operations, but not “increase.” From this, we can deduce that the result of run-length encoding of \(B\) must be a subsequence of the run-length encoded \(A\). This condition is also sufficient, because we can perform operations that extend the subsequence of \(A\) corresponding to \(B\). This solves the case where \(K = 1\).
Case \(K \geq 2\):
Looking at the operations in reverse, they can be seen as follows:
- Choose \(i,j\) that satisfy \(|i-j| \leq K\) and \(B_i = B_j\), then change \(B_i\) to any desired value.
First, if no operation can be performed on \(B\), the answer is No
.
Also, if there is a value in \(B\) that does not appear in \(A\), the answer is No
.
Actually, in all other cases, the answer is Yes
.
Let’s reinterpret the part where \(B_i\) can be changed to any desired value as an operation where \(B_i\) is changed to a wildcard \(*\). By performing one operation on \(B\), we create a state where there is exactly one \(*\).
The involvement of \(*\) enables us to swap adjacent elements in \(B\).
- If you want to change \(*x\) to \(x*\): think of \(*x\) as \(xx\) and perform the operation to turn it into \(x*\).
- If you want to change \(*xy\) to \(*yx\): follow the steps \(*xy \to yxy \to yx* \to y*x \to *yx\).
By combining these operations, you can remove all duplicates in \(B\) and arrange them in any desired order. In particular, you can arrange \(B\) to match \(A\). Therefore, it can be determined that \(A\) can be transformed into \(B\).
Implementing the above operations directly yields an \(O(N)\) solution. The sample code below lazily uses sorting and is an \(O(N\log N)\) solution.
posted:
last update: