Editorial for COCI '11 Contest 5 #4 Razbibriga
Submitting an official solution before solving the problem yourself is a bannable offence.
Notice that we don't need the whole words to solve the problem, only the first and last letters are important. Therefore, it is sufficient to memorize, for each pair of letters, the number of words that begin and end with the respective letters.
Now we can select all possible combinations of letters in the corners of the square ( possibilities). For each combination, we simply add the number of possible squares with the respective corners.
On each edge, we can place any word starting and ending with the appropriate letters. This word selection would always be independent if we could use the same word multiple times in the same square. If the number of possible words on the appropriate edges is denoted by , , , and , the solution would be (ignoring the fact that we cannot select the same word multiple times).
However, if there are two edges requiring the same pair of beginning and ending letters, for example if the first two edges satisfy that constraint, the solution is . It follows from the fact that we cannot choose from all words for the second edge since we have already used one word up for the first edge.
By generalizing this result, we find that if edges require the same pair of beginning and ending letters, and we have such words, we can select the edges in ways.
The complexity of the solution, not counting input, is .
Comments