如果只是一条路径的话,那就是非常简单的线性基。
不过要考虑多组询问……
考虑到n比较小,我们可以模仿倍增LCA的方法,预处理倍增的线性基。在每次路径上跳的时候把线性基合并最后求解即可。具体的做法是,我们用\(p[i][x][j]\)表示在编号为x的点处,向上跳\(2^i\)步以内,线性基第j位的数。这个可以合并,比较好写的方法就是直接传两个数组进去合并。
之后就正常了。代码很短,不到100行。(我交了好多次因为忘记用longlong快读了……)
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<cstring>
#define rep(i,a,n) for(register int i = a;i <= n;i++)
#define per(i,n,a) for(register int i = n;i >= a;i--)
#define enter putchar(‘\n‘)
#define pr pair<int,int>
#define mp make_pair
#define fi first
#define sc second
#define I inline
using namespace std;
typedef long long ll;
const int M = 20005;
const int N = 10000005;
ll read()
{
ll ans = 0,op = 1;char ch = getchar();
while(ch < ‘0‘ || ch > ‘9‘) {if(ch == ‘-‘) op = -1;ch = getchar();}
while(ch >=‘0‘ && ch <= ‘9‘) ans = ans * 10 + ch - ‘0‘,ch = getchar();
return ans * op;
}
struct edge
{
int next,to;
}e[M<<1];
ll p[16][M][62],head[M<<1],ecnt,n,q,G[M],x,y,fa[16][M],dep[M],b[62];
I void add(int x,int y)
{
e[++ecnt] = (edge){head[x],y};
head[x] = ecnt;
}
I void insert(ll x,ll *a)
{
per(i,61,0)
{
if(!((x>>i)&1)) continue;
if(!a[i]) {a[i] = x;break;}
x ^= a[i];
}
}
I void merge(ll *a,ll *b)
{
per(i,61,0) if(a[i]) insert(a[i],b);
}
void dfs(int x,int f,int depth)
{
fa[0][x] = f,dep[x] = depth;
rep(i,1,15) fa[i][x] = fa[i-1][fa[i-1][x]];
rep(i,1,15) merge(p[i-1][x],p[i][x]),merge(p[i-1][fa[i-1][x]],p[i][x]);
for(int i = head[x];i;i = e[i].next) if(e[i].to != f) dfs(e[i].to,x,depth+1);
}
ll calc(int x,int y)
{
ll cur = 0;
memset(b,0,sizeof(b));
if(dep[x] < dep[y]) swap(x,y);
per(i,15,0) if(dep[fa[i][x]] >= dep[y]) merge(p[i][x],b),x = fa[i][x];
per(i,15,0)
{
if(fa[i][x] != fa[i][y])
{
merge(p[i][x],b),merge(p[i][y],b);
x = fa[i][x],y = fa[i][y];
}
}
if(x != y) merge(p[0][x],b),merge(p[0][y],b),x = fa[0][x],y = fa[0][y];
merge(p[0][x],b);
per(i,61,0) if((cur ^ b[i]) > cur) cur ^= b[i];
return cur;
}
int main()
{
n = read(),q = read();
rep(i,1,n) G[i] = read(),insert(G[i],p[0][i]);
rep(i,1,n-1) x = read(),y = read(),add(x,y),add(y,x);
dfs(1,0,1);
while(q--)
{
x = read(),y = read();
printf("%lld\n",calc(x,y));
}
return 0;
}
原文地址:https://www.cnblogs.com/captain1/p/10241929.html
时间: 2024-11-09 03:46:46