公式

A - Two in the Range 解説 by evima 印刷ページ


Let \(p_1,p_2,\cdots,p_k\) be the positions where \(1\)s are placed, and rephrase the conditions in the problem statement in terms of the \(p_i\).

First, append two \(1\)s as sentinels to each of the beginning and the end of \(x\), and shift every interval to the right by \(2\). Redefining \(N\) as the length of the resulting sequence, we may assume \(p_1=1,p_2=2,p_{k-1}=N-1,p_k=N\).

When placing a \(1\) at position \(z=p_i\) (\(3 \leq i\)), the following conditions must be satisfied.

  • Let \(A_z\) be the maximum of \(L_j\) over all \(j\) with \(R_j<z\) (or \(-1\) if no such \(j\) exists). Then, \(A_z \leq p_{i-2}\) must hold.
  • Let \(B_z\) be the minimum of \(L_j\) over all \(j\) with \(z\leq R_j\) (or \(\infty\) if no such \(j\) exists). Then, \(p_{i-2}<B_z\) must hold.

Conversely, if these conditions hold for every \(p_i\), then exactly two \(1\)s are placed in each interval.

Based on these conditions, we can consider the following DP.

  • \(dp[z]\): Consider determining a prefix of \(p\) from the beginning so that its last element is \(z\). Let \(dp[z]\) be the set of indices that can appear immediately before \(z\) in such a sequence. If no such sequence exists, \(dp[z]=\emptyset\).

The transitions of this DP are as follows.

  • \(dp[z]=\{i | i<z,\ [A_z,B_z-1] \cap dp[i] \neq \emptyset \}\)

Naturally, a naive implementation of this is too slow. Thus, we need to look more closely at the structure of \(dp[z]\). In fact, \(dp[z]\) has the following property.

  • Let \(w_1,w_2,\cdots,w_s\) be the sequence of all \(z\) with non-empty \(dp[z]\), in ascending order. Then, each \(dp[z]\) is a contiguous subsequence of \(w\). Moreover, both the left ends and the right ends of these intervals are monotonically non-decreasing.

This property follows from the monotonicity of \(A_z\) and \(B_z\). By considering the process of computing \(dp[z]\) from the beginning, one can verify that the desired monotonicity always holds.

By this property, it suffices to maintain \(dp[z]\) as an interval. Computing the transitions reduces to lower_bound on a monotonically non-decreasing sequence.

Therefore, the problem can be solved in \(O(N + M \log M)\) time in total. Note that lower_bound can be replaced with the two-pointer technique, in which case the complexity becomes \(O(N+M)\).

Sample Solution (C++)

投稿日時:
最終更新: