30%

60%访

100%lca

  注意数组大小

代码:

烟火再美,总抵不过你的一往情深
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#define MAXN 1000100
using namespace std;
int n,m,c;
int head[MAXN<<1],dep[MAXN],f[MAXN][20],cnt,T;
int x1,x2,y1,y2;
struct node {int nxt,to; }e[MAXN<<1];
int read()
{
	int x=0,f=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*f;
}
void add(int from,int to)
{
	e[++cnt]=(node) {head[from],to};
	head[from]=cnt;
}
void clear()
{
	memset(e,0,sizeof(e));
	memset(head,0,sizeof(head));
	memset(dep,0,sizeof(dep));
	memset(f,0,sizeof(f));
}
void buildtree(int rot)
{
    for(int i=head[rot];i;i=e[i].nxt)
	{
        int y=e[i].to;
        if(!dep[y])
		{
            dep[y]=dep[rot]+1;
            f[y][0]=rot;
            buildtree(y);
        }
    }
}
int LCA(int x,int y)
{
    if(dep[x]<dep[y])swap(x,y);
    for(int i=19;i>=0;i--)
    if(dep[f[x][i]]>=dep[y])x=f[x][i];
    if(x==y)return x;
    for(int i=19;i>=0;i--)
    if(f[x][i]!=f[y][i])
	{
        x=f[x][i];
		y=f[y][i];
    }
    return f[x][0];
}
void solve()
{
    n=read();m=read();
    for(int i=1,a,b;i<n;i++)
	{
        a=read();b=read();
        add(a,b);add(b,a);
    }
    dep[1]=1;
    buildtree(1);//
    for(int i=1;(1<<i)<=n;i++)
    for(int j=1;j<=n;j++)
    f[j][i]=f[f[j][i-1]][i-1];//
    for(int i=1;i<=m;i++)
	{
        x1=read();y1=read();x2=read();y2=read();
        int fa1=LCA(x1,y1),fa2=LCA(x2,y2);
        if(dep[fa1] < dep[fa2])
		{
            swap(x1,x2);swap(y1,y2);swap(fa1,fa2);
        }
        if(LCA(fa1,x2)==fa1||LCA(fa1,y2)==fa1)printf("YES\n");
        else printf("NO\n");
    }
}
int main()
{
	#ifdef yilnr
	#else
	freopen("railway.in","r",stdin);
	freopen("railway.out","w",stdout);
	#endif
    T=read();
    while(T--)
    {
    	solve();
    	clear();
    }
    return 0;
}
/*
1
4 2
1 2
2 3
3 4
1 2 3 4
1 4 3 2
*/
01-15 08:12