(LCA + 差分 , 才80分 , 还T了两点 )
#include<bits/stdc++.h>
using namespace std ;
const int Maxs = 5000010 , P = 28 , TIL = ( 1 << 28 ) ;
struct Node { int V , Next ; } tree[Maxs] ;
int Fa[Maxs] , DP[Maxs][P] , DEP[Maxs] ;
int Box[Maxs] , E = 1 ;
int X , Y , S ;
int N , K ;
void ADD(int X , int Y) {
tree[E].Next = Box[X] ;
tree[E].V = Y ;
Box[X] = E ++ ;
}
void DFS(int X , int F , int H) {
Fa[X] = F ;
DEP[X] = H ;
DP[X][0] = F ;
for(int i = Box[X] ; i ; i = tree[i].Next) {
int V = tree[i].V ;
if(V == F) continue ;
DFS(V , X , H + 1 ) ;
}
}
void ST( ) {
for(int l = 1 ; l <= P - 1 ; l ++ )
for(int i = 1 ; i <= N ; i ++ )
DP[i][l] = DP[DP[i][l - 1]][l - 1] ;
}
int LCA(int X , int Y) {
if(DEP[X] <= DEP[Y] - 1) {
X = X + Y ;
Y = X - Y ;
X = X - Y ;
}
for(int i = P - 1 ; i >= 0 ; i -- )
if(DEP[DP[X][i]] >= DEP[Y]) X = DP[X][i] ;
if(X == Y) return X ;
for(int i = P - 1 ; i >= 0 ; i -- )
if(DP[X][i] != DP[Y][i]) X = DP[X][i] , Y = DP[Y][i] ;
return Fa[X] ;
}
int main() {
cin >> N >> K ;
for(int i = 1 ; i <= N - 1 ; i ++ ) {
cin >> X >> Y ;
ADD(X , Y) ;
ADD(Y , X) ;
}
DFS(1 , 1 , 1) ; ST( ) ;
while(K -- ) {
int L , Ans ;
cin >> X >> Y >> S ;
int P1 = LCA(X , Y) , P2 = LCA(X , S) , P3 = LCA(Y , S) ;
if(P1 == P2) L = P3 ;
else if(P1 == P3) L = P2 ;
else if(P2 == P3) L = P1 ;
Ans = DEP[X] + DEP[Y] + DEP[S] - DEP[P1] - DEP[P2] - DEP[P3] ;
printf("%d %d\n" , L , Ans) ;
}
return 0 ;
}
麻烦大佬们抽出点时间来帮我康康 谢谢