HDU-1251(字典树<Tire>入门)

来源:互联网 发布:淘宝助理for mac 编辑:程序博客网 时间:2024/05/29 17:09

我随便一写就能过?这也太神奇了吧?

呵呵,,其实字典树简单的实现还是很简单的.首先建立一个结构体,结构体必须能够模拟26个字母,所以,自然想到了就是让每个结构体出来26个尾巴,然后26个尾巴每个又能生成26个尾巴,

然后呢,每个尾巴的名字就叫那个字母,而且你每次顺着尾巴走一遭就加1,这样就可以求出来了你询问的单词一共出现了多少次了,,,但是说实话,,代码敲的太丑了,毕竟是自己胡乱捣鼓出来的,,下面的我将继续改进.嘿嘿,贴出来.

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <math.h>struct Tire{struct Tire *child[26];int n;};Tire *root;const int st='a';void init(Tire *t){for(int i=0;i<26;i++){t->child[i]=NULL;}t->n=0;}void Insert(char *s){struct Tire *t,*current;t=root;int n=strlen(s);for(int i=0;i<n;i++){if(!t->child[s[i]-st]){current=(struct Tire *)malloc(sizeof(struct Tire));t->child[s[i]-st]=current;t=current;init(t);current->n=1;}else{t=t->child[s[i]-st];t->n++;}}}int search(char *s){Tire *t;t=root;int ans;int n=strlen(s);for(int i=0;i<n;i++){if(t->child[s[i]-st]==0)return 0;else{t=t->child[s[i]-st];ans=t->n;}}return ans;}int main(){char s[11];root=(Tire *)malloc(sizeof(Tire));init(root);while(gets(s)){if(strlen(s)==0)break;Insert(s);}while(scanf("%s",s)!=EOF){printf("%d\n",search(s));}return 0;}


上面的代码有点冗杂,下面是我修改的嘿嘿.

大家给看看吧.

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <math.h>struct T{T *ch[26];int n;}*root;int st='a';void init(T *t){memset(t->ch,0,sizeof(t->ch));t->n=0;}void Insert(char *s){T *t,*newnode;t=root;int n=strlen(s);for(int i=0;i<n;i++){if(t->ch[s[i]-st]==0){newnode=new T;init(newnode);t->ch[s[i]-st]=newnode;t=newnode;t->n=1;}else{t=t->ch[s[i]-st];t->n++;}}}int find(char *s){T *t;t=root;int n=strlen(s);for(int i=0;i<n;i++){if(t->ch[s[i]-st]==0)return 0;else{t=t->ch[s[i]-st];}}return t->n;}int main(){char s[11];root=new T;init(root);while(gets(s)){if(strlen(s)==0)break;Insert(s);}while(gets(s)){printf("%d\n",find(s));}return 0;}


 

原创粉丝点击