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 Kotlin (1.3.71) (judge verdict: Time Limit Exceeded)

@file:Suppress("NOTHING_TO_INLINE", "EXPERIMENTAL_FEATURE_WARNING", "OVERRIDE_BY_INLINE")
//@file:OptIn(ExperimentalStdlibApi::class)

import java.io.PrintWriter
import kotlin.math.*
import kotlin.random.Random
import kotlin.collections.sort as _sort
import kotlin.collections.sortDescending as _sortDescending
import kotlin.io.println as iprintln

/** @author Spheniscine */
fun main() { _writer.solve(); _writer.flush() }
fun PrintWriter.solve() {
//    val startTime = System.nanoTime()

    val numCases = 1//readInt()
    case@ for(case in 1..numCases) {
//        print("Case #$case: ")

        val n = readInt()
        val S = Array(n) { read() }

        val P = Array(n) { i ->
            val s = S[i]
            val res = Array(s.length) { BooleanArray(26) }
            for(j in s.indices) {
                if(j > 0) res[j-1].copyInto(res[j])
                res[j][s[j] - 'a'] = true
            }
            res
        }

        val conc = StringBuilder()
        val posInConc = IntArray(n)
        for(i in 0 until n) {
            posInConc[i] = conc.length
            conc.append(S[i]).append('$')
        }

        var (suff, lcp) = conc.suffixArrayAndLCP()
        suff = suff.copyOfRange(1, suff.size)
        lcp = lcp.copyOfRange(1, lcp.size)

        val id = IntArray(suff.size)
        val pos = IntArray(suff.size)
        val sufflen = IntArray(suff.size)

        for(i in suff.indices) {
            id[i] = posInConc.bsIndexOfLast { suff[i] >= it }
            pos[i] = suff[i] - posInConc[id[i]]
            sufflen[i] = S[id[i]].length - pos[i]
        }

        var start = 0
        var ans = 0L

        while(start < suff.size) {
            var end = start
            while(end < lcp.size && lcp[end] > sufflen[end]) end++

            val cat1 = IntList()
            val cat2 = IntList()

            for(i in start..end) {
                when {
                    pos[i] == 1 -> cat1.add(i)
                    pos[i] > 1 -> cat2.add(i)
                }
            }

            val cnt = IntArray(26)
            for(i in cat2) {
                val p = P[id[i]][pos[i]-1]
                for(j in 0 until 26) if(p[j]) cnt[j]++
            }

            for(i in cat1) {
                val c = S[id[i]][pos[i]-1]
                ans += cnt[c - 'a']
            }

            start = end + 1
        }

        println(ans)

    }

//    iprintln("Time: ${(System.nanoTime() - startTime) / 1000000} ms")
}

class IntList(initialCapacity: Int = 12) {
    private var _arr = IntArray(initialCapacity)
    private val capacity get() = _arr.size
    var size = 0
        private set
    inline val lastIndex get() = size - 1
    inline val indices get() = 0 until size

    constructor(copyFrom: IntArray): this(copyFrom.size) { copyFrom.copyInto(_arr); size = copyFrom.size }
    constructor(copyFrom: Collection<Int>): this(copyFrom.size) { _arr = copyFrom.toIntArray(); size = copyFrom.size }

    fun contentEquals(other: IntList): Boolean {
        return this === other || size == other.size && indices.all { this[it] == other[it] }
    }

    private fun grow(minCapacity: Int = 8) {
        val newCapacity = maxOf(minCapacity, capacity + (capacity shr 1))
        _arr = _arr.copyOf(newCapacity)
    }

    fun ensureCapacity(minCapacity: Int) { if(capacity < minCapacity) grow(minCapacity) }

    operator fun get(index: Int): Int {
        require(index in 0 until size)
        return _arr[index]
    }

    operator fun set(index: Int, value: Int) {
        require(index in 0 until size)
        _arr[index] = value
    }

    fun add(value: Int) {
        if(size == capacity) grow()
        _arr[size++] = value
    }

    fun addAll(list: IntList) {
        ensureCapacity(size + list.size)
        list._arr.copyInto(_arr, size, 0, list.size)
        size += list.size
    }

    fun add(index: Int, element: Int) {
        if(size == capacity) grow()
        _arr.copyInto(_arr, index + 1, index, size)
        size++
        set(index, element)
    }

    fun clear() { size = 0 }

    fun removeAt(index: Int): Int {
        val e = get(index)
        _arr.copyInto(_arr, index, index + 1, size)
        size--
        return e
    }

    operator fun iterator() = object: IntIterator() {
        private var pos = 0
        override fun hasNext() = pos < size
        override fun nextInt() = get(pos++)
    }

    inline fun isEmpty() = size == 0
    inline fun isNotEmpty() = size != 0

    fun pop() = _arr[--size]

    fun swap(i: Int, j: Int) { val t = this[i]; this[i] = this[j]; this[j] = t }
    fun reverse() {
        for(i in 0 until size / 2) swap(i, lastIndex - i)
    }

    fun shuffle(rnd: Random = random) = _shuffle(rnd, _arr::get, _arr::set, size)
    fun sort() { shuffle(); _arr._sort(0, size) }
    fun sortDescending() { sort(); reverse() }

    fun joinToString(separator: CharSequence) = if(size == 0) "" else let {
        buildString {
            append(it[0])
            for (i in 1 until size) {
                append(separator).append(it[i])
            }
        }
    }

    override fun toString() = "[" + joinToString(", ") + "]"

    fun toIntArray() = _arr.copyOf(size)
    fun toList() = List(size, ::get)

    inline fun first() = get(0)
    inline fun last() = get(lastIndex)
}

inline fun IntList(size: Int, init: (Int) -> Int) = IntList(size).apply {
    for(i in 0 until size) { add(init(i)) }
}
inline fun IntArray.toIntList() = IntList(this)
inline fun Collection<Int>.toIntList() = IntList(this)
inline fun intListOf(vararg values: Int) = IntList(values)

fun IntList.max() = (1 until size).fold(this[0]) { acc, i -> max(acc, this[i]) }
fun IntList.min() = (1 until size).fold(this[0]) { acc, i -> min(acc, this[i]) }
fun IntList.getOrNull(i: Int) = if(i in indices) get(i) else null
inline fun IntList.count(predicate: (Int) -> Boolean) = indices.count { predicate(this[it]) }
fun IntList.copyOf() = IntList(size, ::get)


inline fun bsFirst(first: Int, last: Int, predicate: (Int) -> Boolean): Int {
    var low = first
    var high = last

    while (low <= high) {
        val mid = low.and(high) + low.xor(high).shr(1)
        if(predicate(mid)) high = mid - 1
        else low = mid + 1
    }
    return low
}
inline fun IntRange.bsFirst(predicate: (Int) -> Boolean) = bsFirst(first, last, predicate)

inline fun bsLast(first: Int, last: Int, predicate: (Int) -> Boolean) = bsFirst(first, last) { !predicate(it) } - 1
inline fun IntRange.bsLast(predicate: (Int) -> Boolean) = bsLast(first, last, predicate)

inline fun IntArray.bsIndexOfFirst(predicate: (Int) -> Boolean) = bsFirst(0, lastIndex) { predicate(get(it)) }
inline fun IntArray.bsFirst(predicate: (Int) -> Boolean) = get(bsIndexOfFirst(predicate))
inline fun IntArray.bsFirstOrNull(predicate: (Int) -> Boolean) = getOrNull(bsIndexOfFirst(predicate))
inline fun IntArray.bsIndexOfLast(predicate: (Int) -> Boolean) = bsLast(0, lastIndex) { predicate(get(it)) }
inline fun IntArray.bsLast(predicate: (Int) -> Boolean) = get(bsIndexOfLast(predicate))
inline fun IntArray.bsLastOrNull(predicate: (Int) -> Boolean) = getOrNull(bsIndexOfLast(predicate))

fun CharSequence.suffixArrayAndLCP(): Pair<IntArray, IntArray> {
    if(isEmpty()) return intArrayOf(0) to intArrayOf()

    val n = length

    var S = IntArray(n + 1)
    S[0] = n // for empty suffix ('$')

    // counting sort for ascii (max value assumed 127)
    val bkt = IntArray(129)
    bkt[0] = 1 // for empty suffix
    for(i in 0 until n) {
        bkt[this[i].toInt() + 1]++
    }
    for(i in 1 until bkt.lastIndex) {
        bkt[i] += bkt[i-1]
    }
    for(i in 0 until n) {
        S[bkt[this[i].toInt()]++] = i
    }

    // STL sort
//    val A = MutableList(n) { it }
//    A.sortBy { this[it] }
//    for(i in 0 until n) S[i+1] = A[i]

    var C = IntArray(n + 1)
    C[S[1]] = 1
    for(i in 2..n) {
        C[S[i]] = C[S[i-1]]
        if(this[S[i]] != this[S[i-1]]) C[S[i]]++
    }

    var k = 1
    while(k < n) {
        // counting sort
        @Suppress("NAME_SHADOWING")
        val bkt = IntArray(n+2)
        for(i in 0..n) {
            bkt[C[i]+1]++
        }
        for(i in 2..n) {
            bkt[i] += bkt[i-1]
        }

        val Sk = IntArray(n+1)
        for(s in S) {
            val j = s - k modulo n+1
            Sk[bkt[C[j]]++] = j
        }

        val Ck = IntArray(n+1)
        for(i in 1..n) {
            val a = Sk[i]
            val b = Sk[i-1]
            Ck[a] = Ck[b]

            val cmp = C[a] != C[b] || C[(a + k) % (n+1)] != C[(b + k) % (n+1)]
            if(cmp) Ck[a]++
        }

        S = Sk
        C = Ck

        k = k shl 1
    }

    // LCP
    val L = IntArray(n)
    k = 0
    for(i in 0 until n) {
        val pi = C[i] // final C = S^-1
        val j = S[pi - 1]
        while(max(i, j) + k < n && this[i+k] == this[j+k]) k++
        L[pi-1] = k
        if(k > 0) k--
    }

    return S to L
}

infix fun Int.modulo(mod: Int): Int = (this % mod).let { (it shr Int.SIZE_BITS - 1 and mod) + it }


/** IO */
//@JvmField val INPUT = File("input.txt").inputStream()
//@JvmField val OUTPUT = File("output.txt").outputStream()
@JvmField val INPUT = System.`in`
@JvmField val OUTPUT = System.out

const val _BUFFER_SIZE = 1 shl 16
@JvmField val _buffer = ByteArray(_BUFFER_SIZE)
@JvmField var _bufferPt = 0
@JvmField var _bytesRead = 0

tailrec fun readChar(): Char {
    if(_bufferPt == _bytesRead) {
        _bufferPt = 0
        _bytesRead = INPUT.read(_buffer, 0, _BUFFER_SIZE)
    }
    return if(_bytesRead < 0) Char.MIN_VALUE
    else {
        val c = _buffer[_bufferPt++].toChar()
        if (c == '\r') readChar()
        else c
    }
}

fun readLine(): String? {
    var c = readChar()
    return if(c == Char.MIN_VALUE) null
    else buildString {
        while(c != '\n' && c != Char.MIN_VALUE) {
            append(c)
            c = readChar()
        }
    }
}
fun readLn() = readLine()!!

fun read() = buildString {
    var c = readChar()
    while(c <= ' ') {
        if(c == Char.MIN_VALUE) return@buildString
        c = readChar()
    }
    do {
        append(c)
        c = readChar()
    } while(c > ' ')
}
fun readInt() = read().toInt()
fun readDouble() = read().toDouble()
fun readLong() = read().toLong()
fun readStrings(n: Int) = List(n) { read() }
fun readLines(n: Int) = List(n) { readLn() }
fun readInts(n: Int) = List(n) { read().toInt() }
fun readIntArray(n: Int) = IntArray(n) { read().toInt() }
fun readDoubles(n: Int) = List(n) { read().toDouble() }
fun readDoubleArray(n: Int) = DoubleArray(n) { read().toDouble() }
fun readLongs(n: Int) = List(n) { read().toLong() }
fun readLongArray(n: Int) = LongArray(n) { read().toLong() }

@JvmField val _writer = PrintWriter(OUTPUT, false)

/** shuffles and sort overrides to avoid quicksort attacks */
private inline fun <T> _shuffle(rnd: Random, get: (Int) -> T, set: (Int, T) -> Unit, size: Int) {
    // Fisher-Yates shuffle algorithm
    for (i in size - 1 downTo 1) {
        val j = rnd.nextInt(i + 1)
        val temp = get(i)
        set(i, get(j))
        set(j, temp)
    }
}

@JvmField var _random: Random? = null
val random get() = _random ?: Random(0x594E215C123 * System.nanoTime()).also { _random = it }

fun IntArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun IntArray.sort() { shuffle(); _sort() }
fun IntArray.sortDescending() { shuffle(); _sortDescending() }

fun LongArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun LongArray.sort() { shuffle(); _sort() }
fun LongArray.sortDescending() { shuffle(); _sortDescending() }

fun DoubleArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
fun DoubleArray.sort() { shuffle(); _sort() }
fun DoubleArray.sortDescending() { shuffle(); _sortDescending() }

fun CharArray.shuffle(rnd: Random = random) = _shuffle(rnd, ::get, ::set, size)
inline fun CharArray.sort() { _sort() }
inline fun CharArray.sortDescending() { _sortDescending() }

inline fun <T: Comparable<T>> Array<out T>.sort() = _sort()
inline fun <T: Comparable<T>> Array<out T>.sortDescending() = _sortDescending()
inline fun <T: Comparable<T>> MutableList<out T>.sort() = _sort()
inline fun <T: Comparable<T>> MutableList<out T>.sortDescending() = _sortDescending()

fun `please stop removing these imports IntelliJ`() { iprintln(max(1, 2)) }

/** additional commons */
inline fun <T> Iterable<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Sequence<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
inline fun <T> Array<T>.sumByLong(func: (T) -> Long) = fold(0L) { acc, t -> acc + func(t) }
fun IntArray.sumLong() = fold(0L, Long::plus)