BZOJ4568: [Scoi2016]幸运数字(洛谷P3292)

292 篇文章 1 订阅
281 篇文章 1 订阅

线性基 倍增

BZOJ题目传送门
洛谷题目传送门

预处理 x x x跳了 2 j 2^j 2j的线性基,每次询问倍增跳并合并线性基,最后查一下最大值就好了。复杂度 O ( 60 ∗ 60 ∗ m log ⁡ n ) O(60*60*m\log n) O(6060mlogn)

代码:

#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 20005
#define F inline
using namespace std;
typedef long long LL;
struct edge{ int nxt,to; }ed[N<<1];
int n,m,k,h[N],dep[N],fa[N][16]; LL p[N][16][61];
F char readc(){
	static char buf[100000],*l=buf,*r=buf;
	if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
	return l==r?EOF:*l++;
}
F LL _read(){
	LL x=0; char ch=readc();
	while (!isdigit(ch)) ch=readc();
	while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
	return x;
}
F void dfs(int x){
	dep[x]=dep[fa[x][0]]+1;
	for (int i=h[x],v;i;i=ed[i].nxt)
		if ((v=ed[i].to)!=fa[x][0]) fa[v][0]=x,dfs(v);
}
F void mdfy(LL x,LL *p){
	if (!x) return;
	for (int i=60;~i;i--)
		if ((x>>i)&1) if (!p[i]){ p[i]=x; break; } else x^=p[i];
}
F void mrg(LL *x,LL *y){ for (int i=60;~i;i--) mdfy(x[i],y); }
F void Make(){
	for (int j=1;j<16;j++)
		for (int i=1;i<=n;i++){
			fa[i][j]=fa[fa[i][j-1]][j-1];
			mrg(p[i][j-1],p[i][j]),mrg(p[fa[i][j-1]][j-1],p[i][j]);
		}
}
F LL lca(int x,int y){
	LL ans=0,pp[61]; memset(pp,0,sizeof(pp));
	if (dep[x]<dep[y]) swap(x,y);
	for (int j=15;~j;j--)
		if (dep[fa[x][j]]>=dep[y]) mrg(p[x][j],pp),x=fa[x][j];
	if (x==y){ mrg(p[y][0],pp); goto calc; }
	for (int j=15;~j;j--)
		if (fa[x][j]!=fa[y][j])
			mrg(p[x][j],pp),x=fa[x][j],mrg(p[y][j],pp),y=fa[y][j];
	mrg(p[x][1],pp),mrg(p[y][0],pp); goto calc;
	calc:{
		for (int j=60;~j;j--)
			if ((ans^pp[j])>ans) ans^=pp[j];
		return ans;
	}
}
#define add(x,y) ed[++k]=(edge){h[x],y},h[x]=k
int main(){
	n=_read(),m=_read();
	for (int i=1;i<=n;i++) mdfy(_read(),p[i][0]);
	for (int i=1,x,y;i<n;i++)
		x=_read(),y=_read(),add(x,y),add(y,x);
	for (dfs(1),Make();m;m--) printf("%lld\n",lca(_read(),_read()));
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值