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

題目:在一個奇怪的村子中,很多人的名字都很長,比如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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章