Codeforces Round #476 (Div. 2) [Thanks, Telegram!] E. Short Code(树上的启发式合并)

时间:2022-10-13 22:09:49
E. Short Code
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

Input

The first line contains a single integer nn (1n1051≤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.

Output

Print a single integer — the minimum possible total length of new variable names.

Examples
input
Copy
3
codeforces
codehorses
code
output
Copy
6
input
Copy
5
abba
abb
ab
aa
aacada
output
Copy
11
input
Copy
3
telegram
digital
resistance
output
Copy
3
Note

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;
}