字符串之Trie树
https://segmentfault.com/a/1190000008877595?utm_source=tag-newest
-
Trie 树是一种以信息换时间的数据结构,其查询的复杂度为O(m)
-
Trie 的单数组实现能够达到最佳的性能,但是其空间利用率极低,是典型的以空间换时间的实现
-
Trie 树的哈希实现可以很好的平衡性能需求和空间开销,同时能够实现词典的实时更新
-
Trie 树的双数组实现基本可以达到单数组实现的性能,同时能够大幅降低空间开销;但是其难以做到词典的实时更新
-
对双数组 Trie 进行 tail 改进可以明显改善词典的构建速度,同时进一步减少空间开销
这篇文章写的非常好,对于Trie的应用场景miaohuihttps://www.cnblogs.com/justinh/p/7716421.html
https://blog.csdn.net/yu25_21_5/article/details/80954506
https://www.cnblogs.com/justinh/p/7716421.html
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cstring> 5 #include <cmath> 6 using namespace std; 7 string m,s[4001]; 8 const int maxnode=400000,tot_size=26; 9 int num,n,f[300001]; 10 long long ans=0; 11 struct Trie 12 { 13 int ch[maxnode][tot_size];//表示结点i的子节点j 14 int val[maxnode];//中间结点的附加信息 15 int tot;//结点总数 16 void build() 17 { 18 tot=1;//初始时只有一个根结点 19 memset(ch[0],0,sizeof(ch[0])); 20 } 21 int idx(char c) { return c - '0'; }//字符c的编号 22 void insert(string s)//插入字符串s,附加信息为v,注意v必须非0,因为0代表“非结点不是单词结点” 23 { 24 int u=0,n=s.length(); 25 int i; 26 for(i=0;i < n;i++) 27 { 28 int c=idx(s[i]); 29 if(!ch[u][c])//结点不存在 30 { 31 memset(ch[tot],0,sizeof(ch[tot])); 32 val[tot]=0;//中间结点的附加信息为0 33 ch[u][c]=tot++;//新建结点 34 } 35 u=ch[u][c];//往下走 36 } 37 val[u]++;//字符串的最后一个附加字符的附加信息,可作为结束标志 38 ans=max(ans,(long long)(val[u]*(i+1))); 39 } 40 // int find(string s,int now) 41 // { 42 // int u=0,n=s.length(),ans=0; 43 // for(int i=0;i < n;i++) 44 // { 45 // int c=idx(s[i]); 46 // if(!ch[u][c]) return ans; 47 // u=ch[u][c]; 48 // if(val[u]) ans=ans+1; 49 // } 50 // return ans; 51 // } 52 void clear(){ 53 tot = 1; 54 ans = 0; 55 memset(ch, 0, sizeof(ch)); 56 memset(val, 0, sizeof(val)); 57 } 58 59 } tree; 60 int main() 61 { 62 cin.sync_with_stdio(false); 63 int T; 64 cin>>T; 65 while(T--) 66 { 67 cin>>n; 68 ans=0; 69 tree.clear(); 70 // tree.build(); 71 string s; 72 for(int i=0;i<n;i++) 73 { 74 cin>>s; 75 tree.insert(s); 76 } 77 cout<<ans<<endl; 78 } 79 }

浙公网安备 33010602011771号