P3379【模板】最近公共祖先

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+100;
int n,m,s;
int father[20][maxn];
vector<int> g[maxn];
int h[maxn];
void dfs (int x) {
    for (int i=0;i<g[x].size();i++) {
        int v=g[x][i];
        if (v==father[0][x]) continue;
        father[0][v]=x;
        h[v]=h[x]+1;
        dfs(v);
    }
}
int lca (int x,int y) {
    if (h[x]<h[y]) swap(x,y);
    for (int i=17;i>=0;i--)
        if (h[x]-h[y]>>i) x=father[i][x];
    if (x==y) return x;
    for (int i=17;i>=0;i--) 
        if (father[i][x]!=father[i][y]) {
            x=father[i][x];
            y=father[i][y];
        }
    return father[0][x];
}
int main () {
    scanf("%d%d%d",&n,&m,&s);
    for (int i=1;i<n;i++) {
        int x,y;
        scanf("%d%d",&x,&y);
        g[x].push_back(y);
        g[y].push_back(x);
    }
    dfs(s);
    for (int i=1;i<=17;i++)
        for (int j=1;j<=n;j++)
            father[i][j]=father[i-1][father[i-1][j]];
    for (int i=0;i<m;i++) {
        int x,y;
        scanf("%d%d",&x,&y);
        printf("%d\n",lca(x,y));
    }
}

 

posted @ 2020-08-06 19:42  zlc0405  阅读(95)  评论(0编辑  收藏  举报