最近公共祖先模板(LCA)

题目:https://www.luogu.com.cn/problem/P3379

求两个点的公共组先,通过倍增法求解。。模板题算法讲解点这里

代码:

//题目:https://www.luogu.com.cn/problem/P3379
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

const int N = 500050;

//----------------邻接表-------------------
struct edge{
    int next,to;
}edges[N<<1];

int head[N];
int cnt;
void add(int u,int v){
    edges[++cnt].next = head[u];
    edges[cnt].to = v;
    head[u] = cnt;
}
//----------------邻接表-------------------

int fa[N][50],depth[N],lg[N]; //fa记录各个节点的2^i级组先,depth记录各个点的深度,lg是存放常数log2(i) + 1
int n,m,s;

//----------------读入数据-----------------
inline int read(){
    int x = 0,f=1; char ch = getchar();
    while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
    while(ch >= '0' && ch <= '9'){x = x*10 + ch - '0'; ch = getchar();}
    return x*f;
}
//----------------读入数据-----------------

void dfs(int now,int fath){ //记录每个节点的深度,以及祖先
    fa[now][0] =fath,depth[now] = depth[fath]+1;

    for(int i = 1;i<=lg[depth[now]];i++)    //倍增法,意思是now的2^i祖先等于now的2^(i-1)的祖先的2^(i-1)
        fa[now][i] = fa[fa[now][i-1]][i-1];
    
    for(int i = head[now];i;i=edges[i].next){
        if(edges[i].to!=fath) dfs(edges[i].to,now);
    }
}

int LCA(int x,int y){

    if(depth[x] < depth[y]) swap(x,y);  //保证x的深度大于y,因为后面要使它们的深度相同

    while(depth[x] > depth[y])  x = fa[x][lg[depth[x] - depth[y]] - 1];  //这一步就是让它们都处在同一个深度

    if(x == y) return x;

    for(int i = lg[depth[x]]-1;i>=0; --i)
        if(fa[x][i] != fa[y][i]) x = fa[x][i],y = fa[y][i];
    return fa[x][0];
}

int main(){
    
    n = read(),m = read(),s = read();

    int u,v;
    for(int i = 1;i<n;i++){ //建树
        u = read(),v = read();
        add(u,v),add(v,u);
    }
    
    for(int i = 1;i<=n;i++){    //log2(i) + 1,加个常数可以优化
        lg[i] = lg[i-1] + (1 << lg[i-1] == i);
    }
    dfs(s,0);

    while(m--){
        int x = read(),y = read();

        printf("%d\n",LCA(x,y));

    }

    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值