p3398 仓鼠找sugar (LCA+讨论)
分情况讨论,结果是两条路径有公共点时,深度大的LCA在另一条路径上且另一条路径的两个端点至少其中一个的与深度大的LCA的LCA为那个深度大的LCA
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int u[501000*2],v[500100*2],fir[500000+10],nxt[501000*2],cnt,dfs_clock=0,top[500010],dfn[500100],fa[500100],dep[500100],sz[500100],heason[500100];
void addedge(int ui,int vi){
++cnt;
u[cnt]=ui;
v[cnt]=vi;
nxt[cnt]=fir[ui];
fir[ui]=cnt;
}
void dfs1(int u,int f){
fa[u]=f;
sz[u]=1;
int maxsz=-1;
for(int i=fir[u];i;i=nxt[i]){
if(v[i]==f)
continue;
dep[v[i]]=dep[u]+1;
dfs1(v[i],u);
sz[u]+=sz[v[i]];
if(sz[v[i]]>maxsz){
maxsz=sz[v[i]];
heason[u]=v[i];
}
}
}
void dfs2(int u,int topf){
dfn[u]=++dfs_clock;
top[u]=topf;
if(!heason[u])
return;
dfs2(heason[u],topf);
for(int i=fir[u];i;i=nxt[i]){
if(v[i]==fa[u])
continue;
if(v[i]!=heason[u])
dfs2(v[i],v[i]);
}
}
int lca(int x,int y){
while(top[x]!=top[y])
(dep[top[x]]<dep[top[y]])?y=fa[top[y]]:x=fa[top[x]];
return (dep[x]<dep[y])?x:y;
}
int ison(int x,int y,int a,int b){
int Lca1=lca(x,y),Lca2=lca(a,b);
if(dep[Lca1]<dep[Lca2])
swap(Lca2,Lca1),swap(x,a),swap(y,b);
return (lca(Lca1,a)==Lca1||lca(Lca1,b)==Lca1);
}
int main(){
int n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<n;i++){
int a,b;
scanf("%d %d",&a,&b);
addedge(a,b);
addedge(b,a);
}
dfs1(1,0);
dfs2(1,1);
for(int i=1;i<=m;i++){
int x,y,a,b;
scanf("%d %d %d %d",&x,&y,&a,&b);
printf("%c\n",(ison(x,y,a,b))?'Y':'N');
}
return 0;
}