字典树的应用

又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。

定义

 

1 typedef struct trie
2 {
3     trie *next[26];
4     int key;
5 };
6 
7 trie root;

字典树的建立插入

void insert(char *str)
{
    int len=strlen(str);
    trie *p=&root,*q;
    for(int i=0;i<len;i++)
    {
        int id=str[i]-'a';
        if(p->next[id]==NULL)
        {
            q=(trie *)malloc(sizeof(root));
            q->key=1;
            for(int j=0;j<26;j++)//制空下一结点所以字母表
            {
                q->next[j]=NULL;
            }
            p->next[id]=q;
            p=p->next[id];
        }
        else
        {
            p=p->next[id];
        }
    }
    if(p->key!=-1)
    {
        count++;
        p->key=-1;
    }
    else
        p->key=-1;
}

数据结构有关单词的搜索

★数据输入
输入第一行为一个正整数N ( N < =10000)。
接下来N行,每行开头是一个数字1或者2。
如果是1,后面会有一个单词,代表Winder在笔记本上记录下这个单词。每个单词仅
由小写的英文字母组成,且长度不超过8。
如果是2,则代表Winder想知道现在他已经背了几个不同的单词。
★数据输出
对于每个询问,输出一行一个整数,表示Winder已经背的不同的单词个数。
输入示例输出示例
10
1 winder
2

1 hello
1 what
1 holy
1 hello
2

1 acm
1 winder
2

输出:
145

1,建立字典树

2,每个单词的最后一个结点位置标记为-1;如果插入单词到最后一个节点值key不为-1,为多一个生词count++;

附代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 typedef struct trie
 5 {
 6     trie *next[26];
 7     int key;
 8 };
 9 
10 trie root;
11 
12 int count=0;
13 void insert(char *str)
14 {
15     int len=strlen(str);
16     trie *p=&root,*q;
17     for(int i=0;i<len;i++)
18     {
19         int id=str[i]-'a';
20         if(p->next[id]==NULL)
21         {
22             q=(trie *)malloc(sizeof(root));
23             q->key=1;
24             for(int j=0;j<26;j++)
25             {
26                 q->next[j]=NULL;
27             }
28             p->next[id]=q;
29             p=p->next[id];
30         }
31         else
32         {
33             p=p->next[id];
34         }
35     }
36     if(p->key!=-1)
37     {
38         count++;
39         p->key=-1;
40     }
41     else
42         p->key=-1;
43 }
44 
45 int main()
46 {
47     int n,x;
48     char str[9];
49     scanf("%d",&n);
50     for(int j=0;j<26;j++)
51         root.next[j]=NULL;
52     for(int i=0;i<n;i++)
53     {
54         scanf("%d",&x);
55         if(x==1)
56         {
57             scanf("%s",str);
58             insert(str);
59         }
60         else if(x==2)
61             printf("%d\n",count);
62     }
63     return 0;
64 }
View Code

 

posted @ 2013-11-03 21:53  陈泽泽  阅读(192)  评论(0编辑  收藏  举报