0%

字典树

前置知识

字符串,图论基础

引入

trie-字典树,就是一棵可以拿来当字典用的树,它的思考和实现都非常简单。例如,helloherhershis 生成的字典树如下:

示例
示例

实现

Luogu P2580

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include "bits/stdc++.h"
using namespace std;
const int N=500010;
char s[60];
int n,m,ch[N][26],tag[N],tot=1;
int main(){
cin>>n;
for(int i=1;i<=n;++i){
scanf("%s",s+1);
int u=1;
for(int j=1;s[j];++j){
int c=s[j]-'a';
if(!ch[u][c])ch[u][c]=++tot;
u=ch[u][c];
}
tag[u]=1;
}
cin>>m;
while(m--){
scanf("%s",s+1);
int u=1;
for(int j=1;s[j];++j){
int c=s[j]-'a';
u=ch[u][c];
if(!u)break;
}
if(tag[u]==1){
tag[u]=2;
puts("OK");
} else if(tag[u]==2)puts("REPEAT");
else puts("WRONG");
}
return 0;
}