字典树
#include <iostream>
#include <vector>
using namespace std;
const int N = 1e5 + 10;
int son[N][26], cnt[N], idx;//下标是0的点,即是空节点,又是根节点
char str[N];
void insert(char str[])//存储操作
{
int p = 0;//初始化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];//将p值向下传递
}
cnt[p] ++;//以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];
}
int main()
{
int n;
cin >> n;
while(n --)
{
char op[2];
cin >> op >> str;
if(op[0] == 'I') insert(str);
else cout << query(str) << endl;
}
}
最大异或对
#include <bits/stdc++.h>
using namespace std;
const int N = 100010, M = 31 * N;
int a[N];
int son[M][2], idx;
int n;
void insert(int x)
{
int p = 0;
for(int i = 30; i >= 0; i --)
{
int u = x >> i & 1;
if(!son[p][u]) son[p][u] = ++ idx;
p = son[p][u];
}
}
int query(int x)
{
int p = 0, res = 0;
for(int i = 30; i >= 0; i --)
{
int u = x >> i & 1;
if(son[p][!u])
{
p = son[p][!u];
res = res * 2 + !u;
}
else{
p = son[p][u];
res = res * 2 + u;
}
}
return res;
}
int main()
{
scanf("%d", &n);
for(int i = 0; i <n; i ++) scanf("%d", &a[i]);
int res = 0;
for(int i = 0; i < n; i ++)
{
insert(a[i]);
int t = query(a[i]);
res = max(res, a[i] ^ t);
}
printf("%d\n", res);
}
牛异或(前缀和,字典树)
输入:
5
1
0
5
4
2
输出:
6 4 5
#include <bits/stdc++.h>
using namespace std;
const int N = 100010, M = 21 * N;
int a[N];
int son[M][2], idx;
int n;
int id[M];
void insert(int x, int ix)
{
int p = 0;
for(int i = 20; i >= 0; i --)
{
int u = x >> i & 1;
if(!son[p][u]) son[p][u] = ++ idx;
p = son[p][u];
}
id[p] = ix;
}
int query(int x)
{
int p = 0;
for(int i = 20; i >= 0; i --)
{
int u = x >> i & 1;
if(son[p][!u])
{
p = son[p][!u];
}
else{
p = son[p][u];
}
}
return id[p];
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i ++)
{
cin >> a[i];
a[i] = a[i] ^ a[i - 1];
}
insert(a[0], 0);
int res = -1, l, r;
for(int i = 1; i <= n; i ++)
{
int k = query(a[i]);
int t = a[i] ^ a[k];
if (t > res) res = t, l = k + 1, r = i;
insert(a[i], i);
}
cout << res << ' ' << l << ' ' << r << endl;
}