The first line contains two integers n(1<=n<=10^5) and m(1<=m<=10^5), which are the amount of tree’s nodes and queries, respectively.
The second line contains n integers a[1..n] and a[i](0<=a[i]<2^{16}) is the value on the ith node.
The next n–1 lines contains two integers u v, which means there is an connection between u and v.
The next m lines contains three integers x y z, which are the parameters of Zero’s query.
Output For each query, output the answer.
Sample Input
3 2 1 2 2 1 2 2 3 1 3 1 2 3 2Sample Output
3 0
题意:一颗带权树,M个询问,每个询问给出三个值u、v、w,问树上u到v路径中选一个点异或w的最大值是多少?
思路:用可持久化Tri记录每个点到根节点的历史信息,然后就是经典01字典树做法了。
# include <iostream>
# include <cstdio>
# include <algorithm>
# include <vector>
using namespace std;
const int maxn = 1e5+30;
int n, m;
vector<int>g[maxn];
int fa[maxn][20], a[maxn], deep[maxn];
int tree[maxn*35][2], son[maxn*35][2], root[maxn], cnt;
void build(int &x, int y, int val, int pos)
{
if(pos<0) return;
x = ++cnt;
int tmp = !!(1<<pos&val);
tree[x][tmp] = tree[y][tmp] + 1;
tree[x][tmp^1] = tree[y][tmp^1];
son[x][tmp^1] = son[y][tmp^1];
build(son[x][tmp], son[y][tmp], val, pos-1);
}
int query(int x, int y, int z, int val, int sum, int pos)
{
if(pos < 0) return sum;
int tmp = !!(1<<pos&val);
if(tree[x][tmp^1]+tree[y][tmp^1]-2*tree[z][tmp^1] > 0)
return query(son[x][tmp^1], son[y][tmp^1], son[z][tmp^1], val, 1<<pos|sum, pos-1);
else
return query(son[x][tmp], son[y][tmp], son[z][tmp], val, sum, pos-1);
}
void dfs(int u, int pre)
{
deep[u] = deep[pre] + 1;
fa[u][0] = pre;
for(int i=1; i<20; ++i) fa[u][i] = fa[fa[u][i-1]][i-1];
build(root[u], root[pre], a[u], 15);
for(int i=0; i<g[u].size(); ++i)
{
int v = g[u][i];
if(v != pre) dfs(v, u);
}
}
int lca(int v, int u)
{
if(deep[v] > deep[u]) swap(u,v);
for(int i=0; i<20; ++i)
if(deep[u]-deep[v]>>i&1)
u = fa[u][i];
for(int i=19; ~i; --i)
if(fa[v][i] != fa[u][i])
v=fa[v][i], u=fa[u][i];
return v==u?v:fa[v][0];
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
cnt = 0;
for(int i=1; i<=n; ++i)
{
scanf("%d",&a[i]);
g[i].clear();
}
for(int i=1, u, v; i<n; ++i)
{
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1, 0);
while(m--)
{
int u, v, w;
scanf("%d%d%d",&u,&v, &w);
int l = lca(u,v), ans;
ans = max(w^a[l], query(root[u],root[v],root[l],w,0,15));
printf("%d\n",ans);
}
}
return 0;
}
262


&spm=1001.2101.3001.11974&articleId=80345337&d=1&t=3&u=66065dedb28e47a6b49d1a438fd367bd)

被折叠的 条评论
为什么被折叠?



