String Farm
Time limit5sMemory limit128 MB
Given up to 10^4 strings, find the longest chain where each string is a contiguous substring of the next, all photos distinct.
- Level
Medium7 of 10
- Topics
- String, Dynamic programming, String matching, Sorting
- Solved
- No attempts yet
Problem
Sanggeun and Seonyeong run a rather unusual farm. Most farms raise animals or grow vegetables, but they raise strings.
A string is a sequence of consecutive characters. Whenever a string grows, a single character is appended only to its left end or its right end. Existing characters are never removed, and no character is ever inserted into the middle of a string.
The two of them photographed their strings as they grew. Unfortunately, they wrote nothing on the photos, so they forgot which photo shows which string. Now they want to hang the photos on a wall in the order the strings grew.
Each photo can be described by a single string. A sequence of photos must obey the following rule: for photo to come immediately before photo , string must be a grown form of ; that is, must be a contiguous substring of . They never take the same photo twice, so all photos used in a sequence are distinct.
Given the photos they took, write a program that finds the largest number of photos that can be lined up while obeying the rule.
Input
The input consists of several test cases.
The first line of each test case contains the number of photos (). Each of the next lines contains the string on one photo. Each string consists of lowercase letters only and has length at most .
Within a single test case, the sum of the lengths of all given strings does not exceed .
The last line of the input contains a single , which marks the end of the input.
Output
For each test case, print on its own line the length of the longest sequence of photos that can be arranged according to the rule.