字典树
字典树
查找一个字符串是否在「字典」中出现过
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
struct trie
{
int nex[100000][26], tot = 0;
bool exist[100000]; // 该结点结尾的字符串是否存在
void insert(string s)
{
int p = 0;
for (int i = 0; i < s.size(); i++)
{
int c = s[i] - 'a';
if (!nex[p][c])
nex[p][c] = ++tot; // 如果没有,就添加结点
p = nex[p][c];
}
exist[p] = 1;
}
bool query(string s)
{ // 查找字符串
int p = 0;
for (int i = 0; i < s.size(); i++)
{
int c = s[i] - 'a';
if (!nex[p][c])
return false;
p = nex[p][c];
}
return exist[p];
}
};
01字典树(异或)
最大异或和
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
struct trie
{
int nex[31 * 100000][2], tot = 0;
void insert(int x)
{
int p = 0;
for (int i = 30; i >= 0; i--)
{
int ch = (x >> i) & 1;
if (!nex[p][ch])
nex[p][ch] = ++tot; // 如果没有,就添加结点
p = nex[p][ch];
}
}
int query(int x)
{ // 查找字符串
int p = 0, res = 0;
for (int i = 30; i >= 0; i--)
{
int ch = (x >> i) & 1;
if (nex[p][ch ^ 1])
{
res += 1 << i;
p = nex[p][ch ^ 1];
}
else
p = nex[p][ch];
}
return res;
}
};
字典树
http://xiaowhang.github.io/archives/4003859050/