为什么输出全都是-1
查看原帖
为什么输出全都是-1
432183
JoeBiden2020楼主2021/7/25 09:29
#include<bits/stdc++.h>
using namespace std;
struct edge{
	int to,next;
}a[500000];
int h[250000],d[250000],prt[250000],p[250000][50],n,m,root,cnt;
void addedge(int x,int y){
	a[++cnt].to=y;
	a[cnt].next=h[x];
	h[x]=cnt;
}
void dfs(int x,int depth){
	d[x]=depth;
	for(int i=h[x];i!=0;i=a[i].next){
		dfs(a[i].to,++depth);
	}
}
void st(){
	memset(p,-1,sizeof(p));
	for(int i=1;i<=n;i++)p[i][0]=prt[i];
	for(int i=1;(1<<i)<=n;i++){
		for(int j=1;j<=n;j++){
			if(p[i][j-1]!=-1)p[i][j]=p[p[i][j-1]][j-1];
		}
	}
}
int lca(int a,int b){
	if(d[a]<d[b])swap(a,b);
	int k=log2(d[a]);
	for(int i=k;i>=0;i--){
		if(d[a]-pow(2,i)>=d[b])a=p[a][i];
	}
	if(a==b)return b;
	for(int i=k;i>=0;i--){
		if(p[a][i]!=-1 and p[a][i]!=p[b][i]){
			a=p[a][i];
			b=p[b][i];
		}
	}
	return p[a][0];
}
void read(){
	int x,y;
	cin>>n>>m>>root;
	for(int i=1;i<=n-1;i++){
		cin>>x>>y;
		addedge(y,x);
		prt[x]=y;
	}
	//while(prt[root]!=0)root=prt[root];
}
void getans(){
	int x,y;
	for(int i=1;i<=m;i++){
		cin>>x>>y;
		cout<<lca(x,y)<<endl;
	}
}
int main(){
	read();
	dfs(root,1);
	st();
	getans();
	return 0;
}
2021/7/25 09:29
加载中...