HDU 1251 统计难题(字典树计算前缀数量)

时间:2023-03-09 03:18:56
HDU 1251 统计难题(字典树计算前缀数量)

  字典树应用,每个节点上对应的cnt是以它为前缀的单词的数量

#include<stdio.h>
#include<string.h>
struct trie
{
int cnt;
trie *next[];
};
trie *root=new trie;
void insert(char ch[])
{
trie *p=root,*newnode;
for(int i=; ch[i]!='\0'; i++)
{
if(p->next[ch[i]-'a']==)
{
newnode=new trie;
for(int j=; j!=; j++)
{
newnode->next[j]=NULL;
}
newnode->cnt=;
p->next[ch[i]-'a']=newnode;
p=newnode;
}
else
{
p=p->next[ch[i]-'a'];
p->cnt++;
}
}
}
int find(char ch[])
{
trie *p=root;
for(int i=; ch[i]!='\0'; i++)
{
if(p->next[ch[i]-'a']!=NULL)
p=p->next[ch[i]-'a'];
else
return ;
}
return p->cnt;
}
int main()
{
char ch[];
for(int i=; i!=; i++)
{
root->next[i]=NULL;
}
root->cnt=;
while(gets(ch)) //±ØÐëÓÃgets
{
if(!strcmp(ch,"")) break;
insert(ch);
}
while(scanf("%s",ch)!=EOF)
{
printf("%d\n",find(ch));
}
return ;
}