HDU 1251 统计难题(字典树)

 

题目大意

 

给了很多单词,现在要统计以某个字符串为前缀的单词的数量

 

做法分析

 

直接建字典树,初始化出每个节点被覆盖的次数,然后对于每一个字符串,直接统计即可

 

参考代码

 

HDU 1251
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 struct Tire
 8 {
 9     struct Node
10     {
11         Node *next[26];
12         int cnt;
13         Node()
14         {
15             for(int i=0; i<26; i++) next[i]=NULL;
16             cnt=0;
17         }
18     };
19     Node *root;
20     Tire()
21     {
22         root=new Node();
23     }
24 
25     void Insert(char buff[])
26     {
27         Node *u=root;
28         for(int i=0; buff[i]; i++)
29         {
30             int v=buff[i]-'a';
31             if(u->next[v]==NULL) u->next[v]=new Node();
32             u=u->next[v];
33             u->cnt++;
34         }
35     }
36 
37     int Find(char buff[])
38     {
39         Node *u=root;
40         for(int i=0; buff[i]; i++)
41         {
42             int v=buff[i]-'a';
43             if(u->next[v]==NULL) return 0;
44             u=u->next[v];
45         }
46         return u->cnt;
47     }
48 
49     void Free(Node *u)
50     {
51         for(int i=0; i<26; i++)
52             if(u->next[i]!=NULL) Free(u->next[i]);
53         delete u;
54     }
55 } tree;
56 
57 char str[15];
58 
59 int main()
60 {
61     while(gets(str), strcmp(str, "")!=0) tree.Insert(str);
62     while(gets(str)) printf("%d\n", tree.Find(str));
63     tree.Free(tree.root);
64     return 0;
65 }

AC通道

HDU 1251 统计难题

原文地址:https://www.cnblogs.com/zhj5chengfeng/p/3021697.html