swust oj 1100 最短的名字 (字典树)

来源:互联网 发布:阿里云认证 编辑:程序博客网 时间:2024/06/06 13:23
题目:在一个奇怪的村子中,很多人的名字都很长,比如aaaaa, bbb and abababab。
名字这么长,叫全名显然起来很不方便。所以村民之间一般只叫名字的前缀。比如叫'aaaaa'的时候可以只叫'aaa',因为没有第二个人名字的前三个字母是'aaa'。不过你不能叫'a',因为有两个人的名字都以'a'开头。村里的人都很聪明,他们总是用最短的称呼叫人。输入保证村里不会有一个人的名字是另外一个人名字的前缀(作为推论,任意两个人的名字都不会相同)。

如果村里的某个人要叫所有人的名字(包括他自己),他一共会说多少个字母?

将输入的字符按照字典树建树,每个节点的子树有26个,在建树的过程中按照字符移动成为根节点。

#include<stdio.h>#include<string.h>int countid;int ans;int cnt[1000005];int tree[1000005][26];void build(int id,char s[]){    int len=strlen(s);    for(int i=0;i<len;i++)    {        if(tree[id][s[i]-'a']==0)            tree[id][s[i]-'a']=++countid;        id=tree[id][s[i]-'a'];        cnt[id]++;    }}void dfs(int id,int deep){    if(cnt[id]==1)    {        ans+=deep;        return;    }    for(int i=0;i<26;i++)    {        if(tree[id][i]!=0)            dfs(tree[id][i],deep+1);    }}int main(){    int t;    char s[1000005];    int n;    scanf("%d",&t);    while(t--)    {        ans=0;        countid=0;        memset(cnt,0,sizeof(cnt));        memset(tree,0,sizeof(tree));        scanf("%d",&n);        while(n--)        {            scanf("%s",s);            build(0,s);        }        dfs(0,0);        printf("%d\n",ans);    }return 0;}


0 0
原创粉丝点击