AcWing 835. Trie字符串统计

地址 https://www.acwing.com/problem/content/description/837/

目描述
维护一个字符串集合,支持两种操作:

“I x”向集合中插入一个字符串x;
“Q x”询问一个字符串在集合中出现了多少次。
共有N个操作,输入的字符串总长度不超过 105,字符串仅包含小写英文字母。

输入格式
第一行包含整数N,表示操作数。

接下来N行,每行包含一个操作指令,指令为”I x”或”Q x”中的一种。

输出格式
对于每个询问指令”Q x”,都要输出一个整数作为结果,表示x在集合中出现的次数。

每个结果占一行。

数据范围
1≤N≤2∗104

输入样例:
5
I abc
Q abc
Q ab
I ab
Q ab
输出样例:
1
0
1

算法1
根据trie树的意义 自己设计了一个结构体
每个节点额外增加一个当前字母是不是某一个字符串的结尾 另外根据本题题意又增加了一个元素,记录到此节点的字符串被insert了几次(也就是本题的答案)

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 
 5 
 6 using namespace std;
 7 
 8 /*
 9 5
10 I abc
11 Q abc
12 Q ab
13 I ab
14 Q ab
15 */
16 /*
17 1
18 0
19 1
20 */
21 
22 struct Node {
23     vector<struct Node*> next;
24     int isEnd;
25     int count;
26     Node() {
27         next = vector<struct Node*>(26, NULL);
28         isEnd = 0;
29         count = 0;
30     }
31 };
32 
33 struct Node root;
34 
35 void Insert(string& s)
36 {
37     struct Node* p = &root;
38     for (int i = 0; i < s.size(); i++) {
39         char c = s[i];
40         int idx = c - 'a';
41         if (p->next[idx] == NULL) {
42             struct Node* pp = new Node();
43             pp->count++;
44             p->next[idx] = pp;
45             p = pp;
46         }
47         else {
48             p = p->next[idx];
49             p->count++;
50         }
51     }
52     p->isEnd = 1;
53 }
54 
55 
56 void Query(string& s)
57 {
58     struct Node* p = &root;
59     for (int i = 0; i < s.size(); i++) {
60         char c = s[i]; int idx = c - 'a';
61         if (p->next[idx] == NULL) {
62             cout << 0 << endl; return;
63         }
64         else {
65             p = p->next[idx];
66         }
67     }
68 
69     if (p->isEnd == 1)
70         cout << p->count << endl;
71 
72     return;
73 }
74 
75 int main()
76 {
77     int n;
78     cin >> n;
79     while (n--) {
80         string s;
81         char QI;
82         cin >> QI >> s;
83 
84         if (QI == 'I') {
85             Insert(s);
86         }
87         else {
88             Query(s);
89         }
90     }
91 
92     return 0;
93 }
View Code

猜你喜欢

转载自www.cnblogs.com/itdef/p/11957610.html
今日推荐