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;
}
浙公网安备 33010602011771号