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: Wrong Answer)

use proconio::{input, marker::Bytes, source::auto::AutoSource};
use std::collections::{BTreeSet, HashMap};

fn bisect(ss: &[Vec<u8>], target: &[u8]) -> usize {
    let mut lo = 0;
    let mut hi = ss.len();
    while lo < hi {
        let mid = (lo + hi) / 2;
        let s = &ss[mid][..target.len().min(ss[mid].len())];
        if target < s {
            hi = mid;
        } else {
            lo = mid + 1;
        }
    }
    hi
}

fn main() {
    let source = AutoSource::from(
        r#"6
b
a
abc
c
d
ab
"#,
    );
    input! {
        from source,
        n: usize,
        ss: [Bytes; n],
    }
    let mut ss = ss
        .into_iter()
        .map(|s| s.into_iter().rev().map(|c| c - 97).collect::<Vec<_>>())
        .collect::<Vec<_>>();
    ss.sort();

    let mut count = 0;
    let mut will_remove = HashMap::new();
    let mut btree_list = vec![BTreeSet::new(); 26];
    for (i, s) in ss.iter().enumerate() {
        let j = i + bisect(&ss[i + 1..], &s[..s.len() - 1]);

        let c = *s.last().unwrap();
        let m = s.len() - 1;
        will_remove.entry(j).or_insert_with(Vec::new).push((c, m));
        btree_list[c as usize].insert(m);

        if let Some(remove) = will_remove.get(&i) {
            for &(c, k) in remove.iter() {
                btree_list[c as usize].remove(&k);
            }
        }
        let mut used = [false; 26];
        for (i, &c) in s.iter().enumerate().rev() {
            let c = c as usize;
            if used[c] {
                continue;
            }
            used[c] = true;
            for k in btree_list[c].iter() {
                if *k <= i {
                    count += 1;
                } else {
                    break;
                }
            }
        }
    }
    println!("{}", count);
}