题解:P16780 ⌈Xzy OI R1 T2⌋ 成成边

· · 题解

link

Solution

既然要求 LCP,肯定用字典树,把所有字符串放到字典树里。

首先,你需要知道 Cayley 公式:一个n 个节点完全图的生成树有 n^{n-2} 种,我就不证明了。

分析一下每条边的贡献,一个生成树有 n-1 条边,一共有 \dfrac{n \times (n-1)}{2} 条边,所以每条边会出现 m=\dfrac{(n-1) \times n^{n-2}}{\dfrac{n \times (n-1)}{2}} = 2 \times n^{n-3},当 n<3 时,m=1。

每当我们 insert 一个字符串时,每一个字符都会产生贡献,设这个字符的 cnt 值和上个字符的 cnt 值差为 edge,现在的深度为 dep,则加入这个字符会产生 edge 条边,贡献为 edge \times dep \times m,注意到了叶子也要加贡献。

Code

:::success[code]

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef char ch;
typedef string str;
typedef double db;
typedef __int128 i128;
const ll inf=9e18,mod=1e9+7,maxn=1e5+1;
const i128 Inf=1e35;
ll n,m,ans;
str s;
ll qpow(ll a,ll b)
{
    if(b==0) return 1;
    if(b==1) return a;
    ll temp=qpow(a,b/2);
    temp=temp*temp%mod;
    if(b%2) temp=temp*a%mod;
    return temp;
}
struct trie
{
    ll tr[maxn*26][27],tot,cnt[maxn*26];
    void insert(str s)
    {
        ll u=0,dep=0;
        for(int i=0;i<s.length();i++)
        {
            ll x=s[i]-'a';
            if(!tr[u][x]) tr[u][x]=++tot;
            ll edge=cnt[u]-cnt[tr[u][x]];
            ans=(ans+(dep*edge%mod)*m%mod)%mod;
            cnt[u]++,dep++,u=tr[u][x];
        }
        ans=(ans+(dep*cnt[u]%mod)*m%mod)%mod;
        cnt[u]++;
        return;
    }
}tree;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    m=(n<3?1:qpow(n,n-3)*2ll%mod);
    for(int i=1;i<=n;i++) cin>>s,tree.insert(s);
    cout<<ans;
}

:::