Mix and Build

Time limit1sMemory limit128 MB

Summary
Find the longest sequence of given distinct words where each word is formed by adding one letter and rearranging.
Level

Medium6 of 10

Topics
Hash map, Dynamic programming, String, Sorting
Solved
No attempts yet

Problem

You are given a list of words, where each word is a sequence of lowercase letters. From this list, find the longest chain of words w1,w2,…,wnw_1, w_2, \ldots, w_n in which every wiw_i is a mixed extension of wi−1w_{i-1}.

A word AA is a mixed extension of a word BB if AA can be obtained by adding exactly one letter to BB and then rearranging all of the letters in any order. Equivalently, AA is a mixed extension of BB when the multiset of letters of AA equals the multiset of letters of BB together with one extra letter (so the length of AA is exactly one greater than the length of BB).

For example, the words ab, bar, crab, cobra, carbon form a chain of length 55, because each word is a mixed extension of the one before it.

Input

The input contains at least 22 and at most 1000010000 lines. Each line contains one word. Every word has length at least 11 and at most 2020 and consists only of lowercase letters. All words are distinct.

Output

Print a single integer: the length of the longest chain (that is, the number of words in it) that can be built from the given words.

Examples1

  1. Example 1

    Input
    ab
    arc
    arco
    bar
    bran
    carbon
    carbons
    cobra
    crab
    crayon
    narc
    
    Expected output
    6