这是一道入门字典树!
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
struct trie
{
int v;
trie *next[26];
} root;
void creattrie(char *str)
{
int len=strlen(str);
trie *p=&root,*q;
for(int i=0; i<len; i++)
{
int id=str[i]-'a';
if(p->next[id]==NULL)
{
q=(trie *)malloc(sizeof(root));
q->v=1;
for(int j=0; j<26; j++)
q->next[j]=NULL;
p->next[id]=q;
p=p->next[id];
}
else
{
p->next[id]->v++;
p=p->next[id];
}
}
}
int findtrie(char *str)
{
int len=strlen(str);
trie *p=&root;
for(int i=0; i<len; i++)
{
int id=str[i]-'a';
p=p->next[id];
if(p==NULL)
return 0;
}
return p->v;
}
int main()
{
char str[15];
int i;
for(i=0; i<26; i++)
root.next[i]=NULL;
while(gets(str)&&(str[0]!='\0'))
creattrie(str);
memset(str,0,sizeof(str));
while(scanf("%s",str)!=EOF)
{
int ans=findtrie(str);
printf("%d\n",ans);
}
return 0;
}