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

hdu1251 统计难题 字典树

2015-10-18 11:02 561 查看
字典树模板题










#include<iostream>
#include<cstdio>
using namespace std;

struct point
{
point*  next[26];
int cot;   //count how many prefixes from root to current point.
point()   //constructor method, initialize 26 child of pointer
{
cot = 0;
memset(next,0,sizeof(next));
}
};

void insert(point *rt,char *s)
{
point p = rt;
int i=0;
int k;
while(s[i])
{
k = (s[i++]-'a');
if(p->next[k]==NULL)
{
p->next[k] = new point();
}
p->next[k]->cot++;
p = p->next;
}
return ;
}

int search(point *rt,char *s)
{
point p = rt;
int i = 0;
int k;
while(s[i])
{
k = s[i++]-'a';
if(p->next[k]==NULL) //the trie tree doesn't have the prefix
{
return 0;
}
}
return p->next[k]->cot;
}

int main()
{
point *rt = new point();
char s[25];
while(gets(s)!=NULL)
{
if(s[0]=='\0')
break;
cout<<s<<endl;
insert(rt,s);
}
while(cin>>s)
{
cout<<search(rt,s)<<endl;
}
return 0;
}
注意 要用c++交,不然MLE,不知道为什么
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 数据结构