AtCoder - abc353_e

· · 个人记录

题意

设 f(x, y) 表示 x 和 y 的最长公共前缀的长度, 请计算表达式的值

\sum\limits_{i=1}^{n-1} \sum\limits_{j=i+1}^{n} f(S_i, S_j)

思路

使用字典树,将遍历到的节点加一,查询时可快速求出每个节点的字符串数量。

按顺序查找和修改,可不重复计算。

代码

#include <bits/stdc++.h>
#define ll long long
#define min(a, b) (a < b ? a : b)
#define max(a, b) (a > b ? a : b)
using namespace std;
ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; }
void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); return; }

const int N = 3e5 + 3;
int n;
string s;

int t[N][37], c;
int a[N];
ll ans;

void change(){
    int p = 0;
    for(int i = 0; i < s.size(); i ++){
        if(!t[p][s[i] - 'a']) t[p][s[i] - 'a'] = ++ c;
        p = t[p][s[i] - 'a'];
        a[p] ++;
    }
}

int Find(){
    int p = 0, ans = 0;
    for(int i = 0; i < s.size(); i ++){
        if(!t[p][s[i] - 'a']) t[p][s[i] - 'a'] = ++ c;
        p = t[p][s[i] - 'a'];
        ans += a[p];
    }
    return ans;
}

int main(){

    n = read();
    for(int i = 1; i <= n; i ++){
        cin >> s;
        ans += Find();
        change();
    }
    write(ans);

    return 0;
}