1、心得
字典树理解了半天,总算是大概弄懂了,感觉自己没有刚学算法的时候那么智力低下了(哭~),上题吧还是。
2、代码及其应用题
1、基础模版
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2e4+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];
cin >> op >> str;
if(op[0] == 'I') insert(str);
else printf("%d\n", query(str));
}
}
2、应用题:最大异或对
代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e5+10;
int son[31*N][2], num[N], 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])
{
res = res * 2 + 1;
p = son[p][!u];
}
else
{
p = son[p][u];
res*=2;
}
}
return res;
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i ++ )
{
int x = 0;
scanf("%d", &num[i]);
insert(num[i]);
}
int res = 0;
for (int i = 0; i < n; i ++ )
res = max(res,query(num[i]));
printf("%d",res);
return 0;
}
3、
就当记笔记了,自己会常常回来看的。