1 solutions

  • 0
    @ 2026-11-20 16:48:10

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    vector<int> G[500010];
    int z[500010][30],depth[500010];
    int len;
    void dfs(int x,int fa,int dep){
    	depth[x] = dep;
    	z[x][0] = fa;
    	for (int i=1;i<=len;i++){
    		z[x][i] = z[z[x][i-1]][i-1];
    	}
    	for (int i=0;i<G[x].size();i++){
    		if (G[x][i]!=fa){
    			dfs(G[x][i],x,dep+1);
    		}
    	}
    	return;
    }
    int LCA(int a,int b){
    	if (depth[a]<depth[b]){
    		swap(a,b);
    	}
    	for (int i=len;i>=0 && depth[a]>depth[b];i--){
    		if (depth[z[a][i]]>=depth[b]){
    			a = z[a][i];
    		}
    	}
    	if (a==b){
    		return a;
    	}
    	for (int i=len;i>=0;i--){
    		if (z[a][i]!=z[b][i]){
    			a = z[a][i];
    			b = z[b][i];
    		}
    	}
    	return z[a][0];
    }
    int main(){
    	int N,M,S,x,y,a,b;
    	scanf("%d%d%d",&N,&M,&S);
    	len = log2(N)+1;
    	for (int i=1;i<N;i++){
    		scanf("%d%d",&x,&y);
    		G[x].push_back(y);
    		G[y].push_back(x);
    	}
    	dfs(S,0,1);
    	for (int i=1;i<=M;i++){
    		scanf("%d%d",&a,&b);
    		printf("%d\n",LCA(a,b));
    	}
    	return 0;
    }
    
    • 1

    Information

    ID
    397
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    10
    Tags
    # Submissions
    2
    Accepted
    1
    Uploaded By