30pts求助
查看原帖
30pts求助
632955
伊地知虹夏楼主2023/1/12 22:37
#include <bits/stdc++.h>
using namespace std;
const int N = 500005;
int n,m,s,d[N];
int LCA[N][22],fa[N];
vector<int> g[N];
void dfs(int cur,int dep){
    d[cur] = dep;
    for(int i = 0;i < g[cur].size();i ++){
        int y = g[cur][i];
        if(d[y] == 0) 
            LCA[y][0] = cur,dfs(y,dep+1);
    }
    return ;
}
void init(){
    for(int j = 1;j <= 20;j ++)
        for(int i = 1;i + (1 << j-1)-1 <= n;i ++)
            LCA[i][j] = LCA[LCA[i][j-1]][j-1];
}
int lca(int a, int b)
{
    if(d[a] < d[b]) swap(a,b);
    int sum = d[a] - d[b];
    for(int i = 20;i >= 0;i --)
        if(sum >= (1 << i))
            sum -= (1 << i),
            a = LCA[a][i];
    if(a == b) return a;
    for(int i = 20;i >= 0;i --)
        if(LCA[a][i] != LCA[b][i])
            a = LCA[a][i],b = LCA[b][i];
    return LCA[a][0];
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m >> s;
    for(int i = 1;i < n;i ++){
        int x,y;
        cin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    dfs(s,1);
    init();
    while(m --){
        int x,y;
        cin >> x >> y;
        cout << lca(x,y) << "\n";
    }
    return 0;
}
2023/1/12 22:37
加载中...