LCA哪里炸了啦?qwq
查看原帖
LCA哪里炸了啦?qwq
134593
反手一只MJJ楼主2020/11/5 07:54

LCA板子T了一个点,wa了6个点,哪里炸了啊?QwQ 求大佬指导!

#include<cstdio>
#include<cctype>
#define rd read()
const int maxn=1000008;
inline int read(){
	int x=0;
	char g=getchar();
	while(!isdigit(g))g=getchar();
	while(isdigit(g))x=(x<<1)+(x<<3)+(g^48),g=getchar();
	return x;
}
int head[maxn>>1],to[maxn],nex[maxn],tot=0;
inline void add(int u,int v){
	to[++tot]=v;
	nex[tot]=head[u];
	head[u]=tot;
	to[++tot]=u;
	nex[tot]=head[v];
	head[v]=tot;
	return;
}
int deth[maxn>>1],fa[maxn>>1][22],lg[maxn>>1];
inline void dfs(int now,int fath){
	fa[now][0]=fath,deth[now]=deth[fath]+1;
	for(int i=1;(1<<i)<=deth[now];i++)
		fa[now][i]=fa[fa[now][i-1]][i-1];
	for(int tmp=head[now];tmp;tmp=nex[tmp]){
		if(to[tmp]!=fath)dfs(to[tmp],now);
	}
	return;
}
inline int LCA(int x,int y){
	if(deth[y]>deth[x]){int tmp=x;x=y,y=tmp;}
	while(deth[x]>deth[y])
		x=fa[x][lg[deth[x]-deth[y]]-1];
	if(x==y)return x;
	for(int k=lg[deth[x]]-1;k>=0;k--){
		if(fa[x][k]==fa[y][k])continue;
		x=fa[x][k],y=fa[y][k];
	}
	return fa[x][0];
}
int n=rd,m=rd,s=rd;
int main(){
	for(int i=1;i<n;i++)add(rd,rd);
	for(int i=1;i<=n;i++)lg[i]=lg[i-1]+(1<<lg[i-1]==1);
	dfs(s,0);
	for(int i=1;i<=m;i++)printf("%d\n",LCA(rd,rd));
	return 0;
}
2020/11/5 07:54
加载中...