Description
给出一棵 n n 个节点的树,节点为根节点, i i 节点点权为,有 q q 组查询,每组查询给出一个节点编号和以非负整数 x x ,查询以为根节点的子树中,节点点权异或 x x 的最大值
Input
多组用例,每组用例首先输入两个整数表示点数和查询数,之后输入 n n 个节点表示这 n n 个点的点权,之后输入个整数表示 2,...,n 2 , . . . , n 节点的父亲节点,最后 q q 行每行输入两个整数表示一组查询
(2≤n,q≤105,0≤vali≤109,0≤x≤109) ( 2 ≤ n , q ≤ 10 5 , 0 ≤ v a l i ≤ 10 9 , 0 ≤ x ≤ 10 9 )
Output
对于每组查询,输出以 u u 节点为根的子树中点权异或的最大值
Sample Input
2 2
1 2
1
1 3
2 1
Sample Output
2
3
Solution
离线查询,按 dfs d f s 序把节点一个个加入字典树中,对于当前加入节点的每个查询在字典树中跑一边即可
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
#define maxn 100005
typedef struct trie
{
trie *son[2];
}trie;
trie *root[maxn];
vector<int>g[maxn];
vector<P>q[maxn];
int n,m,val[maxn],ans[maxn];
void Insert(trie *x,int v)
{
trie *y=x;
for(int i=29;i>=0;i--)
{
int t=0;
if(v&(1<<i))t^=1;
if(y->son[t]==NULL)
{
trie *temp=new trie;
temp->son[0]=temp->son[1]=NULL;
y->son[t]=temp;
}
y=y->son[t];
}
return ;
}
trie* Merge(trie *x,trie *y)
{
if(x==NULL)return y;
if(y==NULL)return x;
x->son[0]=Merge(x->son[0],y->son[0]);
x->son[1]=Merge(x->son[1],y->son[1]);
free(y);
return x;
}
void Delete(trie *x)
{
if(x->son[0]!=NULL)Delete(x->son[0]);
if(x->son[1]!=NULL)Delete(x->son[1]);
free(x);
return ;
}
int Query(trie *x,int v)
{
trie *y=x;
int ans=0;
for(int i=29;i>=0;i--)
{
int t=0;
if(v&(1<<i))t^=1;
if(y->son[t^1]==NULL)y=y->son[t];
else
{
ans|=(1<<i);
y=y->son[t^1];
}
}
return ans;
}
void dfs(int u)
{
root[u]=new trie;
root[u]->son[0]=root[u]->son[1]=NULL;
Insert(root[u],val[u]);
for(int i=0;i<g[u].size();i++)
{
int v=g[u][i];
dfs(v);
root[u]=Merge(root[u],root[v]);
}
for(int i=0;i<q[u].size();i++)ans[q[u][i].second]=Query(root[u],q[u][i].first);
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)g[i].clear(),q[i].clear();
for(int i=1;i<=n;i++)scanf("%d",&val[i]);
for(int i=2;i<=n;i++)
{
int a;
scanf("%d",&a);
g[a].push_back(i);
}
for(int i=1;i<=m;i++)
{
int u,x;
scanf("%d%d",&u,&x);
q[u].push_back(P(x,i));
}
dfs(1);
for(int i=1;i<=m;i++)printf("%d\n",ans[i]);
Delete(root[1]);
}
return 0;
}