Shortest Names UVA

来源:互联网 发布:got7直播软件 编辑:程序博客网 时间:2024/06/06 03:04

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

其实是一个裸的字典树QAQ

#include<stdio.h>#include<stdlib.h>#include<string.h>using namespace std;struct aa{    int vistime;    aa* pos[26];    aa()    {        memset(pos,0,sizeof(pos));        vistime=0;    }}*head=NULL;int sum;void insertx(char *get){    int len=strlen(get);    struct aa *to=head;    for(int i=0; i<len; i++)    {        int x=get[i]-'a';        if(to->pos[x]==NULL)        {            to->pos[x]=(struct aa*)malloc(sizeof(struct aa));        }        to=to->pos[x];        to->vistime++;    }}void dfs(struct aa *now,int deep){    if(now==NULL)        return ;    if(now->vistime==1)    {        sum+=deep;        return ;    }    for(int i=0; i<26; i++)    {        if(now!=NULL)        {            dfs(now->pos[i],deep+1);            free(root->pos[i]);        }    }}void btree(struct aa *root){    if(root==NULL)        return;    for(int i=0; i<26; i++)    {        if(root->pos[i]!=NULL)            btree(root->pos[i]);    }}char get[10086];int main(){    int t;    scanf("%d",&t);    while(t--)    {        int n;        sum=0;        scanf("%d",&n);        head=(struct aa*)malloc(sizeof(aa));        while(n--)        {            scanf("%s",get);            insertx(get);        }        dfs(head,0);        btree(head);        printf("%d\n",sum);    }}



原创粉丝点击