CF BUDDY
← Problems·

1902E · Collapsing Strings

1900 · data structures, strings, trees

Problem: You are given nn strings s1,s2,,sns_1, s_2, \dots, s_n, consisting of lowercase Latin letters. Let x|x| be the length of string xx.

Let a collapse C(a,b)C(a, b) of two strings aa and bb be the following operation:

  • if aa is empty, C(a,b)=bC(a, b) = b;
  • if bb is empty, C(a,b)=aC(a, b) = a;
  • if the last letter of aa is equal to the first letter of bb, then C(a,b)=C(a1,a1,b2,b)C(a, b) = C(a_{1,|a|-1}, b_{2,|b|}), where sl,rs_{l,r} is the substring of ss from the ll-th letter to the rr-th one;
  • otherwise, C(a,b)=a+bC(a, b) = a + b, i. e. the concatenation of two strings.

Calculate i=1nj=1nC(si,sj)\sum\limits_{i=1}^n \sum\limits_{j=1}^n |C(s_i, s_j)|.

Input Format: The first line contains a single integer nn (1n1061 \le n \le 10^6).

Each of the next nn lines contains a string sis_i (1si1061 \le |s_i| \le 10^6), consisting of lowercase Latin letters.

The total length of the strings doesn't exceed 10610^6.

Output Format: Print a single integer — i=1nj=1nC(si,sj)\sum\limits_{i=1}^n \sum\limits_{j=1}^n |C(s_i, s_j)|.

Sample Cases

Case 1

Input

3
aba
ab
ba

Output

20

Case 2

Input

5
abab
babx
xab
xba
bab

Output

126

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback