Official

E - Half Palindromes Editorial by DEGwer


Use Manacher’s algorithm to compute palindrome radii.

Let us consider solving the subproblems for \(T\). Since cutting prefixes does not increase the answer, a simple greedy strategy works.

Let us consider solving the problem for \(S\). For an index \(j\), let the sum of the answers for the problems for \(T=S[i...j]\) for all \(i\leq j\) be \(s_j\). We manage \(s_j\) while increasing \(j\) one by one.

Let \(f_j(i)\) be the largest index such that \(S[i...j]\) can be contracted to \(S[f_j(i)...j]\) by applying the operation in the problem. Then, for each \(k\), the set of indices \(i\) with \(f_j(i)=k\) is an interval ending at \(k\). Let these intervals be \([1=x_0,...,x_1-1],[x_1,...,x_2-1],...,[x_{t_j-1},...,x_{t_j}-1=j]\) and consider managing them while increasing \(j\) one by one.

By increasing \(j\), these intervals are only merged. Since the merging operation happens \(O(1)\) times amortized, all we have to do is enumerating all merging events.

Using a sparse table and a binary search, we can enumerate all such events in \(O(|S|\log |S|)\) time. The following observation is useful: An interval \(I\) is merged with the next interval when there is a palindrome that begins in \(I\), has the center outside of \(I\), and ends at \(j+1\). Since \(I\) has not been merged before, we should only consider that the palindrome begins at the endpoint of \(I\).

Therefore, this problem can be solved in \(O(|S|\log |S|)\) time.

posted:
last update: