您的位置:首页 > 其它

hdu 1251 统计难题 字典树

2014-03-17 15:25 183 查看
trie树,指针模式更优雅

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

struct node{
int cnt;
node *childs[26];
node(){
cnt=0;
for(int i=0;i<26;i++)
childs[i]=NULL;
}
};
node *rt=new node();
node *cur,*next;

void insert(char *str){
cur=rt;
int len=strlen(str),t;
for(int i=0;i<len;i++){
t=str[i]-'a';
if(cur->childs[t]==NULL){
next=new node();
cur->childs[t]=next;
}
else{
next=cur->childs[t];
}
next->cnt++;
cur=next;
}
}
int search(char *str){
cur=rt;
int len=strlen(str),t;
for(int i=0;i<len;i++){
t=str[i]-'a';
if(cur->childs[t]==NULL)
return 0;
cur=cur->childs[t];
}
return cur->cnt;
}
int main(){
char str[20];
while(gets(str)&&str[0])
insert(str);
while(gets(str))
printf("%d\n",search(str));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: