【典中典】Trie
AcWing 835. Trie字符串统计
#include <cstdio>
using namespace std;
const int N = 1e6 + 10;
int son[N][52], cnt[N], idx = 0;
inline void insert(char str[]) {
int u = 0;
for (int i = 0; str[i]; i++) {
int j = str[i] - 'a';
if (!son[u][j]) {
son[u][j] = ++idx;
}
u = son[u][j];
}
cnt[u]++;
}
inline int query(char str[]) {
int u = 0;
for (int i = 0; str[i]; i++) {
int j = str[i] - 'a';
if (!son[u][j]) {
return 0;
}
u = son[u][j];
}
return cnt[u];
}
int n;
char op, str[100];
int main() {
scanf("%d\n", &n);
while (n--) {
scanf("%c %s\n", &op, str);
if (op == 'I') {
insert(str);
} else {
printf("%d\n", query(str));
}
}
return 0;
}
Luogu P2580 于是他错误的点名开始了
#include <cstdio>
using namespace std;
const int N = 1e6 + 10;
int son[N][52], cnt[N], idx = 0;
inline void insert(char str[]) {
int u = 0;
for (int i = 0; str[i]; i++) {
int j = str[i] - 'a';
if (!son[u][j]) {
son[u][j] = ++idx;
}
u = son[u][j];
}
cnt[u]++;
}
inline int query(char str[]) {
int u = 0;
for (int i = 0; str[i]; i++) {
int j = str[i] - 'a';
if (!son[u][j]) {
return 0;
}
u = son[u][j];
}
return cnt[u];
}
int n, m;
char str[100];
int main() {
scanf("%d", &n);
while (n--) {
scanf("%s", str);
insert(str);
}
scanf("%d", &m);
while (m--) {
scanf("%s", str);
int result = query(str);
if (result == 0) {
puts("WRONG");
} else if (result == 1) {
puts("OK");
insert(str);
} else {
puts("REPEAT");
}
}
return 0;
}