10分
查看原帖
10分
1397174
zldx楼主2024/10/3 15:47
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>>v;
vector<vector<int>>ve;
vector<int> h;
int n,m,s;
void C(){
    cin>>n>>m>>s;
    v=vector<vector<int>>(n+1);
    h=vector<int>(n+1);
    ve=vector<vector<int>>(n+1,vector<int>(21,0));
    for(int i=1;i<=n-1;i++){
        int x,y;
        cin>>x>>y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
}
void f(int x,int father,int hig){
    ve[x][0]=father;
    h[x]=hig;
    for(int i=1;i<20;i++){
        ve[x][i]=ve[ve[x][i-1]][i-1];
    }
    for(auto i:v[x]){
        if(i!=father){
            f(i,x,hig+1);
        }
    }
}
void LCA(int a,int b){
    if(h[a]!=h[b]){
        if(h[a]<h[b])swap(a,b);
        for(int i=20;i>=0;i--){
            if(h[ve[a][i]]==h[b]){
                a=ve[a][i];
                break;
            }
        }
    }
    if(a==b){
        cout<<a<<endl;
        return;
    }

    for(int i=20;i>=0;i--){
        if(ve[a][i]!=ve[b][i]){
            a=ve[a][i];
            b=ve[b][i];
        }
    }
    cout<<ve[a][0]<<endl;
}
void detect(){
    for(int i=1;i<=n;i++){
        for(int j=0;j<20;j++){
            cout<<ve[i][j]<<" ";
        }
        cout<<endl;
    }
    for(int i=1;i<=n;i++){
        cout<<h[i]<<" ";
    }
    cout<<endl;
}
int main(){
    C();
    f(s,0,1);
    for(int i=0;i<m;i++){
        int a,b;
        cin>>a>>b;
        LCA(a,b);
    }
//    detect();
}

2024/10/3 15:47
加载中...