Monkey A lives on a tree, he always plays on this tree.
One day, monkey A learned about one of the bit-operations, xor. He was keen of this interesting operation and wanted to practise it at once.
Monkey A gave a value to each node on the tree. And he was curious about a problem.
The problem is how large the xor result of number x and one node value of label y can be, when giving you a non-negative integer x and a node label u indicates that node y is in the subtree whose root is u(y can be equal to u).
Can you help him?
Input
There are no more than 6 test cases.
For each test case there are two positive integers n and q, indicate that the tree has n nodes and you need to answer q queries.
Then two lines follow.
The first line contains n non-negative integers V1,V2,⋯,Vn
, indicating the value of node i.
The second line contains n-1 non-negative integers F1,F2,⋯Fn−1, Fi means the father of node i+1.
And then q lines follow.
In the i-th line, there are two integers u and x, indicating that the node you pick should be in the subtree of u, and x has been described in the problem.
2≤n,q≤105
0≤Vi≤109
1≤Fi≤n, the root of the tree is node 1.
1≤u≤n,0≤x≤109
Output
For each query, just print an integer in a line indicating the largest result.
Sample Input
2 2 1 2 1 1 3 2 1
Sample Output
2 3
题意:给一棵树,树上每个节点有一个权值。然后有q次查询,每次查询给你节点标号u和一个数x。问以u的子树里面的所有节点点权和数x的最大异或值是多少。
题解:先dfs序把每个节点的区间跑出来,当然也可以离线处理,这里学习一下可持久化字典树,原理上和主席树一样
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define lowbit(x) x&(-x)
const int N = 100000+10;
const int mod = 1000000007;
int n, q;
int val[N];
int root[N], cnt;
int son[N * 32][2], index;
int in[N], out[N], id[N];
int num[N * 32]; // num数组记录该节点下已统计了多少数
vector<int> v[N];
void init() {
for(int i = 0; i <= n; i++)
v[i].clear();
// memset(num, 0, sizeof(num));
cnt = 0;
index = 0;
}
void dfs(int u)
{
in[u] = ++cnt;
id[cnt] = u;
for(int i = 0; i < v[u].size(); i++) {
dfs(v[u][i]);
}
out[u] = cnt;
}
int build() {
index++;
son[index][0] = son[index][1] = 0;
return index;
}
void update(int rt, int up, int x) {
for(int i = 30; i >= 0; i--) {
int w = (x >> i) & 1;
son[rt][w] = build();
son[rt][!w] = son[up][!w];
rt = son[rt][w];
up = son[up][w];
num[rt] = num[up] + 1;
}
}
int query(int p, int x)
{
int l = root[in[p] - 1];
int r = root[out[p]];
int ans = 0;
for(int i = 30; i >= 0; i--) {
int w = (x >> i) & 1;
w = !w;
if(num[son[r][w]] - num[son[l][w]] > 0) { // 区间存在该i位置为w的数
ans += (1 << i);
} else w = !w;
r = son[r][w];
l = son[l][w];
}
return ans;
}
int main()
{
int pos, x, u;
while(~scanf("%d %d", &n, &q)) {
init();
for(int i = 1; i <= n; i++) scanf("%d", &val[i]);
for(int i = 2; i <= n; i++)
{
scanf("%d", &u);
v[u].push_back(i);
}
dfs(1);
for(int i = 1; i <= n; i++) {
root[i] = build();
update(root[i], root[i - 1], val[id[i]]);
}
while(q--) {
scanf("%d %d", &pos, &x);
printf("%d\n", query(pos, x));
}
}
return 0;
}