关于 Trie
【Trie 是什么】
Trie,字典树,存储字符串的树形结构。
【Trie 的作用】
Trie 可以高效地查询一个字符串出现的次数。
【Trie 的实现】
Trie 包含:
-
布尔数组 tr,其中
tr[i][j]=true 表示i 号结点有j 号字符的儿子。 -
数组
cnt ,cnt[i] 记录 以i 号结点结尾的字符串个数。
初始只有一个根节点。
每插入一个字符串,都把它的字符遍历一遍。
当遍历到字符
若有,
否则给
遍历结束后,给最后结点的
查询进行类似操作,每次看看当前结点有没有对应字符的儿子。
若有,切换到这个儿子上;
若没有,说明没有这个字符串。
遍历结束后,返回当前结点的
显然时间复杂度是
【Code】
板子题:P2580 于是他错误的点名开始了
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int n;
char s[60];
int tot = 0;
int tr[1000005][50];
int ed[1000005] = {};
int fnd[1000005] = {};
void add(char *s) {
int len = strlen(s);
int u = 1;
for (int i = 0; i < len; i++) {
int c = s[i] - 'a';
if (!tr[u][c])
tr[u][c] = ++tot;
u = tr[u][c];
}
ed[u]++;
}
int query(char *s) {
int len = strlen(s), u = 1;
for (int i = 0; i < len; i++) {
int c = s[i] - 'a';
if (tr[u][c] == 0)
return 0;
u = tr[u][c];
}
if (fnd[u])
return 1;
fnd[u]++;
return 2;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
scanf("%s", &s);
add(s);
}
int m;
cin >> m;
for (int i = 1; i <= m; i++) {
scanf("%s", s);
int tmp = query(s);
if (tmp == 0)
cout << "WRONG" << endl;
else if (tmp == 1)
cout << "REPEAT" << endl;
else
cout << "OK" << endl;
}
return 0;
}