【模板】倍增求LCA

颓废了几个月了qwq

先敲一通模板(Luogu P3379

#include<iostream>
#include<cstdio>
#define N 500005
using namespace std;
int n, m, root, tot;
int f[N][22];
struct edge{
    int go, next;
}e[2*N];
int head[N], dep[N], a, b;
void ycl(int u, int father){
    dep[u]=dep[father]+1;
    for(int i=0; i<=20; i++) 
        f[u][i+1]=f[f[u][i]][i];
    for(int i=head[u]; i; i=e[i].next){
        int v=e[i].go;
        if(v==father) continue;
        f[v][0]=u;
        ycl(v, u);
    }
}
void add(int u, int v){
    e[++tot].go=u;
    e[tot].next=head[v];
    head[v]=tot;
}
int LCA(int x, int y){
    if(dep[x]<dep[y])swap(x, y);
    for(int i=21; i>=0; i--){
        if(dep[f[x][i]]>=dep[y])x=f[x][i];
        if(x==y)return x;
    }
    for(int i=21; i>=0; i--)
        if(f[x][i]!=f[y][i]) x=f[x][i], y=f[y][i];
    return f[x][0];
}
int main(){
    scanf("%d%d%d", &n, &m, &root);
    for(int i=1; i<n; i++){
        scanf("%d%d", &a, &b);
        add(a, b);
        add(b, a);
    }
    ycl(root, 0);
    for(int i=1; i<=m; i++){
        scanf("%d%d", &a, &b);
        printf("%d\n", LCA(a, b));
    }
    return 0; 
}

猜你喜欢

转载自www.cnblogs.com/pushinl/p/9714792.html
今日推荐