Luogu3379 【模板】最近公共祖先(LCA) (倍增LCA)

蒟蒻又来复习模板了。还WA了两次

#include 
#include 
#include 
#include 
#include 
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long
#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")

#else

#define D_e_Line ;

#endif

struct ios{
    templateios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;
const int N  = 500007;

struct Edge{
    int nxt, pre;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v){
    e[++cntEdge] = (Edge){head[u], v}, head[u] = cntEdge;
}

int f[N][22], lg[N], dep[N];

inline void DFS(int u, int fa){
    dep[u] = dep[fa] + 1, f[u][0] = fa;
    for(register int i = 1; (1 << i) <= dep[u]; ++ i){
        f[u][i] = f[f[u][i - 1]][i - 1];
    }
    for(register int i = head[u]; i; i = e[i].nxt){
        int v = e[i].pre;
        if(v == fa) continue;
        DFS(v, u);
    }
}


inline int LCA(int x, int y){
    if(dep[x] < dep[y]) Swap(x, y);
    while(dep[x] > dep[y]){
        x = f[x][lg[dep[x] - dep[y]] - 1];
    }
    if(x == y) return x;
    nR(k,lg[dep[x]] - 1,0){
        if(f[x][k] != f[y][k]){
            x = f[x][k];
            y = f[y][k];
        }
    }
    return f[x][0];
}

int main(){

    int n, Ques, root;
    io >> n >> Ques >> root;
    R(i,1,n-1){
        int u, v;
        io >> u >> v;
        add(u, v);
        add(v, u);
    }
    
    //log(n) + 1
    R(i,1,n)
        lg[i] = lg[i-1] + ((1 << lg[i - 1]) == i);
    
    DFS(root,0);
    
    while(Ques--){
        int x, y;
        io >> x >> y;
        printf("%d\n", LCA(x, y));
    }

    return 0;
}

转载于:https://www.cnblogs.com/bingoyes/p/11217479.html

你可能感兴趣的:(Luogu3379 【模板】最近公共祖先(LCA) (倍增LCA))