Trie树
又叫字典树、前缀树(Prefix Tree)、单词查找树 或 键树,是一种多叉树结构,可以高效存储和查找字符串集合的数据结构.
int son[N][26], cnt[N], idx;
// 0号点既是根节点,又是空节点
// son[][]存储树中每个节点的子节点
// cnt[]存储以每个节点结尾的单词数量
// 插入一个字符串
void insert(char *str)
{
int p = 0;
for (int i = 0; str[i]; i ++ )
{
int u = str[i] - 'a';
if (!son[p][u]) son[p][u] = ++ idx;
p = son[p][u];
}
cnt[p] ++ ;
}
// 查询字符串出现的次数
int query(char *str)
{
int p = 0;
for (int i = 0; str[i]; i ++ )
{
int u = str[i] - 'a';
if (!son[p][u]) return 0;
p = son[p][u];
}
return cnt[p];
}
//测试实例,Trie字符串统计
#include<iostream>
using namespace std;
const int N = 1e5+10;
int son[N][26],cent[N],idx;
char s[N];
void insert(char s[]){
int p = 0;
for(int i = 0;s[i];i++){
int u = s[i]-'a';
if(!son[p][u]) son[p][u] = ++idx;
p = son[p][u];
}
cent[p]++;
}
int query(char s[]){
int p = 0;
for(int i = 0;s[i];i++){
int u = s[i]-'a';
if(!son[p][u]) return 0;
p = son[p][u];
}
return cent[p];
}
int main(){
int num;
char c[2];
scanf("%d",&num);
while(num--){
scanf("%s%s",c,s);
if(c[0]=='I') insert(s);
if(c[0]=='Q') printf("%d\n",query(s));
}
return 0;
}
//实例测试,最大异或对
#include<iostream>
using namespace std;
const int N = 1e5+10 , M = 31*N;
int a[N];
int s[M][2],idex;
void insert(int x){
int p = 0;
for(int i = 30;i>=0;i--){
int u = x>>i&1;
if(!s[p][u]) s[p][u]= ++idex;
p = s[p][u];
}
}
int query(int x){
int p = 0,res = 0;
for(int i = 30;i>=0;i--){
int u = x>>i&1;
if(s[p][!u]) {
p = s[p][!u];
res = res*2+1;
}
else{
p = s[p][u];
res = res*2+0;
}
}
return res;
}
int main(){
int num,temp=0,res=0;
scanf("%d",&num);
for(int i = 0;i<num;i++){
scanf("%d",&a[i]);
insert(a[i]);
temp = query(a[i]);
res = res>=temp?res:temp;
}
printf("%d",res);
return 0;
}