Trie 字典树,hdu1251

参考博客:https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html

字典树就是单词树,顺着一条路径到达终止结点就形成一个单词,该单词的前缀包含在这条路径中。字典树的一般操作有insert单词和search前缀或者单词。

hdu1251字典树模板链接:http://icpc.njust.edu.cn/Problem/Hdu/1251/

代码如下:唯一要注意的地方就是读入数据,读入空行的时候gets函数读入的是NULL

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned int ui;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 #define pf printf
 7 #define mem(a,b) memset(a,b,sizeof(a))
 8 #define prime1 1e9+7
 9 #define prime2 1e9+9
10 #define pi 3.14159265
11 #define lson l,mid,rt<<1
12 #define rson mid+1,r,rt<<1|1
13 #define scand(x) scanf("%llf",&x) 
14 #define f(i,a,b) for(int i=a;i<=b;i++)
15 #define scan(a) scanf("%d",&a)
16 #define dbg(args) cout<<#args<<":"<<args<<endl;
17 #define inf 0x3f3f3f3f
18 const int maxn=1e6+10;
19 int n,m,t;
20 char s[maxn],s1[maxn];
21 int trie[maxn][26],sum[maxn];
22 int cnt=0;
23 void insert(char* s)
24 {
25     int rt=0;
26     int len=strlen(s);
27     f(i,0,len-1)
28     {
29         int c=s[i]-'a';
30         if(!trie[rt][c])trie[rt][c]=++cnt;
31         rt=trie[rt][c];
32         sum[rt]++;
33     }
34 }
35 int find(char* s)
36 {
37     int rt=0;
38     int len=strlen(s);
39     f(i,0,len-1)
40     {
41         int c=s[i]-'a';
42         if(!trie[rt][c])return 0;
43         rt=trie[rt][c];
44     }
45     return sum[rt];
46 }
47 int main()
48 {
49     //freopen("input.txt","r",stdin);
50     //freopen("output.txt","w",stdout);
51     std::ios::sync_with_stdio(false);
52     while(gets(s))
53     {
54         if(s[0]==NULL)break;//gets读入空行时会转化成NULL 
55         insert(s);
56     }
57     while(gets(s))
58     {
59         pf("%d\n",find(s));
60     }
61  } 

猜你喜欢

转载自www.cnblogs.com/randy-lo/p/12541655.html