HDU 1075--字典树

http://acm.hdu.edu.cn/showproblem.php?pid=1075

字典树,就是输入的字符处理比较恶心,还有应该注意的是避免前缀问题。。如:字典里有liwo,但是查找liw的时候应该是找不到的,不能单从NULL判断有没有找到,还要看那个节点是否有存字符串。。

代码:

复制代码
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 struct node{
 6     char a[25];
 7     node *next[26];
 8     node()
 9     {
10         a[0]='\0';
11         memset(next,0,sizeof(next));
12     }
13 };
14 node *root=new node;
15 void build(char *a,char *b)
16 {
17     node *p=root;
18     for(int i=0;b[i];i++)
19     {
20         int k=b[i]-'a';
21         if(p->next[k]==NULL)
22             p->next[k]=new node;
23         p=p->next[k];
24     }
25     strcpy(p->a,a);
26 }
27 node *Find(char *a)
28 {
29     node *p=root;
30     for(int i=0;a[i];i++)
31     {
32         int k=a[i]-'a';
33         if(p->next[k]==NULL)
34             return NULL;
35         p=p->next[k];
36     }
37     return p;
38 }
39 void print(char *s)
40 {
41     char ch[25];
42     int j=0;
43     for(int i=0;s[i];i++)
44     {
45         if(s[i]>='a'&&s[i]<='z')
46             ch[j++]=s[i];
47         else
48         {
49             if(j!=0)
50             {
51                 ch[j]='\0';
52                 j=0;
53                 node *q=Find(ch);
54                 if(q==NULL)
55                     printf("%s",ch);
56                 else
57                 {
58                     if(q->a[0]!='\0')
59                         printf("%s",q->a);
60                     else
61                         printf("%s",ch);
62                 }
63             }
64             printf("%c",s[i]);
65         }
66     }
67     puts("");
68 }
69 int main()
70 {
71     char str[25],a[25],b[25],s[3033];
72     while(~scanf("%s",a))
73     {
74         if(strcmp(a,"START")==0)
75             continue;
76         if(strcmp(a,"END")==0)
77         {
78             getchar();
79             while(gets(s))
80             {
81                 if(strcmp(s,"START")==0)
82                     continue;
83                 if(strcmp(s,"END")==0)
84                     break;
85                 print(s);
86             }
87             break;
88         }
89         scanf("%s",b);
90         build(a,b);
91     }
92     return 0;
93 }
复制代码

 

posted on 2013-02-05 14:35  acoderworld  阅读(144)  评论(0)    收藏  举报

努力加载评论中...
< 2025年7月 >
29 30 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9

导航

点击右上角即可分享
微信分享提示