This page is still under construction.

Parts of this page are still being built. What you see may change.

String Farm

Time limit5sMemory limit128 MB

Summary
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 s1,s2,…,sks_1, s_2, \dots, s_k must obey the following rule: for photo sis_i to come immediately before photo si+1s_{i+1}, string si+1s_{i+1} must be a grown form of sis_i; that is, sis_i must be a contiguous substring of si+1s_{i+1}. 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 NN (1≤N≤1041 \le N \le 10^4). Each of the next NN lines contains the string on one photo. Each string consists of lowercase letters only and has length at most 10001000.

Within a single test case, the sum of the lengths of all given strings does not exceed 10610^6.

The last line of the input contains a single 00, 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.

Examples3

  1. Example 1

    Input
    6
    plant
    ant
    cant
    decant
    deca
    an
    2
    supercalifragilisticexpialidocious
    rag
    0
    
    Expected output
    4
    2
    
  2. Example 2

    Input
    5
    abcd
    xyz
    a
    abc
    ab
    0
    
    Expected output
    4
    
  3. Example 3

    Input
    5
    a
    aa
    aaa
    aaaa
    aaaaa
    0
    
    Expected output
    5