#P1688. 新单词接龙问题

新单词接龙问题

Description

Given a dictionary that contains nn words, define the dictionary order as the order within this dictionary (i.e., the given list order). Select some words and form a word ladder in dictionary order so that the ladder length is maximized.

Rules for the new word ladder:

  1. Word transformation: from wiw_i, adding one letter, deleting one letter, or changing one letter can obtain wi+1w_{i+1}.
  2. Dictionary-order chain: w1,w2,,wkw_1, w_2, \cdots, w_k are in dictionary order.

Input Format

The first line contains an integer nn (1n25,0001 \le n \le 25,000), the total number of words in the dictionary. The next nn lines, in dictionary order, contain nn words, one string per line. Each word consists only of lowercase letters, and its length is between 11 and 1616 inclusive.

Output Format

Output a single integer on one line, the maximum possible length of the word ladder.

9
cat
dig
dog
fig
fin
fine
fog
log
wine

5

Hint

Sample explanation:

A word ladder of length 55 is: $\texttt{dig}\to \texttt{fig}\to \texttt{fin}\to \texttt{fine}\to \texttt{wine}$.

Translated by ChatGPT 5