Trie——理论知识

来源:互联网 发布:上瘾网络剧花絮视频 编辑:程序博客网 时间:2024/06/06 00:37

定义及用途


Trie树,字典树,又称单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计和排序大量的字符串(但不仅限于字符串)。


Trie的核心思想是空间换时间,利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的.




时间复杂度


Trie树时间复杂度:插入和查询时间复杂度都为 O(k) ,其中 k 为 key 的长度,与 Trie中保存了多少个元素无关。




基本性质


1)根节点不包含字符,除根节点意外每个节点只包含一个字符。
(2)从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。 
(3)每个节点的所有子节点包含的字符串各不相同。

























操作


1、插入


  假设存在字符串str,Trie树的根结点为root。i=0,p=root。


  1)取str[i],判断p->next[str[i]-97]是否为空,

 若为空,则建立结点temp,并将p->son[str[i]-97]指向temp,

然后p指向temp;

 若不为空,则p=p->son[str[i]-97];


  2)i++,继续取str[i],循环1)中的操作,直到遇到结束符'\0',

 此时将当前结点p中的 exist置为true。



2、查找


 
假设要查找的字符串为str,Trie树的根结点为root,i=0,p=root


 
1)取str[i],判断判断p->next[str[i]-97]是否为空,

  若为空,则返回false;

  若不为空,则p=p->next[str[i]-97],继续取字符。


  2)重复1)中的操作直到遇到结束符'\0',

  若当前结点p不为空并且 exist 为true,则返回true,

  否则返回false。



3、删除


  删除可以以递归的形式进行删除。





完整代码(c++)



#include <string>#include <cstring>#include <iostream>using namespace std;int n,m,ans=0,num=0,c,w;string s;struct trie{    int son[27];    bool ex;}p[100010];inline void add();inline void del(int pos,int sum,int len);inline bool ask();int main(){cin>>n;for(int i=1;i<=n;++i){cin>>s;add();}cin>>m;for(int i=1;i<=m;++i){cin>>c>>s;if(c==1)w=0,del(0,0,s.size());elsecout<<ask()<<endl;}return 0;}inline void del(int pos,int sum,int len){if(sum==len)return ;del(sum+1,p[pos].son[s[sum]-96],len);if(w==1)return ;else if(p[pos].ex==1)w=1;elsep[pos].son[s[sum]-96]=0;return ;}inline bool ask(){int len=s.size(),pos=0;for(int i=0;i<len;++i){if(p[pos].son[s[i]-96]!=0)pos=p[pos].son[s[i]-96];elsereturn 0;}return 1;}inline void add(){int len=s.size(),pos=0;for(int i=0;i<len;++i){if(p[pos].son[s[i]-96]!=0)pos=p[pos].son[s[i]-96];else{++num;p[pos].son[s[i]-96]=num;pos=num;}}p[pos].ex=1;return ;}




习题


 

模板题


hzwer【bzoj1174】[Balkan2007]Toponyms

http://hzwer.com/2448.html


洛谷P1666 【模板】前缀单词

https://www.luogu.org/problem/show?pid=1666


POJ 2418 Hardwood Species

http://poj.org/problem?id=2418
http://www.cnblogs.com/suncoolcat/archive/2013/09/01/3294108.html




进阶题目





hzwer 【小奇模拟赛】小奇的自动机

http://hzwer.com/7938.html 



hzwer 【bzoj1954】Pku3764 The xor-longest Path

http://hzwer.com/5632.html








原创粉丝点击