Editorial for COCI '21 Contest 6 #4 Palindromi
Submitting an official solution before solving the problem yourself is a bannable offence.
For the first subtask, we can iterate over all substrings of the new string after each concatenation and check (e.g. using hashing) how many different palindromes there are. In this way, for a word of length
The following fact is useful for the remaining subtasks: if we append a character
In short, each subpalindrome of
For the final subtask, we need to make a couple of modifications:
- Instead of the time complexity of
being amortized , we can make it so that it is (non-amortized) , where is the alphabet size. In our case, the alphabet consists only of the characters0
and1
, so we consider the time complexity to be . Along with , it is enough to keep track of two additional values: and , which represent the longest proper suffix in front of which is the character0
or1
respectively. All the mentioned values can be computed in when adding a new node. - Instead of having a function
which adds the character to the right, we'll support adding character both to the left and to the right. To do this, we maintain both the longest prefix and the longest suffix palindrome of the current string. When adding a character to the right, this affects only the longest suffix palindrome, and when adding it to the left it affects only the longest prefix palindrome. The only exception is when the entire string becomes a palindrome, in which case the longest prefix and suffix palindromes are equal and are equal to the entire string. Since the time complexity is no longer amortized, appending to both sides is done in . - We'll append the smaller string to the larger string. If the right string is smaller than the left string, we successively add characters from the right string to the right end of the left string. If the left string is smaller, we successively add characters from the left string to the left end of the right string. It can be shown that the number of times a character gets added to a string is
, and since we have a data structure which supports these additions in , the total time complexity is also .
Comments