树剖求LCA
我们可以发现,两条路径ab,cd相交,当且仅当 dep[lca(a,b)]>=dep[lca(c,d)]&(lca(lca(a,b),c)lca(a,b)||lca(lca(a,b),d)lca(a,b))或把abcd交换一下即可
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
using namespace std;
const int MAXN=200005;
int init(){
int rv=0,fh=1;
char c=getchar();
while(c<'0'||c>'9'){
if(c=='-') fh=-1;
c=getchar();
}
while(c>='0'&&c<='9'){
rv=(rv<<1)+(rv<<3)+c-'0';
c=getchar();
}
return rv*fh;
}
int head[MAXN],dep[MAXN],fa[MAXN],siz[MAXN],son[MAXN],n,m,nume,top[MAXN],id[MAXN],ind;
struct edge{
int to,nxt;
}e[MAXN<<1];
void adde(int from,int to){
e[++nume].to=to;
e[nume].nxt=head[from];
head[from]=nume;
}
void dfs1(int u,int rt){
fa[u]=rt;
dep[u]=dep[rt]+1;
siz[u]=1;
int ma=0;
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].to;
if(v==rt) continue;
dfs1(v,u);
siz[u]+=siz[v];
if(ma<siz[v]){
ma=siz[v];
son[u]=v;
}
}
}
void dfs2(int u,int topf){
top[u]=topf;
id[u]=++ind;
if(!son[u]) return;
dfs2(son[u],topf);
for(int i=head[u];i;i=e[i].nxt){
int v=e[i].to;
if(v==fa[u]||v==son[u]) continue;
dfs2(v,v);
}
}
int LCA(int a,int b){
while(top[a]!=top[b]){
if(dep[top[a]]>dep[top[b]]) a=fa[top[a]];
else b=fa[top[b]];
}
return dep[a]>dep[b]?b:a;
}
int main(){
n=init();m=init();
for(int i=1;i<n;i++){
int u=init(),v=init();
adde(u,v);adde(v,u);
}
dep[1]=1;
dfs1(1,0);
dfs2(1,1);
for(int i=1;i<=m;i++){
int a=init(),b=init(),c=init(),d=init();
int r1=LCA(a,b),r2=LCA(c,d);
if(dep[r1]<dep[r2]){
swap(r1,r2);
swap(a,c);
swap(b,d);
}
if(LCA(r1,c)==r1||LCA(r1,d)==r1) cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
return 0;
}