LCA。注意细节。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxv 500500 #define maxe 1005000 using namespace std; int n,m,x,y,z,g[maxv],nume=0,anc[maxv][23],dis[maxv]; struct edge { int v,nxt; }e[maxe]; void addedge(int u,int v) { e[++nume].v=v; e[nume].nxt=g[u]; g[u]=nume; } void dfs(int x) { for (int ee=1;ee<=20;ee++) anc[x][ee]=anc[anc[x][ee-1]][ee-1]; for (int i=g[x];i;i=e[i].nxt) { int v=e[i].v; if (v!=anc[x][0]) { anc[v][0]=x;dis[v]=dis[x]+1; dfs(v); } } } int lca(int x,int y) { if (dis[x]<dis[y]) swap(x,y); for (int e=20;e>=0;e--) { if ((dis[anc[x][e]]>=dis[y]) && (anc[x][e]!=0)) x=anc[x][e]; } if (x==y) return x; for (int ee=20;ee>=0;ee--) { if (anc[x][ee]!=anc[y][ee]) { x=anc[x][ee]; y=anc[y][ee]; } } return anc[x][0]; } int get_dis(int x,int y) { int k=lca(x,y); return dis[x]+dis[y]-2*dis[k]; } int main() { scanf("%d%d",&n,&m); for (int i=1;i<=n-1;i++) { scanf("%d%d",&x,&y); addedge(x,y); addedge(y,x); } dfs(1); for (int i=1;i<=m;i++) { scanf("%d%d%d",&x,&y,&z); int t1,t2,t3; t1=lca(x,y);t2=lca(x,z);t3=lca(y,z); int ans1,ans2=0; if (t1==t2) ans1=t3; else if (t1==t3) ans1=t2; else ans1=t1; ans2=get_dis(x,ans1)+get_dis(y,ans1)+get_dis(z,ans1); printf("%d %d ",ans1,ans2); } return 0; }