Official

D - Rolling Hash Editorial by evima


Since we can consider the elements of \(A\) modulo \(P\), we assume \(0 \leq A_i < P\) from now on.

For a sequence \(A\), we define a sequence \((C_1, C_2, \dots, C_{N + 1})\) by the following recurrence formula:

\[ \begin{aligned} C_{N + 1} &= 0 \\ C_i &= (C_{i + 1} + B^{N - i} A_i) \bmod{P} \end{aligned} \]

Here, the set of sequences \((A_1, A_2, \dots, A_N)\) \((0 \leq A_i < P)\) and the set of sequences \((C_1, C_2, \dots, C_N)\) \((0 \leq C_i < P)\) are in one-to-one correspondence. This is because, when we fix \((C_1, C_2, \dots, C_N)\), we can restore the corresponding \((A_1, A_2, \dots, A_N)\) using the formula

\[A_i = \left((C_i - C_{i+1}) \times B^{-(N - i)}\right) \bmod p\]

(Here, \(B^{-1}\) denotes the multiplicative inverse of \(B\) modulo \(p\).)

Moreover, \(\mathrm{hash}((A_L, A_{L+1}, \dots, A_R))\) can be rewritten using \(C\) as follows:

\[ \begin{aligned} &\mathrm{hash}((A_L, A_{L+1}, \dots, A_R)) \\ &=\left(\sum_{i=L}^R A_i B^{R-i}\right)\bmod{P} \\ &= \left(B^{R-N}\sum_{i=L}^R A_i B^{N-i}\right)\bmod{P} \\ &= B^{R-N}(C_L - C_{R + 1}) \bmod{P} \end{aligned} \]

Therefore, the condition \(\mathrm{hash}((A_L, A_{L+1}, \dots, A_R)) \neq 0\) is equivalent to the condition \(C_L \neq C_{R + 1}\). Thus, using \(C\), this problem can be rephrased as follows:

  • There is a graph with \(N + 1\) vertices and \(M\) edges. Edge \(i\) connects vertices \(L_i\) and \(R_i + 1\). Now, each vertex is to be colored with one of the \(P\) colors \(0,1,\dots,P-1\), with vertex \(N+1\) already colored \(0\). Determine whether it is possible to color all vertices so that vertices connected by an edge are not colored the same.

This is precisely a coloring problem. That is, we have reduced the problem to determining whether the chromatic number of the graph is less than or equal to \(P\).

Let’s explain how to find the chromatic number of a graph.

  • Let \(V\) be the set of vertices of the graph.
  • Let \(dp(v)\) be the chromatic number of the subgraph of \(G\) induced by \(\emptyset \neq v \subseteq V\).

Then, for \(\emptyset \neq v \subseteq V\), the following recurrence formula holds (\(\sqcup\) denotes the disjoint union):

\[dp(v) = \begin{cases} 1 & (v \text{ is an independent set}) \\ \displaystyle {\min_{s \sqcup t = v, s \neq \emptyset, t \neq \emptyset}} dp(s) + dp(t) & \mathrm{otherwise} \end{cases} \]

Therefore, we can calculate the chromatic number of \(G\) in \(\mathrm{O}(3^N)\) using what is commonly known as subset DP.
Thus, the problem is solved in \(\mathrm{O}(3^N)\).

posted:
last update: