求调
查看原帖
求调
1341274
KarS_楼主2025/1/14 16:06
#include <iostream>
#include <cstring>
using namespace std;
#define endl '\n'

const int N=5e5+10,M=19;

int h[N],nxt[N],ne[N],tot=1;
int f[N][M],deep[N];

inline void add(int x,int y) {
	ne[tot]=y;
	nxt[tot]=h[x],h[x]=tot++;
}

void dfs(int u,int father) {
	f[u][0]=father;
	for (int i=1;i<M;i++) 
		f[u][i]=f[ f[u][i-1] ][i-1];
	for (int i=h[u];~i;i=nxt[i]) {
		int v=ne[i];
		if (v!=father) {
			deep[v]=deep[u]+1;
			dfs(v,u);
		}
	}
}

int LCA(int x,int y) {
	if (deep[x]<deep[y]) swap(x,y);
	for (int i=M-1;i>=0;i--) {
		if (deep[f[x][i]]>=deep[y]) x=f[x][i]; 
	}
	if (x==y) return x;
	for (int i=M-1;i>=0;i--)
		if (deep[f[x][i]] != deep[f[y][i]]) {
			x=f[x][i];
			y=f[y][i];
		}
	return f[x][0];
}

int main() {
	ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	memset(h,-1,sizeof h);
	int n,m,root;
	cin>>n>>m>>root;
	for (int i=1;i<n;i++) {
		int x,y;
		cin>>x>>y;
		add(x,y),add(y,x);
	}
	deep[root]=1;
	dfs(root,root);
	int x,y;
	for (int i=1;i<=m;i++) {
		cin>>x>>y;
		if (x==y) cout << x << endl;
		else cout << LCA(x,y) << endl;
	}
	return 0;
}
2025/1/14 16:06
加载中...