树上倍增(LCA)

int f[maxn][30];
int depth[maxn];
void bfs(){//遍历
    queue<int>q;
    q.push(s);
    depth[s]=1;
    f[s][0]=s;
    while (!q.empty()){
        int u=q.front();q.pop();
        for(int i=head[u];i;i=e[i].next){
            int v=e[i].to;
            if(depth[v])continue;
            depth[v]=depth[u]+1;
            f[v][0]=u;
            for(int i=1;i<=t;i++){
                f[v][i]=f[f[v][i-1]][i-1];
            }
            q.push(v);
        }
    }
};
int lca(int c,int d){
    if(depth[c]>depth[d])swap(c,d);// depth  d  >= c
    for(int i=t;i>=0;i--){//控制深度相同
        if(depth[f[d][i]]>=depth[c])d=f[d][i];
    }
    if(c==d)return c;
    for(int i=t;i>=0;i--){//同步倍增
        if(f[c][i]!=f[d][i]){
            c=f[c][i];d=f[d][i];
        }
    }
    return f[c][0];
}
原文地址:https://www.cnblogs.com/yesuweiYYYY/p/13801357.html