首页 > 其他 > 详细

【模板】 字典树

时间:2019-08-22 00:40:41      阅读:115      评论:0      收藏:0      [点我收藏+]
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 struct node{
 6     int cnt;  //记录出现次数
 7     int nex[30];//该节点下一个儿子的节点
 8 }trie[400500];
 9 char s1[105],s2[105];
10 int tot=1;//也可以0
11 void build(char* s){
12     int len=strlen(s);
13     int root=0;
14     for(int i=0;i<len;++i){
15         int id=s[i]-a;
16         if(trie[root].nex[id]==0) trie[root].nex[id]=++tot;
17         root=trie[root].nex[id];
18         ++trie[root].cnt;
19     }
20 }
21 int query(char* s){
22     int len=strlen(s);
23     int root=0;
24     for(int i=0;i<len;++i){
25         int id=s[i]-a;
26         if(!trie[root].nex[id]) return 0;
27         root=trie[root].nex[id];
28     }
29     return trie[root].cnt;
30 }
31 int main(){
32     while(gets(s1)){
33         int len=strlen(s1);
34         if(!len) break;
35         build(s1);
36     }
37     while(gets(s2)){
38         int u=query(s2);
39         printf("%d\n",u);
40     }
41     return 0;
42 }
43 //hdu1251
44 //https://vjudge.net/contest/281068#problem/C
45 //用gets不用scanf是因为读取字符串时,gets会舍弃回车,但scanf不会。
46 //https://www.cnblogs.com/hlongch/p/5742477.html

 

【模板】 字典树

原文:https://www.cnblogs.com/xiaobuxie/p/11391852.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!