http://acm.hdu.edu.cn/showproblem.php?pid=1251
1 #include<stdio.h>
2 #include<string.h>
3 struct distree{
4 int n;
5 struct distree * child[26];
6 };
7 struct distree *root;
8 void Ins(char *ch)
9 {
10 int i;
11 struct distree *p,*newnode;
12 p = root;
13 for (;*ch;ch++)
14 {
15 if(p->child[*ch - 'a'])
16 {
17 p = p->child[*ch - 'a'];
18 p->n ++;
19 }
20 else
21 {
22 newnode = (struct distree *)malloc(sizeof(struct distree));
23 for (i=0;i<26;i++)
24 newnode->child[i] = 0;
25 p->child[*ch - 'a'] = newnode;
26 p = newnode;
27 p->n = 1;
28 }
29 }
30 }
31 int find(char *ch)
32 {
33 struct distree *p;
34 p = root;
35 for(;*ch;ch++)
36 {
37 if(p->child[*ch -'a'])
38 p = p->child[*ch - 'a'];
39 else
40 return 0;
41 }
42 return p->n;
43 }
44 int main()
45 {
46 int i;
47 char ch[11];
48 root = (struct distree *)malloc(sizeof(struct distree));
49 for(i=0;i<26;i++)
50 root->child[i] = 0;
51 root->n = 0;
52 while (gets(ch),strcmp(ch,""))
53 Ins(ch);
54 while (gets(ch))
55 printf("%d\n",find(ch));
56 }
http://acm.hdu.edu.cn/diy/contest_show.php?cid=2072密码
ruanyubin
5道字典树
posted on 2009-02-09 22:35
shǎ崽 阅读(713)
评论(1) 编辑 收藏 引用