您的位置:首页 > 其它

第十二章Trie树(字典树)解决HDU1251

2012-04-19 17:05 218 查看
http://acm.hdu.edu.cn/showproblem.php?pid=1251

#include <iostream>
using namespace std;

struct TrieNode
{
TrieNode *children[26];
bool flag;
int cnt;//前缀数目
};

void InitTrieNode(TrieNode *tn)
{
if(!tn)
{
exit(1);
}
for(int i=0;i<26;i++)
{
(tn->children)[i]=NULL;
}
tn->flag=false;
tn->cnt=0;
}

//把长度为n的字符串a插入Trie树
void TrieTreeInsert(TrieNode **root,char *a,int n)
{
if(!(*root))
{
*root=new TrieNode;
InitTrieNode(*root);
}
TrieNode *tn=*root;

for(int i=0;i<n;i++)
{
TrieNode *child=(tn->children)[a[i]-'a'];
if(!child)
{
child=new TrieNode;
InitTrieNode(child);
(tn->children)[a[i]-'a']=child;
}
if(child->flag==false)
{
child->flag=true;
child->cnt++;
}
else
{
child->cnt++;
}
tn=child;
}
}

//统计以字符串b为前缀的单词数量
int Count(TrieNode *root,char *b,int n)
{
int cnt=0;
if(root)
{
TrieNode *tn=root;
for(int i=0;i<n;i++)
{
TrieNode *child=(tn->children)[b[i]-'a'];
if(child)
{
tn=child;
}
else
{
tn=NULL;
break;
}
}
if(tn!=root && tn!=NULL)
{
cnt=tn->cnt;
}
}
return cnt;
}

int main()
{
char a[10];
TrieNode *root=NULL;
while(gets(a))
{
int len=strlen(a);
if(len==0)
{
break;
}
TrieTreeInsert(&root,a,len);
}

char b[10];
while(gets(b))
{
int len=strlen(b);
cout<<Count(root,b,len)<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: