社区讨论
满江红求调0
P3379【模板】最近公共祖先(LCA)参与者 3已保存回复 5
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 5 条
- 当前快照
- 1 份
- 快照标识符
- @lo1ik9kj
- 此快照首次捕获于
- 2023/10/22 21:37 2 年前
- 此快照最后确认于
- 2023/11/02 22:32 2 年前
CPP
#include<bits/stdc++.h>
using namespace std;
const int N=6e5+10,M=N*2;
int h[N],e[M],ne[M],idx;
int depth[N],fa[N][30];
int n,m;
void add(int a,int b){
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void bfs(int root){
memset(depth,0x3f,sizeof depth);
queue<int> q;
q.push(root);
depth[0]=0,depth[root]=1;
while(q.size()){
int t=q.front();
q.pop();
for(int i=h[t];i!=-1;i=ne[i]){
int j=e[i];
if(depth[j]>depth[t]+1){
depth[j]=depth[t]+1;
fa[j][0]=t;
q.push(j);
for(int k=1;k<=30;k++)
fa[j][k]=fa[fa[j][k-1]][k-1];
}
}
}
}
int lca(int a,int b){
if(depth[a]<depth[b]) swap(a,b);
for(int k=30;k>=0;k--)
if(depth[fa[a][k]]>=depth[b])
a=fa[a][k];
if(a==b) return a;
for(int k=30;k>=0;k--)
if(fa[a][k]!=fa[b][k]){
a=fa[a][k];
b=fa[b][k];
}
return fa[a][0];
}
int main()
{
int root=0;
cin>>n>>m>>root;
memset(h,-1,sizeof h);
for(int i=0;i<n-1;i++){
int a,b;
cin>>a>>b;
add(a,b),add(b,a);
}
bfs(root);//预处理
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
int p=lca(a,b);
cout<<p<<endl;
}
return 0;
}
回复
共 5 条回复,欢迎继续交流。
正在加载回复...