lca模板

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#define inf 2147483647
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(int i=a;i<=b;++i)

using namespace std;

int n,m,s,x,y;
int f[N][21],deep[N];

void in(int &x){
    int y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(int x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

struct node{
    int n;
    node *next;
}*e[N];

void push(int x,int y){
    node *p;
    p=new node();
    p->n=y;
    if(e[x]==0) e[x]=p;
    else{
        p->next=e[x]->next;
        e[x]->next=p;
    }
}

void build(int now){
    deep[now]=deep[f[now][0]]+1;
    for(int i=1;(1<<i)<=deep[now];i++) f[now][i]=f[f[now][i-1]][i-1];
    for(node *i=e[now];i!=NULL;i=i->next){
        if(i->n!=f[now][0]){
            f[i->n][0]=now;
            build(i->n);
        }
    }
} 

int query(int x,int y){
    if(deep[x]<deep[y]) swap(x,y);
    int c=deep[x]-deep[y];
    for(int i=0;i<=log2(c);i++) if((1<<i)&c) x=f[x][i];
    if(x==y) return x;
    for(int i=log2(deep[x]);i>=0;i--){
        if(f[x][i]!=f[y][i]){
            x=f[x][i];
            y=f[y][i];
        }
    }
    return f[x][0];
}

int main(){ 
      in(n),in(m),in(s);
      For(i,1,n-1){
        in(x),in(y);
        push(x,y);
        push(y,x);
    }
    f[s][0]=s;
    build(s);
    for(int i=1;i<=m;i++){
        in(x),in(y);
        o(query(x,y));
        p('
');
    }
  return 0;
}
原文地址:https://www.cnblogs.com/war1111/p/7360591.html