题解:P16780 ⌈Xzy OI R1 T2⌋ 成成边
NoneOfTheAbove · · 题解
link
Solution
既然要求 LCP,肯定用字典树,把所有字符串放到字典树里。
首先,你需要知道 Cayley 公式:一个
分析一下每条边的贡献,一个生成树有
每当我们 insert 一个字符串时,每一个字符都会产生贡献,设这个字符的
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;
}
:::