题目链接:https://loj.ac/problem/2013
倍增+线性基合并,但是最开始合并线性基的姿势不是很优秀哦?所以无限T,最后修改了一下自己的模板才过的啊?
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=2e4+5;
const int MAXL=60;
const int DEG=16;
struct LinearBasis
{
ll v[MAXL+1];
int sz,n;
LinearBasis()
{
memset(v,0,sizeof(v));
}
void add(ll x)
{
for(int i=MAXL;i>=0;i--)
{
if(x&(1LL<<i))
{
if(!v[i])
{
v[i]=x;
break;
}
x^=v[i];
}
}
}
ll query()
{
ll x=0;
for(int i=MAXL;i>=0;i--)
if((x^v[i])>x)
x^=v[i];
return x;
}
}lb[MAXN][17];
LinearBasis merge(LinearBasis A,LinearBasis B)
{
for(int i=0;i<=MAXL;i++)
{
if(B.v[i])
A.add(B.v[i]);
}
return A;
}
int n,q;
ll a[MAXN];
vector<int> E[MAXN];
int fa[MAXN][17],deg[MAXN];
ll LCA(int u,int v)
{
if(u==v)
return a[u];
LinearBasis ret;
if(deg[u]>deg[v])
swap(u,v);
int hu=deg[u],hv=deg[v];
int tu=u,tv=v;
for(int det=hv-hu,i=0;det;det>>=1,i++)
if(det&1)
{
ret=merge(ret,lb[tv][i]);
tv=fa[tv][i];
}
if(tu==tv)
{
return ret.query();
}
for(int i=DEG-1;i>=0;i--)
{
if(fa[tu][i]==fa[tv][i])
continue;
ret=merge(ret,lb[tu][i]);
ret=merge(ret,lb[tv][i]);
tu=fa[tu][i];
tv=fa[tv][i];
}
ret=merge(ret,lb[tu][0]);
ret=merge(ret,lb[tv][0]);
return ret.query();
}
void build()
{
for(int j=1;j<DEG;j++)
{
for(int i=1;i<=n;i++)
{
fa[i][j]=fa[fa[i][j-1]][j-1];
lb[i][j]=merge(lb[i][j-1],lb[fa[i][j-1]][j-1]);
}
}
}
void dfs(int now,int dp)
{
deg[now]=dp;
for(int j=0;j<E[now].size();j++)
{
int i=E[now][j];
if(i==fa[now][0])
continue;
fa[i][0]=now;
lb[i][0].add(a[i]);lb[i][0].add(a[now]);
dfs(i,dp+1);
}
}
inline char nc()
{
static char buf[100000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline void rea(ll &x)
{
char c=nc(); x=0;
for(;c>'9'||c<'0';c=nc());for(;c>='0'&&c<='9';x=x*10+c-'0',c=nc());
}
inline void rea(int &x)
{
char c=nc(); x=0;
for(;c>'9'||c<'0';c=nc());for(;c>='0'&&c<='9';x=x*10+c-'0',c=nc());
}
void solve()
{
for(int i=1;i<=n;i++)
{
rea(a[i]);
//scanf("%lld",&a[i]);
}
for(int i=1;i<n;i++)
{
int u,v;
rea(u);rea(v);
//scanf("%d%d",&u,&v);
E[u].push_back(v);
E[v].push_back(u);
}
dfs(1,0);
build();
while(q--)
{
int u,v;
rea(u);rea(v);
//scanf("%d%d",&u,&v);
printf("%lld\n",LCA(u,v));
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
rea(n);rea(q);
//scanf("%d%d",&n,&q);
solve();
return 0;
}