Loading

LCA

P3379 【模板】最近公共祖先(LCA)

邻接表存图。

struct node{...};
void add(...){}

ll dep[500010], fa[500010][23];
ll head[500010], tot;
ll n, m, s;

ll dep[N], fa[N][25];
void dfs(ll now, ll fath)
{
    dep[now] = dep[fath] + 1;
    fa[now][0] = fath;
    for(int i = 1; i <= 22; ++i)
        fa[now][i] = fa[fa[now][i - 1]][i - 1];
    for(int i = head[now]; i; i = t[i].nxt)
        if(t[i].to != fath)
            dfs(t[i].to, now);
}

ll LCA(ll x, ll y)
{   
    if(dep[x] < dep[y]) swap(x, y);
    for(int k = 22; k >= 0; --k)
        if(dep[fa[x][k]] >= dep[y])
            x = fa[x][k];
    if(x == y) return x;
    for(int k = 22; k >= 0; --k)
        if(fa[x][k] != fa[y][k])
            x = fa[x][k], y = fa[y][k];
    return fa[x][0];    
}

int main()
{
    n = read();
    m = read();
    s = read();
    for (int i = 1; i <= n; ++i)
        lg[i] = lg[i - 1] + (1 << lg[i - 1] == i);
        
    for (int i = 1; i < n; ++i)
    {
        ll x = read(), y = read();
        add(x, y);
        add(y, x);
    }
    
    dfs(s, 0);
    for (int i = 1; i <= m; ++i)
    {
        ll x = read(), y = read();
        printf("%lld\n", LCA(x, y));
    }
    return 0;
}
posted @ 2021-06-29 10:37  EdisonBa  阅读(39)  评论(0编辑  收藏  举报