解题思路:很明显第一个条件是可以避免的,第二个条件是第三个条件的特殊情况,所以有用的只有第三个条件,现在我们就是想将这些单词重排使得每个单词后缀都在这个单词的前面并且代价最小
我们举个例子:
6
a
ca
ea
gda
hda
ifb
很明显我们发现很多点是没有用的我们为了计算其实可以直接提出红色的点
我们可以举几个例子,发现先跑子树小的明显最优
#include <iostream>
#include <cstdio>
#include <stack>
#include <sstream>
#include <limits.h>
#include <vector>
#include <map>
#include <cstring>
#include <deque>
#include <cmath>
#include <iomanip>
#include <queue>
#include <algorithm>
#include <set>
#define mid ((l + r) >> 1)
#define Lson rt << 1, l , mid
#define Rson rt << 1|1, mid + 1, r
#define ms(a,al) memset(a,al,sizeof(a))
#define log2(a) log(a)/log(2)
#define _for(i,a,b) for( int i = (a); i < (b); ++i)
#define _rep(i,a,b) for( int i = (a); i <= (b); ++i)
#define for_(i,a,b) for( int i = (a); i >= (b); -- i)
#define rep_(i,a,b) for( int i = (a); i > (b); -- i)
#define lowbit(x) ((-x) & x)
#define IOS std::ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define INF 0x3f3f3f3f
#define LLF 0x3f3f3f3f3f3f3f3f
#define hash Hash
#define next Next
#define pb push_back
#define f first
#define s second
using namespace std;
const int N = 1e5 + 10, mod = 1e9 + 9;
const long double eps = 1e-5;
const int EPS = 500 * 500;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef pair<double,double> PDD;
template<typename T> void read(T &x)
{
x = 0;char ch = getchar();ll f = 1;
while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
template<typename T, typename... Args> void read(T &first, Args& ... args)
{
read(first);
read(args...);
}
int n, idx, cnt;
int tr[N * 31][30];
char a[N * 6];
int tag[N * 31];
vector<int> g[N * 6];
int siz[N * 6];
void insert(char *a)
{
int rt = 0;
int len = strlen(a);
for(int i = len - 1; i >= 0; -- i)
{
if(!tr[rt][a[i] - 'a']) tr[rt][a[i] - 'a'] = ++ idx;
rt = tr[rt][a[i] - 'a'];
}
tag[rt] = 1;
}
void build(int rt,int last)//last是上一个红点编号是啥
{
if(tag[rt] && rt)
{
g[last].pb(rt);
last = rt;
}
for(int i = 0; i < 26; ++ i)
if(tr[rt][i])
build(tr[rt][i],last);
}
bool cmp(int x, int y)
{
return siz[x] < siz[y];
}
void dfs(int u)//按照子树大小排序
{
siz[u] = 1;
for(auto it : g[u])
{
dfs(it);
siz[u] += siz[it];
}
sort(g[u].begin(),g[u].end(),cmp);
}
ll ans = 0;
void getans(int x)
{
int dfn = cnt ++;
for(auto it : g[x])
{
ans += cnt - dfn;
getans(it);
}
}
int main()
{
read(n);
for(int i = 0; i < n; ++ i)
{
scanf("%s",a);
insert(a);
}
tag[0] = 1;
build(0,0);
dfs(0);
getans(0);
cout << ans << endl;
return 0;
}