Problem:
Score : 700 points

Problem Statement

Limak can repeatedly remove one of the first two characters of a string,
for example abcxyx \rightarrow acxyx \rightarrow cxyx \rightarrow cyx.

You are given N different strings S_1, S_2, \ldots, S_N.
Among N \cdot (N-1) / 2 pairs (S_i, S_j),
in how many pairs could Limak obtain one string from the other?

Constraints

2 \leq N \leq 200\,000

S_i consists of lowercase English letters a-z.

S_i \neq S_j

1 \leq |S_i|

|S_1| + |S_2| + \ldots + |S_N| \leq 10^6

Input

Input is given from Standard Input in the following format.

N
S_1
S_2
\vdots
S_N

Output

Print the number of unordered pairs (S_i, S_j)
where i \neq j and Limak can obtain one string from the other.

Sample Input 1

3
abcxyx
cyx
abc

Sample Output 1

1

The only good pair is (abcxyx, cyx).

Sample Input 2

6
b
a
abc
c
d
ab

Sample Output 2

5

There are five good pairs: (b, abc), (a, abc), (abc, c), (b, ab), (a, ab).

Solution in C++ (GCC 9.2.1) (judge verdict: Wrong Answer)

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
using ull = unsigned long long;
const static int MAX_N = 200000;
int first[MAX_N][26];

int main(){
    unsigned N;
    scanf("%u\n", &N);
    pair<string, pair<char, unsigned> > word[N];
    unsigned sz[N];
    memset(first, -1, sizeof first);
    for (unsigned i = 0; i < N; i++)
    {
        cin >> word[i].first;
        sz[i] = word[i].first.size();
        reverse(word[i].first.begin(), word[i].first.end());
        for (unsigned j = 0; j < sz[i]; j++){
            first[i][word[i].first[j] - 'a'] = j;
        }
        word[i].second.second = i;
        word[i].second.first = word[i].first[sz[i]-1];

    }
    sort(word, word + N);
    ull answer = 0;
    for (unsigned i = 0; i < N-1; i++){
        word[i].first.pop_back();
        unsigned j = i+1;
        while(j < N && sz[word[j].second.second] == sz[word[i].second.second]) j++;
        while(j < N && word[j].first.substr(0, sz[word[i].second.second]-1) == word[i].first){
            if(first[word[j].second.second][word[i].second.first - 'a'] + 1 >= sz[word[i].second.second]) answer++;
            j++;
        }
    }
    printf("%llu\n", answer);
	return 0;
}