Borrow Classroom----------------------------------思维(LCA)

Insert picture description here
Insert picture description here
Insert picture description here
Analysis:
Those who meet the conditions must look carefully! ! ! ! ! ! ! ! !

Divided into three cases,
let a1 be lca (a, 1)
let bc be lca (b, c)
let c1 be lca (c, 1)
let ac be lca (a, c) the
first one: lca (a, c ) == 1 Then if a1 <bc + c1 outputs YES, otherwise it outputs NO.
The second type: ac <= bc Then it must be able to intercept the output of the
third type of lca (a, c)! = 1, then a1 <= bc + c1 Then it can be intercepted (the picture is clear at a glance)

Other output NO

#include<bits/stdc++.h> 
using namespace std;
const int N=1e5+100;
vector<int> G[N];
int t,n,q,a,b;
int depth[N],fa[N][20];
void dfs(int root)
{
	memset(depth,0x3f,sizeof depth);
	depth[0]=0;depth[root]=1;
	queue<int> q;
	q.push(root);
	while(q.size())
	{
		int t=q.front();
		q.pop();
		for(auto j :G[t])
		{
			if(depth[j]>depth[t]+1)
			{
				depth[j]=depth[t]+1;
				q.push(j);
				fa[j][0]=t;
				for(int k=1;k<=18;k++) fa[j][k]=fa[fa[j][k-1]][k-1]; 
			}
		}
	}
	
}
int lca(int x,int y)
{
	if(depth[x]<depth[y]) swap(x,y);
	for(int k=18;k>=0;k--) if(depth[fa[x][k]]>=depth[y]) x=fa[x][k];
	if(x==y) return x;
	for(int k=18;k>=0;k--) 
	{
		if(fa[x][k]!=fa[y][k])
		{
			x=fa[x][k];
			y=fa[y][k];
		}
	}
	return fa[x][0];
}
int getdis(int x,int y)
{
	return depth[x]+depth[y]-2*depth[lca(x,y)];
}

int main()
{
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d",&n,&q);
		for(int i=1;i<=n;i++) G[i].clear();
		memset(fa,0,sizeof fa);
		for(int i=1;i<=n-1;i++)
		{
			scanf("%d %d",&a,&b);
			G[a].push_back(b);G[b].push_back(a);
		}
		dfs(1);
		while(q--)
		{
			int c;
			scanf("%d %d %d",&a,&b,&c);
			int a1=getdis(a,1);
			int bc=getdis(c,b);
			int c1=getdis(c,1);
			int ac=getdis(a,c);
			if(a1<bc+c1)
			{
			cout<<"YES"<<endl;
			 } 
			
			 else if(ac<=bc)
			 {
			 cout<<"YES"<<endl;
			 	
			 }
			 else if(lca(a,c)!=1&&a1<=bc+c1)
			 {
			 	cout<<"YES"<<endl;
			 }
			 else cout<<"NO"<<endl;
		}
	 } 
}
Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105388366