This page is still under construction.

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

Insidious Branding

Time limit2sMemory limit128 MB

Summary
Count quadruples of dictionary words A, B, C, D with A+B = C+D and length(A) < length(C).
Level

Medium7 of 10

Topics
Hash map, String
Solved
No attempts yet

Problem

"I know a trick worth two of that"

-- William Shakespeare, Henry IV, Part 1, Act II, Scene 1

A brand designer has proposed a strategy that could be the key to your company's success — and therefore to yours. The idea is to pick a brand name that can be split into a pair of common everyday words in two different ways, then bombard consumers with all four words in short bursts of sensory overload. The consumer's mind is jarred, and the brand eases its way into long-term memory.

Your task is to write a program that searches a dictionary for combinations of four words (not necessarily distinct) AA, BB, CC, and DD that satisfy

A+B=C+DA + B = C + D

where ++ denotes concatenation, == denotes an exact string match, the length of AA is strictly less than the length of CC, and all four words are non-empty.

Input

The input contains several test cases; each test case uses its own dictionary. A test case begins with a line containing an integer WW (1≤W<100,0001 \le W < 100{,}000), the number of words in the dictionary. Each of the next WW lines contains one word. The words appear in no particular order and are all distinct within a test case. Each word is a string of LL lowercase letters and contains no spaces, where 1<L<301 < L < 30. The input ends with a line containing a single 00.

Output

For each test case, output on its own line a single integer: the number of equations A+B=C+DA + B = C + D that can be formed.

Examples3

  1. Example 1

    Input
    4
    catchment
    ally
    catch
    mentally
    0
    
    Expected output
    1
    
  2. Example 2

    Input
    3
    ab
    cd
    ef
    0
    
    Expected output
    0
    
  3. Example 3

    Input
    4
    catchment
    ally
    catch
    mentally
    3
    ab
    cd
    ef
    0
    
    Expected output
    1
    0