字典树板子很简单,用数组方式写的或是指针写的,这里提到的是字典树的剪枝问题,以下面这道题为例,
http://acm.hdu.edu.cn/showproblem.php?pid=5536
这道题因为要除去i,j,k相等的情况,所以每次查询的时候要去剪枝,即一路标记,需要剪枝的时候再一路减下去,剪完之后还要加上去,
代码如下:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<bits/stdc++.h>
using namespace std;
#define maxx 1005*32
int tree[maxx][5];
int a[maxx];
int boo[maxx],tot=1;
void insert(int x)
{
int rt=0;
for(int i=31; i>=0; i--)
{
int k=(x>>i)&1;
if(!tree[rt][k])
tree[rt][k]=tot++;
rt=tree[rt][k];
boo[rt]++;//标记,每次都要标记,
}
}
int find(int x)
{
int rt=0,ans=0;
for(int i=31; i>=0; i--)
{
int k=(x>>i)&1;
if(tree[rt][k^1]&&boo[tree[rt][k^1]])
{
ans+=(1<<i);
rt=tree[rt][k^1];
}
else
rt=tree[rt][k];
}
return ans;
}
void Delete(int x)//剪枝的时候就是按照标记一路减下去
{
int rt=0;
for(int i=31; i>=0; i--)
{
int k=(x>>i)&1;
rt=tree[rt][k];
boo[rt]--;
}
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
tot=1;
memset(tree,0,sizeof(tree));
memset(boo,0,sizeof(boo));
scanf("%d",&n);
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
insert(a[i]);
}
int maxn=0;
for(int i=0; i<n-1; i++)
{
Delete(a[i]);
for(int j=i+1; j<n; j++)
{
Delete(a[j]);
int g=a[i]+a[j];
int p=find(g);
if(p>maxn)
maxn=p;
insert(a[j]);
}
insert(a[i]);
}
printf("%d\n",maxn);
}
return 0;
}
如果查询单词个数的话,可以在每次插入单词的时候标记让boo[root]++;查询的时候就可以直接查到整棵树中相同单词的个数。
线段树之前看到过一篇入门博客,写的很好,以后复习的时候还可以拿出来看看