banana band bee absolute acm ba b band abc
2 3 1 0
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<limits.h>
typedef long long LL;
using namespace std;
typedef struct Trie{
int num;
Trie *next[26];
}Trie;
Trie root;
void buildtrie(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->num=1;
for(int j=0;j<26;j++)
q->next[j]=NULL;
p->next[id]=q;
p=p->next[id];
}
else//若存在则遍历
{
p->next[id]->num++;
p=p->next[id];
}
}
}
int find(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->num;
}
int main()
{
char str[15];
for(int i=0;i<26;i++)
root.next[i]=NULL;
while(gets(str)&&str[0]!='\0')
buildtrie(str);
memset(str,0,sizeof(str));
while(~scanf("%s",str))
{
int ans=find(str);
printf("%d\n",ans);
}
return 0;
}
原文:http://blog.csdn.net/u013582254/article/details/38853265