代码如下
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
using namespace std;
char a[2001];
char b[500001][20];
char c[1001];
int f1;
struct trie
{
struct trie *next[26];
int flag;
int number;
};
int cmp(const void *a,const void *b)
{
return strcmp((char *)a,(char *)b);
}
trie *h=NULL;
trie *init()
{
trie *tmp=(trie *)malloc(sizeof(trie));
for(int i=0;i<26;i++)
{
tmp->next[i]=NULL;
}
tmp->flag=0;
tmp->number=0;
return tmp;
}
void in(char *s,trie *tmp)
{
int l=strlen(s);
for(int i=0;i<l;i++)
{
int tt=s[i]-'a';
if(tmp->next[tt]==NULL)
{
tmp->next[tt]=init();
tmp=tmp->next[tt];
tmp->number+=1;
}
else
{
tmp=tmp->next[tt];
tmp->number+=1;
}
}
}
void delet(trie *tmp)
{
for(int i=0;i<26;i++)
{
if(tmp->next[i]!=NULL)
{
delet(tmp->next[i]);
}
}
free(tmp);
}
int quiry(char *s,trie *tmp)
{
int sum=0;
int l=strlen(s);
for(int i=0;i<l;i++)
{
int tt=s[i]-'a';
if(tmp->flag==1)
{
f1=1;
}
if(tmp->next[tt]==NULL)
{
return 0;
}
else
tmp=tmp->next[tt];
}
return tmp->number;
}
int main()
{
int i=0;
int j,k,n,m,l;
while(gets(a)&&a[0])
{
strcpy(b[i],a);
i++;
}
int cnt=i;
qsort(b,cnt,sizeof(b[0]),cmp);
trie *h=NULL;
h=init();
for(i=0;i<cnt;i++)
{
in(b[i],h);
}
while(gets(c))
{
printf("%d\n",quiry(c,h));
}
delet(h);
return 0;
}