40分隔着wa
查看原帖
40分隔着wa
906904
OobugoO楼主2023/8/25 18:57
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<int,int>
const int N=5e5+50;
const int M=4e5;
const ll mod=998244353;
const ll inf=(1LL<<31)-1;
const double eps=1e-7;
vector<int> G[N];
int fa[N][22];
int depth[N];
void dfs(int now,int pre){
    fa[now][0]=pre; depth[now]=depth[pre]+1;
    for(int i=1;(1<<i)<=depth[now];i++){
        fa[now][i]=fa[fa[now][i-1]][i-1];
    }
    for(auto x:G[now]){
        if(x!=pre)  dfs(x,now);
    }
}
int LCA(int x,int y){
    if(depth[x]<depth[y])   swap(x,y);
    while(depth[x]>depth[y])
        x=fa[x][(int)log2(depth[x]-depth[y])];
    if(x==y)    return x;
    for(int i=(int)log2(depth[x])-1;i>=0;i--){
        if(fa[x][i]!=fa[y][i]){
            x=fa[x][i];
            y=fa[y][i];
        }
    }
    return fa[x][0];
}
void solve(){
    int n,m,s;
    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,0);
    while(m--){
        int x,y;
        cin>>x>>y;
        cout<<LCA(x,y)<<endl;
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t=1;//cin>>t;
    while(t--) solve();
    return 0;
}
2023/8/25 18:57
加载中...