Editorial for COCI '16 Contest 4 #5 Rima
Submitting an official solution before solving the problem yourself is a bannable offence.
We will reverse the given words and add them to a prefix tree. Two words rhyme if and only if the node that represents one of them is a parent of the node that represents the other word or if the two nodes have a common parent.
Let's observe a sequence where every two adjacent words rhyme. The sequence begins at a node in the tree and makes a couple of steps upwards or to the side. In other words, towards the parent or between the nodes with a common parent. Once it makes a step downwards, towards the child, it can only make steps to the side or downwards.
Now we can solve the task using dynamic programming. For each node, we calculate the largest number of nodes in its subtree that we can traverse moving only upwards or downwards (it doesn't make a difference), and to the side. For each node, we can assume that it is the highest node in the sequence, and find the two longest paths between its children. We must be careful to count all nodes with a common parent.
The total complexity is , where is the sum of lengths of all strings.
Comments