Tree chain division to find LCA board

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e5+100;
typedef int LL;
LL root;
LL siz[maxn],fa[maxn],dep[maxn],son[maxn];
LL top[maxn];
vector<LL>g[maxn];
void predfs(LL u,LL father)
{
    siz[u]=1;
    dep[u]=dep[father]+1;
    fa[u]=father;
    for(LL i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==father) continue;
        predfs(v,u);
        siz[u]+=siz[v];
        if(siz[v]>siz[son[u]]){
            son[u]=v;
        }
    }
}
void dfs(LL u,LL topx)
{
    top[u]=topx;
    if(son[u]==0) return;///叶子节点
    dfs(son[u],topx);///先处理重儿子
    for(LL i=0;i<g[u].size();i++)
    {
        LL v=g[u][i];
        if(v==fa[u]||v==son[u]) continue;
        dfs(v,v);
    }
}
LL lca(LL u,LL v)
{
    while(top[u]!=top[v])
    {
        if(dep[top[u]]<dep[top[v]]){
            swap(u,v);
        }
        u=fa[top[u]];
    }
    return dep[u]<dep[v]?u:v;
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n,m,root;cin>>n>>m>>root;
  for(LL i=1;i<n;i++){
    LL u,v;cin>>u>>v;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  predfs(root,0);
  dfs(root,root);
  while(m--)
  {
      LL u,v;cin>>u>>v;
      cout<<lca(u,v)<<endl;
  }
return 0;
}

 

Guess you like

Origin blog.csdn.net/zstuyyyyccccbbbb/article/details/109851646