P3379 【模板】最近公共祖先(LCA)求调
查看原帖
P3379 【模板】最近公共祖先(LCA)求调
905666
kun1145141919810楼主2023/8/13 18:09
#include<bits/stdc++.h>
using namespace std;
int head[100010],nxt[100010],to[100010],top[100010],dep[100010],siz[100010],son[100010],fa[100010];
int xjz[100010],tot=0;
void add(int u,int v){
	tot++;
	to[tot]=v;
	nxt[tot]=head[u];
	head[u]=tot; 
}
inline int read(){
	int x=0,f=1;char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
	return x*f;
}
void dfs1(int u) {
	son[u] = -1;
	siz[u] = 1;
	for (int i=head[u];i;i=nxt[i]){//遍历每个节点 
    	if (!dep[xjz[i]]){//有值 
    		dep[xjz[i]]=dep[u]+1;//更新深度 
    		fa[xjz[i]]=u;//连接父亲 
    		dfs1(xjz[i]);
    		siz[u] += siz[xjz[i]]; 
    		if (son[u] == -1 || siz[xjz[i]] > siz[son[u]]) son[u] = xjz[i];
    	}
	}
}
void dfs2(int u, int t) {
	top[u] = t;
	if (son[u] == -1) return;
	dfs2(son[u],t); 
	for (int i=head[u];i;i=nxt[i]){
		if(xjz[i]!=son[u]&&xjz[i]!=fa[u]){
			dfs2(xjz[i],xjz[i]);
		}
	}
}
int lca(int u, int v) {
	while (top[u] != top[v]) {
    	if (dep[top[u]] > dep[top[v]])u = fa[top[u]];
    	else v = fa[top[v]];
	}
	return dep[u] > dep[v] ? v : u;
}
int main(){
	int n,m,s;
	n=read();m=read();s=read();
	for(int i=1;i<=n-1;i++){
		int x,y;
		x=read();
		y=read();
		add(x,y);
		add(y,x);
	}
	dfs1(s);
	dfs2(s,s);
	for(int i=1;i<=m;i++){
		int x,y;
		x=read();
		y=read();
		cout<<lca(x,y)<<endl;
	}
	return 0;
}
2023/8/13 18:09
加载中...