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 Rust (1.42.0) (judge verdict: Accepted)

use std::io;

#[derive(Default, Debug)]
struct Trie {
    size: usize,
    children: [Option<Box<Trie>>; 26],
    leaf: [bool; 26],
    acc: [usize; 26],
}

impl Trie {
    fn insert(&mut self, x: &[u8]) {
        let target = (x[x.len() - 1] - b'a') as usize;
        self.size += 1;
        if x.len() == 1 {
            self.leaf[target] = true;
        } else {
            if self.children[target].is_none() {
                self.children[target] = Some(Box::new(Trie::default()));
            }
            self.children[target]
                .as_mut()
                .unwrap()
                .insert(&x[..x.len() - 1]);
        }
    }
    fn build_acc(&mut self) {
        for i in 0..26 {
            self.acc[i] = self.leaf[i] as usize;
        }
        for (i, c) in self.children.iter_mut().enumerate() {
            if let Some(c) = c.as_mut() {
                c.build_acc();
                for j in 0..26 {
                    if i != j {
                        self.acc[j] += c.acc[j];
                    } else {
                        self.acc[i] += c.size;
                    }
                }
            }
        }
    }
    fn aggregate(&self) -> usize {
        let mut sum = 0;
        for c in self.children.iter() {
            if let Some(c) = c.as_ref() {
                sum += c.aggregate();
            }
        }
        for i in 0..26 {
            if self.leaf[i] {
                sum += self.acc[i] - 1;
            }
        }
        sum
    }
}

fn main() {
    let mut trie = Trie::default();
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let n: usize = buf.trim_end().parse().unwrap();
    for _ in 0..n {
        buf.clear();
        io::stdin().read_line(&mut buf).unwrap();
        trie.insert(buf.trim_end().as_bytes());
    }
    trie.build_acc();
    println!("{}", trie.aggregate());
}