E. Short Code
Arkady's code contains n
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 a
is a prefix of a string b if you can delete some (possibly none) characters from the end of b and obtain a.
Please find this minimum possible total length of new names.
The first line contains a single integer n
) — the number of variables.
The next n
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 105. 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.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+10;
char buf[N];
struct Trie{
int nxt[N][26],dep[N],tot;
multiset<int> st[N];
void init(){
memset(nxt,0,sizeof(nxt));
dep[tot=1]=0;
}
void add(const string &str){
int now=1;
for(int i=0;i<str.size();i++){
if(!nxt[now][str[i]-'a'])
dep[nxt[now][str[i]-'a']=++tot]=dep[now]+1;
now=nxt[now][str[i]-'a'];
}
//cout<<now<<endl;
st[now].insert(dep[now]);
}
void dfs(int u=1){
int emp=(u>1&&st[u].empty());
for(int i=0;i<26;i++){
int v=nxt[u][i];
if(!v)continue;
dfs(v);
for(auto &t:st[v])
st[u].insert(t);
st[v].clear();
}
if(emp){
auto it=--st[u].end();
//cout<<*it<<endl;
st[u].erase(--st[u].end());
st[u].insert(dep[u]);
//cout<<u<<" "<<st[u].size()<<endl;
}
}
}trie;
int main(){
int n;
//freopen("in.txt","r",stdin);
scanf("%d",&n);
trie.init();
for(int i=1;i<=n;i++){
scanf("%s",buf);
trie.add(buf);
}
trie.dfs();
ll res=0;
for(auto &t:trie.st[1])
res+=t;
cout<<res<<endl;
}