您的位置:首页 > 理论基础 > 数据结构算法

hdu1251 统计难题 数据结构之Trie树

2012-09-13 21:33 519 查看
哈哈,第一次用Trie树,从网上找了个模板改了改,然后自己写了search()。

题目很简单,就不解释了。

#include<stdio.h>
#include <string.h>

const int sonnum=26, base='a';
struct Trie{
int num;  //记录有多少个单词能到达次,也即相同前缀的个位
//bool terminal; //判断是否是结束节点
struct Trie *son[sonnum];
Trie()
{
num=1;
// terminal=false;
memset(son,NULL,sizeof(son));
}
};

void Insert(Trie *root, char *s)
{
Trie *temp=root;
while(*s)
{
if(temp->son[*s-base]==NULL)   //不存在 则建立
temp->son[*s-base]=new Trie();//NewTrie();
else
{
temp->son[*s-base]->num++;
}
temp=temp->son[*s-base];
s++;
}
//temp->terminal=true;  //到达尾部,标记一个串
}

int search(Trie *root,char a[])
{
Trie *temp=root;
int i=0;
while(a[i])
{
if(temp->son[a[i]-base]!=NULL)
temp=temp->son[a[i]-base];
else return 0;
i++;
}
return temp->num;
}

int main()
{
char a[11];
Trie *root=new Trie();
while(gets(a))
{
if(a[0]=='\0')break;
Insert(root,a);
}
while(gets(a))
printf("%d\n",search(root,a));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: