HDU 1251 裸的字典树、入门题

裸的字典树还是挺简单的、

四个基本操作建立、查找、插入、删除

建立新结点我是用的c++中 new操作、当然也可以用malloc,都方便

不过指针阿、地址阿、这其中关系什么的我貌似还不是很清楚阿、

因为刚开始我的头结点也是定义的指针、然后程序就炸了、我不清楚原因呢、

有待弄清楚、

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #include<cstring>
 6 typedef struct node
 7 {
 8     int cnt;
 9     struct node *next[26];
10     node()
11     {
12         cnt=0;
13         memset(next,0,sizeof(next));
14     }
15 }t;
16 node root;        //头结点 
17 void save(char *s)
18 {
19     int len=strlen(s);
20     if(len==0)    return;
21     node *p=&root;
22     node *tmp=NULL;
23     for(int i=0;i<len;++i){
24         if(p->next[s[i]-'a']==NULL){
25             tmp=new struct node;
26             p->next[s[i]-'a']=tmp;
27         }
28         p=p->next[s[i]-'a'];
29         p->cnt++;
30     }
31 }
32 void findtree(char *s)
33 {
34     struct node *p=&root;
35     int i,l=strlen(s);
36     for(int i=0;i<l;++i){
37         if(p->next[s[i]-'a']==NULL){
38             printf("0\n");
39             return;
40         }
41         p=p->next[s[i]-'a'];
42     }
43     printf("%d\n",p->cnt);
44     return;
45 }
46 int main()
47 {
48     char s[15];
49     while(gets(s)&&s[0]!=0)    save(s);
50     while(~scanf("%s",s))
51         findtree(s);
52     return 0;
53 }

 

posted @ 2016-04-05 11:52  我不萌、我要高冷  阅读(206)  评论(0编辑  收藏  举报