重链剖分求LCA

#include 

using namespace std;
#define ll long long
#define mem(a, b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define DBG printf("this is a input\n")
#define fi first
#define se second
#define mk(a, b) make_pair(a,b)
#define p_queue priority_queue

ll gcd(ll a, ll b) {
    return b == 0 ? a : gcd(b, a % b);
}

ll lcm(ll a, ll b) {
    return a / gcd(a, b) * b;
}
const int maxn = 500005;
int head[maxn] , cnt = 0;
struct e
{
    int t, next;
}edge[maxn*2];
void add(int f, int t)
{
    edge[cnt].t = t;
    edge[cnt].next = head[f];
    head[f] = cnt ++;
}
int n , m, rt;
int son[maxn] , size[maxn], top[maxn], fa[maxn] , deep[maxn];
map,int>ma;
void dfs1(int u)
{
    size[u] = 1;
    for(int i = head[u] ; i != -1 ; i = edge[i].next)
    {
        int v = edge[i].t;
        if(v != fa[u])
        {
            fa[v] = u;
            deep[v] = deep[u] + 1;
            dfs1(v);
            size[u] += size[v];
            if(size[v] > size[son[u]])
                son[u] = v;
        }
    }
}
void dfs2(int u, int t)
{
    top[u] = t;
    if(son[u])
        dfs2(son[u],t);
    for(int i = head[u] ; i != -1; i = edge[i].next)
    {
        int v = edge[i].t;
        if(v != son[u] && v != fa[u])
            dfs2(v,v);
    }
}
int lca(int x , int y)
{
    while(top[x] != top[y])
    {
        if(deep[top[x]] < deep[top[y]])
            swap(x,y);
        x = fa[top[x]];
    }
    return deep[x] > deep[y] ? y : x;
}
int main(void)
{
    mem(head,-1);
    scanf("%d %d %d",&n, &m, &rt);
    for(int i = 1 ; i <= n - 1 ; i ++)
    {
        int u , v;
        scanf("%d %d",&u, &v);
        add(u,v);
        add(v,u);
    }
    dfs1(rt);
    dfs2(rt,rt);
    for(int i = 1 ; i <= m ; i ++)
    {
        int x , y;
        scanf("%d %d",&x, &y);
        printf("%d\n",lca(x,y));
    }
}

 

你可能感兴趣的:(树上操作)