UVA 12506 Shortest Names

来源:互联网 发布:linux 查看自启动服务 编辑:程序博客网 时间:2024/06/05 23:59

In a strange village, people have very long names. For example: aaaaa, bbb and abababab. You see, it’s very inconvenient to call a person, so people invented a good way: just call a prefix of the names. For example, if you want to call ‘aaaaa’, you can call ‘aaa’, because no other names start with ‘aaa’. However, you can’t call ‘a’, because two people’s names start with ‘a’. The people in the village are smart enough to always call the shortest possible prefix. It is guaranteed that no name is a prefix of another name (as a result, no two names can be equal). If someone in the village wants to call every person (including himself/herself) in the village exactly once, how many characters will he/she use?
Input The first line contains T (T ≤ 10), the number of test cases. Each test case begins with a line of one integer n (1 ≤ n ≤ 1000), the number of people in the village. Each of the following n lines contains a string consisting of lowercase letters, representing the name of a person. The sum of lengths of all the names in a test case does not exceed 1,000,000.
Output
For each test case, print the total number of characters needed.


Sample Input
1 3

aaaaa

bbb

abababab


Sample Output


5

比赛的时候队友做的,,一直没想出来是用字典树,还以为是KMP啥的,后来看了题解才想起来是字典树的一个模板题,还是自己太菜了。。

每遍历一种情况,总和加上遍历的深度,就是所有字符串的前缀。。

感觉寒假的数据结构都白学了。。。T T

#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int N=1123456;char s[N];int ans;struct Trie{    int value;    Trie *child[30];    Trie()    {        value=0;        memset(child,NULL,sizeof(child));    }}*root;void Insert(char *s){    Trie *x=root;    int i;    for(i=0;s[i];i++)    {        int pos=s[i]-'a';        if(x->child[pos]==NULL)        {            x->child[pos]=new Trie;        }        x=x->child[pos];        x->value++;    }}void DFS(Trie *x,int level){    if(x==NULL) return;    if(x->value==1)    {        ans+=level;        return ;    }    int i;    for(i=0;i<=25;i++)    {        if(x->child[i]!=NULL)        {            DFS(x->child[i],level+1);        }    }}int main(){    int t;    scanf("%d",&t);    while(t--)    {        int n;        scanf("%d",&n);        ans=0;        root=new Trie;        int i;        for(i=0;i<=n-1;i++)        {            scanf("%s",s);            Insert(s);        }        DFS(root,0);        printf("%d\n",ans);    }    return 0;}