倍增求LCA

参考:倍增求LCA

#include <iostream>
#include <cstdlib>
#include <vector>
#include <queue>

using namespace std;

#define SIZE 500005

struct edge{
    int to;
    int next;
}edges[SIZE<<1];
int head[SIZE];
int depth[SIZE];
int fathers[SIZE][21];
int lg[SIZE];
int tot=0;

void add(int from, int to){
    tot++;
    edges[tot].to = to;
    edges[tot].next = head[from];
    head[from] = tot;
}

void dfs(int now, int father){
    fathers[now][0] = father;
    depth[now] = depth[father] + 1;
    for(int i=1; i<lg[depth[now]]; i++){
        fathers[now][i] = fathers[fathers[now][i-1]][i-1];
    }
    for(int i=head[now]; i; i=edges[i].next){
        if(edges[i].to!=father)
            dfs(edges[i].to, now);
    }
}

void swap(int&u, int& v){
    int temp = u;
    u = v;
    v = temp;
}

int LCA(int u, int v){
    if(depth[u]<depth[v])   swap(u, v);
    while(depth[u]>depth[v]){
        u = fathers[u][lg[depth[u]-depth[v]]-1];
    }
    if(u==v)    return u;
    for(int i=lg[depth[u]]-1; i>=0; i--){
        if(fathers[u][i]!=fathers[v][i]){
            u = fathers[u][i];
            v = fathers[v][i];
        }
    }
    return fathers[u][0];
}

int main() {
    int M,N,S,u,v;
    cin >> M >> N >> S;
    for(int i=1; i<M; i++){
        cin >> u >> v;
        add(u,v);
        add(v,u);
    }
    for(int i=1; i<=N; i++){预先算出log_2(i)+1的值,用的时候直接调用就可以了
        lg[i] = lg[i-1] + (1<<lg[i-1]==i);
    }
    dfs(S,0);
    int a = 234;
    for(int i=1; i<=N; i++){
        cin >> u >> v;
//        cout << u << " " << v << " " << LCA(u,v) << endl;
        cout << LCA(u,v) << endl;
    }
    return 0;
}
/*
5 5 1
3 1
2 4
5 1
1 4
2 4
 *
 * */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值