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 Java (OpenJDK 11.0.6) (judge verdict: Time Limit Exceeded)


import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
	static class LenComparator implements Comparator<String>{
		@Override
		public int compare(String o1, String o2) {
			return o1.length() - o2.length();
		}
	}
	static long solve(String S[]){
		Arrays.sort(S, new LenComparator());
		Map<String, int[]> map = new HashMap<String, int[]>();
		long tot = 0;
		for(String s : S){
			int vis[] = new int[26];
			vis[s.charAt(0) - 'a'] = 1; 
			for(int i = 1; i <= s.length() ; ++i){
				String sub = s.substring(i);
				if(map.containsKey(sub)){
					int[] arr = map.get(sub);
					for(int j = 0 ; j < 26 ; ++j){
						tot += arr[j] * vis[j];
					}
				}
				if(i < s.length()){
					vis[s.charAt(i) - 'a'] = 1;					
				}
			}
			String suffix = s.substring(1);
			if(!map.containsKey(suffix)){
				map.put(suffix, new int[26]);
			}
			char s0 = s.charAt(0);
			int arr[] = map.get(suffix);
			arr[s0 - 'a']++;
		}
		return tot;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);		
		int N = sc.nextInt();
		String S[] = new String[N];
		for(int i = 0 ; i < N ; ++i){
			S[i] = sc.next();			
		}
		long ret = solve(S);
		System.out.println(ret);
	}
}