倍增求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-1背包问题


下一篇:把二叉树打印成多行