全紫求条(洛谷ide能过)
查看原帖
全紫求条(洛谷ide能过)
828358
Carl170679楼主2025/7/19 15:03
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned ll
#define pb push_back
using namespace std;

vector<int>g[500005];
int n,q,root,fa[500005][25],deep[500005];

int dfs(int x,int d,int f){
	deep[x]=d;
	fa[x][0]=f;
	for(int i=0;i<g[x].size();i++){
		if(g[x][i]<0x3f3f3f3f and g[x][i]!=f){
			dfs(g[x][i],d+1,x);
		}
	}
}

int main(){
		cin>>n>>q>>root;
		for(int i=1;i<n;i++){
			int x,y;
			cin>>x>>y;
			g[x].pb(y);
			g[y].pb(x);
		}
		dfs(root,1,0);
		for(int i=1;i<=n;i++){
		 	for(int j=1;j<=25;j++){
		 		if(deep[i]>(1<<j)){
		 			fa[i][j]=fa[fa[i][j-1]][j-1];
		 		}
		 	}
		}
		for(int i=1;i<=q;i++){
			int x,y;
			cin>>x>>y;
			if(deep[x]>deep[y]){
				swap(x,y);
			}
			int t=deep[y]-deep[x],j=0;
			while(t){
				if(t&1){
					y=fa[y][j];
				}
				t>>=1;
				j++;
			}
			if(x==y){
				cout<<x<<"\n";
				continue;
			}
			int now_x=x,now_y=y;
			for(j=log2(deep[x]);j>=0;j--){
				if(fa[now_x][j]==fa[now_y][j]){
					continue;
				}
				now_x=fa[now_x][j];
				now_y=fa[now_y][j];
			}
			cout<<fa[now_x][0]<<"\n";
		}
	return 0;
}

为啥我不开O2在洛谷IDE试了数据#1,过了,但是交的时候还是RE

2025/7/19 15:03
加载中...