Trie:高效地存储和查找字符串集合的数据结构。
AcWing 835. Trie字符串统计
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
int son[N][26], cnt[N], idx;
char str[N];
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];
}
int main()
{
int n;
cin >> n;
while(n--)
{
char op[2];
scanf("%s%s", op, str);
if(op[0] == 'I') insert(str);
else printf("%d\n", query(str));
}
return 0;
}
AcWing 143. 最大异或对
1.暴力算法怎么做
res = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < i; j++)
res = max(res, a[i] ^ a[j]);
2.如何去优化
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10, M = 31 * N;
int n;
int a[N];
int son[M][2], idx;
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()
{
cin >> 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);
}
cout << res << endl;
return 0;
}
标签:记录,Trie,res,++,son,char,int,str,AcWing
From: https://www.cnblogs.com/YuukiAsuna/p/17153926.html