Arkady's code contains nn variables. Each variable has a unique name consisting of lowercase English letters only. One day Arkady decided to shorten his code.
He wants to replace each variable name with its non-empty prefix so that these new names are still unique (however, a new name of some variable can coincide with some old name of another or same variable). Among such possibilities he wants to find the way with the smallest possible total length of the new names.
A string aa is a prefix of a string bb if you can delete some (possibly none) characters from the end of bb and obtain aa.
Please find this minimum possible total length of new names.
The first line contains a single integer nn (1≤n≤1051≤n≤105) — the number of variables.
The next nn lines contain variable names, one per line. Each name is non-empty and contains only lowercase English letters. The total length of these strings is not greater than 105105. The variable names are distinct.
Print a single integer — the minimum possible total length of new variable names.
3 codeforces codehorses code
6
5 abba abb ab aa aacada
11
3 telegram digital resistance
3
In the first example one of the best options is to shorten the names in the given order as "cod", "co", "c".
In the second example we can shorten the last name to "aac" and the first name to "a" without changing the other names.
题解: 建字典树,假设有n个人站在起点,最后每个人都站在不同的点, 使所有有人的点到起点的距离之和最小。 开始假设每个人都站在最末端,然后向上搜索,若有空位置,则 向上补上空位置。 代码: #include<bits/stdc++.h> using namespace std; const int maxn=1e5+7; char t[maxn]; int tire[maxn][26],cnt=1; int par[maxn],ans=0,L[maxn]; bool vis[maxn]; vector<int>p[maxn]; void build() { int len=strlen(t),cur=0; for(int i=0;i<len;i++) { int k=t[i]-'a'; if(tire[cur][k]==0)tire[cur][k]=cnt++; par[tire[cur][k]]=cur; cur=tire[cur][k]; L[cur]=i+1; } vis[cur]=1;ans+=len; p[len].push_back(cur); } int get(int x) { if(par[x]==-1)return -1; if(!vis[x])return x; return par[x]=get(par[x]); } void pp() { for(int i=maxn-1;i>=1;i--) { for(int j=0;j<p[i].size();j++) { int x=p[i][j]; int fx=get(x); if(fx!=-1) { vis[fx]=1; ans=ans-L[x]+L[fx]; p[L[fx]].push_back(fx); } } } } int main() { int n;scanf("%d",&n); memset(par,-1,sizeof(par)); for(int i=0;i<n;i++) { scanf("%s",&t); build(); } pp(); printf("%d\n",ans); return 0; }