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)

#![allow(unused_imports)]
#![allow(non_snake_case, unused)]

use std::cmp::*;
use std::collections::*;
use std::ops::*;

// https://atcoder.jp/contests/hokudai-hitachi2019-1/submissions/10518254 より

macro_rules! eprint {
    ($($t:tt)*) => {{
        use ::std::io::Write;
        let _ = write!(::std::io::stderr(), $($t)*);
    }};
}
macro_rules! eprintln {
    () => { eprintln!(""); };
    ($($t:tt)*) => {{
        use ::std::io::Write;
        let _ = writeln!(::std::io::stderr(), $($t)*);
    }};
}
macro_rules! dbg {
    ($v:expr) => {{
        let val = $v;
        eprintln!("[{}:{}] {} = {:?}", file!(), line!(), stringify!($v), val);
        val
    }}
}

macro_rules! mat {
    ($($e:expr),*) => { Vec::from(vec![$($e),*]) };
    ($($e:expr,)*) => { Vec::from(vec![$($e),*]) };
    ($e:expr; $d:expr) => { Vec::from(vec![$e; $d]) };
    ($e:expr; $d:expr $(; $ds:expr)+) => { Vec::from(vec![mat![$e $(; $ds)*]; $d]) };
}

macro_rules! ok {
    ($a:ident$([$i:expr])*.$f:ident()$(@$t:ident)*) => {
        $a$([$i])*.$f($($t),*)
    };
    ($a:ident$([$i:expr])*.$f:ident($e:expr$(,$es:expr)*)$(@$t:ident)*) => { {
        let t = $e;
        ok!($a$([$i])*.$f($($es),*)$(@$t)*@t)
    } };
}

pub fn readln() -> String {
    let mut line = String::new();
    ::std::io::stdin().read_line(&mut line).unwrap_or_else(|e| panic!("{}", e));
    line
}

macro_rules! read {
    ($($t:tt),*; $n:expr) => {{
        let stdin = ::std::io::stdin();
        let ret = ::std::io::BufRead::lines(stdin.lock()).take($n).map(|line| {
            let line = line.unwrap();
            let mut it = line.split_whitespace();
            _read!(it; $($t),*)
        }).collect::<Vec<_>>();
        ret
    }};
    ($($t:tt),*) => {{
        let line = readln();
        let mut it = line.split_whitespace();
        _read!(it; $($t),*)
    }};
}

macro_rules! _read {
    ($it:ident; [char]) => {
        _read!($it; String).chars().collect::<Vec<_>>()
    };
    ($it:ident; [u8]) => {
        Vec::from(_read!($it; String).into_bytes())
    };
    ($it:ident; usize1) => {
        $it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1
    };
    ($it:ident; [usize1]) => {
        $it.map(|s| s.parse::<usize>().unwrap_or_else(|e| panic!("{}", e)) - 1).collect::<Vec<_>>()
    };
    ($it:ident; [$t:ty]) => {
        $it.map(|s| s.parse::<$t>().unwrap_or_else(|e| panic!("{}", e))).collect::<Vec<_>>()
    };
    ($it:ident; $t:ty) => {
        $it.next().unwrap_or_else(|| panic!("input mismatch")).parse::<$t>().unwrap_or_else(|e| panic!("{}", e))
    };
    ($it:ident; $($t:tt),+) => {
        ($(_read!($it; $t)),*)
    };
}


pub fn main() {
    let _ = ::std::thread::Builder::new().name("run".to_string()).stack_size(32 * 1024 * 1024).spawn(run).unwrap().join();
}

// const MOD: i64 = 998244353;
const MOD: usize = 1_000_000_007;
const INF: i64 = std::i64::MAX/2;

#[derive(Clone)]
pub struct Node {
    child: Vec<usize>,
    count: Vec<i64>,
}

impl Node {
    pub fn new() -> Self{
        Node {
            child: vec![0;26],
            count: vec![0;26],
        }
    }
}

pub struct Trie {
    nodes: Vec<Node>,
}

impl Trie {
    pub fn new() -> Self {
        let root = Node::new();
        Trie {
            nodes: vec![root],
        }
    }
    pub fn add(&mut self, c: &[char]) {
        let n = c.len();
        let mut cum = vec![vec![0;26];n+1];
        for i in 0..n {
            let val = (c[i] as u8 - 'a' as u8) as usize;
            for j in 0..26 {
                cum[i+1][j] += cum[i][j];
                if val==j {
                    cum[i+1][j] += 1;
                }
            }
        }
        let mut cur = 0;
        let mut cidx = 0;
        loop {
            if cidx==c.len() {
                break;
            }
            let nidx = (c[cidx] as u8 - 'a' as u8) as usize;
            if self.nodes[cur].child[nidx]==0 {
                let nnode = Node::new();
                self.nodes.push(nnode);
                self.nodes[cur].child[nidx] = self.nodes.len()-1;
            }
            for i in 0..26 {
                let tmp = cum[n][i] - cum[cidx][i];
                if tmp>0 {
                    self.nodes[cur].count[i] += 1;
                }
            }
            cur = self.nodes[cur].child[nidx];
            cidx += 1;
        }        
    }
    pub fn find(&self, c: &[char])->i64{
        let mut cur = 0;
        let mut cidx = 0;
        let mut count = 0;
        loop {
            let nidx = (c[cidx] as u8 - 'a' as u8) as usize;
            if cidx==c.len()-1 {
                count = self.nodes[cur].count[nidx];
                break;
            }
            cur = self.nodes[cur].child[nidx];
            if cur==0 {
                break;
            }
            cidx += 1;
        }
        return count;
    }
}

fn solve() {
    let n = read!(usize);
    let mut c = read!([char];n);
    let mut v = vec![];
    for c in &c {
        v.push((c.len(),c));
    }
    v.sort_by(|a,b| b.cmp(a));
    let mut trie = Trie::new();
    let mut ans = 0;
    for (_,x) in v {
        let mut c = x.clone();
        c.reverse(); 
        let tmp = trie.find(&c);
        // println!("{:?} {}",c, tmp);
        // println!("{:?}", root.clone().unwrap().borrow().count);
        ans += tmp;
        trie.add(&c);
    }
    println!("{}",ans);
}

fn run() {
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    solve();
}