代码:
#include <stdio.h>
#define MAX 26
typedef struct TrieNode
{
int nCount;
struct TrieNode *next[MAX];
}TrieNode;
TrieNode Memory[1000000];
int allocp = 0;
TrieNode *CreateTrieNode()
{
int i;
TrieNode *p;
p = &Memory[allocp++];
p->nCount = 1;
for(i = 0 ; i < MAX ; i++)
{
p->next[i] = NULL;
}
return p;
}
void InsertTrie(TrieNode **pRoot , char *s){
int i , k;
TrieNode *p;
if(!(p = *pRoot))
{
p = *pRoot = CreateTrieNode();
}
i = 0;
while(s[i])
{
k = s[i++] - ‘a‘;
if(p->next[k])
p->next[k]->nCount++;
else
p->next[k] = CreateTrieNode();
p = p->next[k];
}
}
int SearchTrie(TrieNode **pRoot , char *s)
{
TrieNode *p;
int i , k;
if(!(p = *pRoot))
{
return 0;
}
i = 0;
while(s[i])
{
k = s[i++] - ‘a‘;
if(p->next[k] == NULL)
return 0;
p = p->next[k];
}
return p->nCount;
}
int main()
{
char a[11];
TrieNode *root=NULL;
while(gets(a)&&a[0])
{
CreateTrieNode();
InsertTrie(&root,a);
}
while(gets(a))
{
int ans=SearchTrie(&root , a);
printf("%d\n",ans);
}
return 0;
}
hdoj 1251 字典树