字典树
字典树
什么是字典树?
图中就是一个字典树,树中的点不存储信息,字符由边存储,每一条从根节点
容易发现
- 共享前缀:具有相同前缀的字符串共享存储路径。
- 空间换时间:为每一位的每一种可能字符提供完整的存储空间,使得查询效率仅与查询字符串长度相关,复杂度
O(L) 。
而字典树最重要的两个代码便是:
1. 插入
代码:
int trie[N][30];//字典树,其中第一维表示父亲节点,第二维表示字符编号
int tot;//存储字符编号
bool ie[N];//结尾节点
void insertTrie(const string &s){
int p = 0; //p从根节点开始
int len = s.size();
for(int i = 0; i < len; i ++){
int x = s[i] - 'a' + 1;
if(!trie[p][x]) trie[p][x] = ++tot;//不存在则新建
p = trie[p][x];
}
ie[p] = 1;//标记结尾
}
2. 查询
代码:
bool ask(const string &s){
int p = 0;
int len = s.size();
for(int i = 0; i < len; i ++){
int x = s[i] - 'a' + 1;
if(!trie[p][x]) return false;
p = trie[p][x];
ans += ie[p];
}
return ie[p];
}
既然字典树有这样的性质,那么有人
字典树该怎么应用?
1.统计前缀
:::info[题目大意] 统计所有以指定前缀开头的字符串数量。 ::: :::warning[题目思路] 前缀信息统计利用Trie。将结尾标记改为结尾计数,最后累加即可 ::: :::success[ACcode]
#include<bits/stdc++.h>
using namespace std;
const int N = 1e2 + 5;
int n, m;
int trie[N][20], tot;
bool ie[N];
void insertTrie(const string &s){
int p = 0;
int len = s.size();
for(int i = 0; i < len; i ++){
int x = s[i] - 'a' + 1;
if(!trie[p][x]) trie[p][x] = tot++;
p = trie[p][x];
}
ie[p]++;
}
int ask(const string &s){
int p = 0, ans = 0;
int len = s.size();
for(int i = 0; i < len; i ++){
int x = s[i] - 'a';
if(!trie[p][x]) return len;
p = trie[p][x];
ans += ie[p];
}
return len;
}
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i ++){
string s; cin >> s;
insertTrie(s);
}
for(int i = 1; i <= m; i ++){
string s; cin >> s;
cout << ask(s) << '/n';
}
return 0;
}
:::
2.求异或最值
如果你和我一样是蒟蒻,建议点开下面的折叠框看看,大佬可以直接跳过。
::::info[什么是异或?//]
异或是一种位运算,运算方式是:两个二进制位相同为0,相异为1。 :::info[如果你连位运算都不知道,可以看看这里] 在计算机中,所有数字都是以二进制进行存储的。位运算就是直接对数字的二进制位进行操作,且操作方式十分便捷。
实际应用中\tiny{(比如你要卡时间)} ,有些位运算可以代替其他较慢的方式。 ::: :::: 根据异或的定义,我们发现:求异或最大值时,我们可以用二进制字典树存储每个数字,每次尽量选择不一样的数字,就可以求出异或最大值。
例
:::info[题目大意] 给定整数数组,选取两个数,使它们的异或结果最大。 ::: :::warning[题目思路] 上面已经讲过了,可以仔细看看。 ::: :::success[ACcode]
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5 + 5;
int trie[N][2], tot, ans;
void insertTrie(int x){
int p = 0;
for(int i = ans; i >= 0; --i){
int ym = (x >> i) & 1;
if(trie[p][ym]) trie[p][ym] = ++tot;
p = trie[p][ym];
}
return p;
}
int ask(int x){
int p = 0, num = 0;
for(int i = ans; i >= 0; i --){
int ym = (x >> i) & 1;
ym ^= 1;
if(trie[p][ym]) num = (1 << i);
else ym ^= 1;
p = trie[p][ym];
}
return num;
}
int main(){
int n;cin >> n;
while(n++){
int x; cin >> x;
insertTrie(x);
ans = min(ans, ask(x));
}
cout << ans;
return 0;
}
::: :::align{center}
:::