样例能过,一组数据能过,求助
查看原帖
样例能过,一组数据能过,求助
1169614
abbcc8865楼主2023/11/5 14:14
#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
const int M = log2(N)+1;
int fa[M][N];
vector <int>ch[N];
int depth[N];

void build(int from , int n,int d)
{
	fa[0][n]= from;
	depth[n] = d;
	for(int i = 0 ; i != ch[n].size();++i)
	if(ch[n][i]!=from)
	{
		build(n,ch[n][i],d+1);
	}
}
void init(int n,int m)
{
	for(int i = 1 ; i != m ;++i)
	for(int j = 1 ; j <= n  ;++j)
	{
		fa[i][j]=fa[i-1][fa[i-1][j]];
	}
}

int LCA(int x,int y)
{
	if(depth[x]<depth[y])
	{
		int temp = x;
		x=y;
		y=temp;
		
	}
	int t = depth[x]-depth[y];
	int p = 0;
	while(t!= 0)
	{
		
		if(t&1==1)
		{
			x = fa[p][x];
		}
		t=t>>1;
		++p;
		
	}
	if (x==y)return x;
	t = log2(depth[x]);
	for(int i = t; i >= 0 ; --i)
	{
		if(fa[t][x]!=fa[t][y])
		{
			x=fa[t][x];
			y=fa[t][y];
		}
	}
	return fa[0][x];
}

int main(){
	int n,m ,s;
	cin >> n >> m >>s;
	for(int i = 2 ; i <= n ; ++i)
	{
		int x,y;
		cin>>x>>y;
		ch[x].push_back(y);
		ch[y].push_back(x);
	}
	build(0,s,1);
	init(n,log2(n)+1);
	vector<int> ans;
	for(int i=0;i!=m;++i)
	{
		int a,b;
		cin >>a>>b;
		ans.push_back(LCA(a,b));
	}
		for(int i=0;i!=m;++i)
		cout << ans[i]<<endl;
}
2023/11/5 14:14
加载中...