哪里错了,谢谢大佬orz!P3379 lca
  • 板块题目总版
  • 楼主华悦泽
  • 当前回复1
  • 已保存回复1
  • 发布时间2021/10/12 19:49
  • 上次更新2023/11/4 03:58:35
查看原帖
哪里错了,谢谢大佬orz!P3379 lca
549617
华悦泽楼主2021/10/12 19:49
#include<bits/stdc++.h>
using namespace std;
const int N=500005;
int fa[N][26],depth[N];
vector<int> g[N];
void dfs(int x,int parent){
	fa[x][0]=parent;
	depth[x]=depth[parent]+1;
	for(int i=0;i<g[x].size();i++){
		if(g[x][i]!=parent) dfs(g[x][i],x);
	}
	
}
int lca(int x,int y){
	if(depth[x]<depth[y]) swap(x,y);
	for(int i=20;i>=0;i--){
		if(depth[fa[x][i]]>=depth[y]) x=fa[x][i];
	}
	if(x==y) return x;
	for(int i=20;i>=0;i--){
		if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i];
	}
    return fa[x][0];
}
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	for(int i=1,x,y;i<n;i++){
	    scanf("%d%d",&x,&y);
		g[x].push_back(y);
		g[y].push_back(x); 
	}
	dfs(1,0);
	for(int i=0;i<20;i++){
		for(int x=1;x<=n;x++){
			fa[x][i+1]=fa[fa[x][i]][i];
		}
	}
	while(m--){
		int x,y;
		scanf("%d%d",&x,&y);
		printf("%d\n",lca(x,y));
	}
return 0;
}

2021/10/12 19:49
加载中...