10分求助除了第一个点全wa 样例能过 倍增算法!!
查看原帖
10分求助除了第一个点全wa 样例能过 倍增算法!!
665828
niuniuniuppppppppp楼主2022/2/23 16:18
#include<cstdio>
#include<cmath>
using namespace std;
int n,q,root,head[500100],fa[500100][25],depth[500100],num_edge;
struct edge{
	int to;
	int next;
}a[1001000];
void add_edge(int from,int to){
	a[++num_edge].next=head[from];
	a[num_edge].to=to;
	head[from]=num_edge;
}
void dfs(int now,int father){
	depth[now]=depth[father]+1;
	fa[now][0]=father;
	int i;
	for(i=1;(1<<i)<=depth[now];i++)
	fa[now][i]=fa[fa[now][i-1]][i-1];
    
	for(i=head[now];i!=0;i=a[i].next)
	if(a[i].to!=father)dfs(a[i].to,now);	
}
int up(int x,int d){
	int ret=x;
	int i;
	for(i=0;(1<<i)<=depth[x];i++)
	if((1<<i)&d!=0)ret=fa[ret][i];
	return ret;
}
int lca(int x1,int x2){
	if(depth[x1]<depth[x2])
	x2=up(x2,depth[x2]-depth[x1]);
	else 
	x1=up(x1,depth[x1]-depth[x2]);
	if(x1==x2)return x1;
	int length3;
	length3=log(depth[x1])/log(2);
	int i;
	for(i=length3;i>=0;i--)
	if(fa[x1][i]!=fa[x2][i])
	{ x1=fa[x1][i];
	  x2=fa[x2][i];
	}
	return fa[x1][0];
}
int main(){
   int i;
   num_edge=0;
   scanf("%d %d %d",&n,&q,&root);
   for(i=1;i<=n-1;i++)
   {int temp1,temp2;
   scanf("%d %d",&temp1,&temp2);
   add_edge(temp1,temp2);
   add_edge(temp2,temp1); 
   }
   dfs(root,root);
   for(i=1;i<=q;i++)
   {int temp3,temp4;
   scanf("%d %d",&temp3,&temp4);
   printf("%d\n",lca(temp3,temp4));
   }

}
2022/2/23 16:18
加载中...