pku 2001 Shortest Prefixes

//简单字典树,520K,16MS
#include <stdio.h>
#include <string.h>

#define MAXL 1001
#define MAXLEN 22

typedef struct TNode
{
    TNode()
    {
        cnt=0;
        memset(next,0,sizeof(next));
    }
    int cnt;
    TNode *next[26];
}*Trie;

char word[MAXL][MAXLEN];

void insert(Trie T,char *str)
{
    int i;
    while(*str)
    {
        i=*str-'a';
        if(!T->next[i]) T->next[i]=new TNode;
        T=T->next[i];
        T->cnt++;
        str++;
    }
}

void query(Trie T,char *str)
{
    int i,j=0;
    while(str[j])
    {
        i=str[j]-'a';
        T=T->next[i];
        if( T->cnt < 2)
        {
            str[j+1]=0;
            printf("%s\n",str);
            return;
        }
        j++;
    }
    printf("%s\n",str);
}

int main()
{
    int n=0,i;
    Trie tree=new TNode;
    while(scanf("%s",word[n])!=EOF)
    {
        insert(tree,word[n]);
        n++;
    }
    for(i=0;i<n;i++)
    {
        printf("%s ",word[i]);
        query(tree,word[i]);
    }
    return 0;
}

posted @ 2010-08-25 23:39  菜到不得鸟  阅读(113)  评论(0)    收藏  举报