这个是个trie树的超简单题了,要注意的是trie树中由于根中逻辑上没有元素,仅起一个引导搜索的作用,所以要比实际的字符串位置快了一步。
题目链接:http://poj.org/problem?id=2001
#include <stdio.h>
#include <string.h>
struct trie_node
{
int num;
trie_node* branch[26];
trie_node()
{
num = 0;
int i;
for(i = 0;i < 26;++i)
branch[i] = NULL;
}
};
struct trie
{
trie_node* root;
trie(){root = NULL;}
void insert(const char* word)
{
if(root == NULL)
root = new trie_node();
trie_node* cur = root;
while(*word)
{
int pos = *word - 'a';
if(cur->branch[pos] == NULL)
cur->branch[pos] = new trie_node();
++cur->branch[pos]->num;
cur = cur->branch[pos];
++word;
}
}
void prefix(const char* word)
{
trie_node* cur = root;
while(cur != NULL && *word)
{
if(cur->num == 1)
{
printf("\n");
return;
}
printf("%c",*word);
int pos = *word - 'a';
cur = cur->branch[pos];
++word;
}
printf("\n");
}
};
int main()
{
freopen("in.txt","r",stdin);
trie tree;
char strs[1000][21];
int i = 0;
while(scanf("%s",strs[i]) != EOF)
{
tree.insert(strs[i]);
++i;
}
int j = 0;
while(j < i)
{
printf("%s ",strs[j]);
tree.prefix(strs[j]);
++j;
}
return 0;
}