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 <bits/stdc++.h>
using namespace std;
using lint = long long int;
using P = pair<int, int>;
using PL = pair<lint, lint>;
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
#define ALL(a)  (a).begin(),(a).end()
constexpr lint MOD1 = 1532834020;
constexpr lint MOD2 = 2147482409;
constexpr int INF = 2147483647;
void yes(bool expr) {cout << (expr ? "Yes" : "No") << "\n";}
lint power(lint x, lint n, lint mod) {
  lint ret = 1;
  while(n > 0) {
    if(n & 1) (ret *= x) %= mod;
    (x *= x) %= mod;
    n >>= 1;
  }
  return ret;
}
int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int N;
  cin >> N;
  vector<pair<string, int>> S(N);
  REP(i, N) {
    string x;
    cin >> x;
    //REP(j, 500000) x += ('a' + j%26) ;
    S[i] = make_pair(x, x.size());
  }
  sort(ALL(S), [](auto const &a, auto const &b) { return a.second > b.second;});
  set<lint> rem;
  REP(i, N) {
    lint hash = 0;
    IFOR(j, 1, S[i].second) {
      hash = hash * MOD1 % MOD2;
      hash = (hash + (S[i].first[j] - 'a' + 1)) % MOD2;
    }
    rem.insert(hash);
  }
  //REP(i, N) cout << S[i].first << "\n";
  lint ans = 0;
  lint inv = power(MOD1, MOD2-2, MOD2);
  vector<map<lint, lint>> st(26);
  REP(i, N) {
    lint hash = 0;
    IFOR(j, 1, S[i].second) {
      hash = hash * MOD1 % MOD2;
      hash = (hash + (S[i].first[j] - 'a' + 1)) % MOD2;
    }
    ans += st[S[i].first[0] - 'a'][hash];
    vector<bool> chr(26);
    REP(j, S[i].second) {
      //cout << hash << endl;
      if(j > 0) {
        hash = (hash - (S[i].first[j] - 'a' + 1) + MOD2) % MOD2;
        hash = hash * inv % MOD2;
      }
      chr[S[i].first[j] - 'a'] = true;
      if(rem.find(hash) != rem.end()) REP(k, 26) if(chr[k]) st[k][hash]++;
    }
  }
  cout << ans << endl;
}