Official

B - L Robust IS Editorial by evima


For simplicity, assume that all \(A_i\) are distinct. This can be achieved by preprocessing such as

  • \(A_i := NA_i + i\)
  • \(X := NX\)
  • \(Y := NY\)

For example, the problem can be solved in polynomial time with a DP such as dp[i][l][a][s] = “whether there is a subsequence of the first \(i\) elements with length \(l\) and last element \(a\), such that the next element to be appended must be at least \(s\).”

Put differently, this DP appends elements one by one while maintaining a set of tuples \((l, a, s)\). However, there are far too many tuples to keep all of them.

Here, if two states \((l, a, s)\) and \((l', b, t)\) satisfy \(l \ge l'\), \(a \le b\), and \(s \le t\), the latter can obviously be discarded. The key fact of this problem is that at most \(N + 1\) maximal tuples survive this pruning.

More strongly, we can show that if two states \((l, a, s)\) and \((l', b, t)\) satisfy \(l \ge l'\) and \(a \lt b\), then \((l', b, t)\) can be discarded.

  • If \(s \le t\), this is obvious.
  • If \(a\) appears before \(b\) in the sequence, appending \(b\) to \((l, a, s)\) yields a better state.
  • If \(b\) appears before \(a\) in the sequence, appending \(a\) to \((l', b, t)\) yields a better state.

By repeatedly removing unnecessary tuples in this way, the state can be compressed into a sequence of tuples \((l_1, a_1, s_1), (l_2, a_2, s_2), \cdots, (l_m, a_m, s_m)\) satisfying the following conditions.

  • \(l_i\) is monotonically increasing.
  • \((a_i, s_i)\) is monotonically increasing in lexicographical order (the \(a_i\) are not necessarily distinct).

It then suffices to manage this tuple sequence with a suitable data structure, for example a segment tree indexed by \(l_i\) that stores \((a_i, s_i)\), and to update the states efficiently.

With a careful implementation, the total number of operations can be bounded by \(O(N)\), using (the number of tuples in the sequence) + (the number of distinct values among the \(a_i\)) as the potential. Therefore, the overall complexity is \(O(N \log N)\).


The writer’s solution simplifies the implementation using further observations, such as the fact that unnecessary tuples do not actually need to be removed completely.

posted:
last update: