才了解了字典树这个东西,就练练手了
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int MAX=26;
typedef struct Trie
{
int count;
bool terminal;
Trie *son[MAX];
};
Trie *Create_New()
{
Trie *temp=new Trie;
temp->count=1; temp->terminal=false;
for(int i=0;i<MAX;i++)
temp->son[i]=NULL;
return temp;
}
void Insert(Trie *pnt,char *s,int len)
{
Trie *temp=pnt;
for(int i=0;i<len;i++)
{
if(temp->son[s[i]-'a']==NULL) temp->son[s[i]-'a']=Create_New();
else temp->son[s[i]-'a']->count++;
temp=temp->son[s[i]-'a']; //cout<<" dsf\n"<<endl;
}
temp->terminal=true;
}
Trie *Find(Trie *pnt,char *s,int len)
{
Trie *temp=pnt;
for(int i=0;i<len;i++)
{
if(temp->son[s[i]-'a']!=NULL)
temp=temp->son[s[i]-'a'];
else
return NULL;
}
return temp;
}
void Delete(Trie *pnt)
{
if(pnt!=NULL)
{
for(int i=0;i<MAX;i++)
if(pnt->son[i]!=NULL) Delete(pnt->son[i]);
delete pnt;
pnt=NULL;
}
}
int main()
{
char a[15],b[15];
Trie *pnt=Create_New();
while(gets(a) && a[0]!='\0')
{
int len=strlen(a);
Insert(pnt,a,len);
}
while(~scanf("%s",b))
{
Trie *p=pnt;
Trie *q=Find(p,b,strlen(b));
if(q!=NULL)
printf("%d\n",q->count);
else printf("0\n");
}
Delete(pnt);
return 0;
}