您的位置:首页 > 其它

字典树模板

2017-07-31 15:28 330 查看


字典树

 

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

//字典树模板
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#define MAX 26
using namespace std;

typedef struct TrieNode
{
bool isStr;                          //标记该节点处是否构成单词
struct TrieNode *next[MAX];          //儿子分支
}Trie;

//建树
void insert(Trie *root, const char *s)
{
if(root==NULL || *s=='\0')
return;
Trie *p = root;
p->isStr = false;
while(*s!='\0')
{

if(p->next[*s-'a']==NULL)      //不在树中
{
Trie *temp = (Trie *)malloc(sizeof(Trie));
temp->isStr = false;
for(int i=0; i<MAX; i++)
temp->next[i] = NULL;
p->next[*s - 'a'] = temp;
p = temp;
}
else
{
p = p->next[*s - 'a'];
}
s++;
}
p->isStr = true;            //最末尾标记为有这个单词
}

//查询
bool reach(Trie *root, char *s)
{
Trie *q = root;
while(q!=NULL && *s!='\0')
{
q = q->next[*s-'a'];
s++;
}
if(q!=NULL && q->isStr)
return true;
return false;
}

//释放空间
void del(Trie *root)
{
if(root!=NULL)
{
for(int i=0; i<MAX; i++)
{
if(root->next[i]!=NULL)
del(root->next[i]);
}
free(root);
}
}

int main()
{
int n;
Trie *t = (Trie *)malloc(sizeof(Trie));
for(int i=0; i<MAX; i++)
t->next[i] = NULL;
scanf("%d", &n);
//建立字典树
for(int i=0; i<n; i++)
{
char s[105];
scanf("%s", s);
insert(t, s);
}

int m;
scanf("%d", &m);
//m次查找
while(m--)
{
char s[105];
scanf("%s", s);
if(reach(t, s))
printf("%s 存在\n", s);
else
printf("%s 不存在\n", s);
}
del(t);              //释放空间
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM