lca模板

#include<bits/stdc++.h>
using namespace std;
const int maxn = 500005;
struct edge{
    int next, to;
}e[maxn << 1];
int head[maxn], cnt;
int n, m, s, a, b, xx, yy;
int depth[maxn], fa[maxn][22];

void add(int u, int v)
{
    e[++cnt].to = v;
    e[cnt].next = head[u];
    head[u] = cnt;
}

void dfs(int now, int fath)
{
    depth[now] = depth[fath] + 1;
    fa[now][0] = fath;
    for(int i = 0; i <= 18; i++)
        fa[now][i+1] = fa[fa[now][i]][i];
    for(int i = head[now]; i != 0; i = e[i].next)
    {
        if(e[i].to != fath)
        dfs(e[i].to, now);
    }
}

int lca(int x, int y)
{
    if(depth[x] < depth[y]) swap(x, y);
    for(int i = 18; i >= 0; i--)
    {
        if(depth[fa[x][i]] >= depth[y]) x = fa[x][i];
        if(x == y) return x;
    }
    for(int i = 18; i >= 0; i--)
    {
        if(fa[x][i] != fa[y][i])
        {
            x = fa[x][i];
            y = fa[y][i];
        }
    }
    return fa[x][0];
}

int main()
{
    scanf("%d%d%d", &n, &m, &s);
    for(int i = 1; i < n; i++)    
    {
        scanf("%d%d", &xx, &yy);
        add(xx, yy); add(yy, xx);
    }
    dfs(s, 0);
    for(int i = 1; i <= m; i++)
    {
        scanf("%d%d", &a, &b);
        printf("%d\n", lca(a, b));
    }
    return 0;
}

 

posted @ 2019-10-31 20:03  ATKevin  阅读(112)  评论(0编辑  收藏  举报