标签:trie
代码:#include<cstdio>
#include<cstring>
#include<stdlib.h>
using namespace std;
struct Node
{
int cnt;
Node * next[26];
void init()
{
cnt=0;
for(int i=0; i<26; i++)
{
next[i]=NULL;
}
}
};
Node *P_root;
void Insert(char s[])
{
int len=strlen(s);
Node *p=P_root;
for(int i=0; i<len; i++)
{
int num=s[i]-'a';
if(p->next[num]==NULL)
{
p->next[num]=(Node *)malloc(sizeof(Node));
(*(p->next[num])).init();
}
p=p->next[num];
p->cnt++;
}
}
/*void Destroy(Node *p)
{
for(int i=0;i<26;i++)
{
if(p->next[i]!=NULL)
{
Destroy(p->next[i]);
}
}
free(p);
}*/
int Search(char s[])
{
int len=strlen(s);
Node *p=P_root;
for(int i=0;i<len;i++)
{
int num=s[i]-'a';
if(p->next[num]==NULL)
{
return 0;
}
p=p->next[num];
}
return p->cnt;
}
int main()
{
P_root=(Node *)malloc(sizeof(Node));
(*P_root).init();
char s[15];
while(gets(s)&&s[0]!=0)
Insert(s);
while(scanf("%s",s)!=EOF)
printf("%d\n",Search(s));
//Destroy(P_root);
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
hdu 1251 统计难题(给定字典单词,查询以某单词为前缀的单词的个数)
标签:trie
原文地址:http://blog.csdn.net/xky1306102chenhong/article/details/47418997