lca求改错
  • 板块灌水区
  • 楼主南瓜桐
  • 当前回复6
  • 已保存回复6
  • 发布时间2024/5/20 22:21
  • 上次更新2024/5/21 14:34:44
查看原帖
lca求改错
439327
南瓜桐楼主2024/5/20 22:21

Orz

#include <bits/stdc++.h> 
using namespace std;
int n,m,s;
const int maxmn = 5e5 + 1, logn = 20;
struct edge{
	int fr,to,nxt;
}e[maxmn*2] = {};
int cnt_edge = 0, head[maxmn] = {};
int fa[maxmn][logn+1] = {}, dep[maxmn] = {};

void add_edge(int u, int v){
	e[++cnt_edge] = (edge){u,v,head[u]};
	head[u] = cnt_edge;
}
void dfs(int root, int father){
	dep[root] = dep[father] + 1;
	fa[root][0] = father;
	for(int i = 1; i <= logn; ++i) fa[root][i] = fa[ fa[root][i-1] ][i-1];
		
	for(int i = head[root]; i != -1; i = e[i].nxt){
		int v = e[i].to;
		if(v == father) continue;
		dfs(v,root);
	}
}
int lca(int x, int y){
	if(dep[x] < dep[y]) swap(x,y);
	for(int i = logn; i >= 0; --i){
		if(dep[fa[x][i]] >= dep[y]) x = fa[x][i];
		if(x == y) return x;
	}
	for(int i = logn; i >= 0; --i){
		if(fa[x][i] != fa[y][i]) {
			x = fa[x][i];
			y = fa[y][i];
		}
	}
	return fa[x][0];
}
int main(){
	cin>>n>>m>>s;
	for(int i = 1; i <= n; ++i) head[i] = -1;
	for(int i = 1; i <= n-1; ++i){
		int u,v;
		cin>>u>>v;
		add_edge(u,v); add_edge(u,v);
	}
	dfs(s,0);
	do{
		int a,b;
		scanf("%d%d",&a,&b);
		printf("%d\n",lca(a,b));
	}while(--m);
	return 0;
}
2024/5/20 22:21
加载中...