voidbfs(){
queue<int> q;
q.push(13), deep[13]=1;while(!q.empty()){int x = q.front();q.pop();for(int i = head[x]; i !=-1; i = edges[i].nex){int y = edges[i].to;if(deep[y])continue;//不走父节点
deep[y]= deep[x]+1;//处理深度
f[y][0]= x;//赋初值 for(int j =1; j < t+1; j++)//倍增DP核心
f[y][j]= f[f[y][j-1]][j-1];
q.push(y);}}}
4.LCA(核心):
intlca(int x,int y){if(deep[x]>deep[y]){int tmp = x;x = y; y = tmp;}for(int i = t; i >-1; i--)if(deep[f[y][i]]>=deep[x])y = f[y][i];//移到同一深度 if(x==y)return x;for(int i = t; i >-1; i--)if(f[x][i]!=f[y][i])x = f[x][i], y = f[y][i];//lca过程 return f[x][0];//最后停在lca的子节点,所以返回父节点 }
5.主程序:
intmain(){freopen("1.in","r",stdin);scanf("%d",&n);memset(head,-1,sizeof(head));int a, b;for(int i =1; i < n; i++){scanf("%d%d",&a,&b);add(a, b);add(b, a);}
t =(int)log2(n)+1;bfs();scanf("%d",&Q);while(Q--){scanf("%d%d",&a,&b);printf("%d\n",lca(a, b));}}