解题报告:
这题其实就是求lca(最近公共祖先)
计算出A->1的距离dist1
计算出B->C->1的距离dist2
如果dist1<dist2 也就是A先到根节点就是YES
如果dist1==dist2 我们这里要看一下lca(a,c)是不是1 如果是的话 说明他们是从根节点的两个子树过去的,在达到根节点之前不会碰到,就输出NO,如果lca!=1,因为距离还一样,他们一定会在lca(a,c)碰面 就输出YES
如果dist1>dist2 就输出NO
#define first f
#define second s
#define ll long long
#define mp make_pair
#define pb push_back
#define pf push_front
#define lb lower_bound
#define ub upper_bound
#define pii pair<int,int>
#include <bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int MOD=1e9+7;
const int maxn=1e5+5;
const double eps=1e-9;
const int inf=0x3f3f3f3f;
const double PI=acos(-1.0);
const double e=2.718281828459;
struct node
{
int to,next;
}edge[maxn<<1];
int head[maxn<<1],cnt,deep[maxn],f[maxn][25];
void add(int from,int to)
{
edge[++cnt].next=head[from];
edge[cnt].to=to;
head[from]=cnt;
}
void dfs(int now,int pre)
{
deep[now]=deep[pre]+1;
f[now][0]=pre;
for(int i=1;i<=20;i++){
f[now][i]=f[f[now][i-1]][i-1];
}
for(int i=head[now];~i;i=edge[i].next){
int to=edge[i].to;
if(to==pre){continue;}
dfs(to,now);
}
}
int LCA(int x,int y)
{
if(deep[x]<deep[y]){swap(x,y);}
for(int i=20;i>=0;i--){
if(deep[f[x][i]]>=deep[y]){x=f[x][i];}
}
if(x==y){return x;}
for(int i=20;i>=0;i--){
if(f[x][i]!=f[y][i]){
x=f[x][i];
y=f[y][i];
}
}
return f[x][0];
}
int main()
{
int T,n,q,u,v,a,b,c;
scanf("%d",&T);
while(T--){
mem(head,-1);deep[0]=-1;cnt=0;
scanf("%d%d",&n,&q);
for(int i=1;i<n;i++){
scanf("%d%d",&u,&v);
add(u,v);add(v,u);
}
dfs(1,0);
while(q--){
scanf("%d%d%d",&a,&b,&c);
u=deep[b]+2*deep[c]-2*deep[LCA(b,c)],v=deep[a];
if(u>v){printf("YES\n");}
else if(u==v){
if(LCA(a,c)!=1){printf("YES\n");}
else{printf("NO\n");}
}
else{printf("NO\n");}
}
}
return 0;
}