传送门(洛谷)
树链剖分(LCA)
题目分析,如果两个人会在路上相遇,则一个点的LCA一定在另一条链上,也就是        \;\;\; S = l c a ( a , b )    P = l c a ( c , d )      如 果 d e p [ S ] > d e p [ P ] , 则 S 在 c − d 的 路 径 上 S=lca(a,b) \;P=lca(c,d) \;\;如果dep[S]>dep[P],则S在c-d的路径上 S=lca(a,b)P=lca(c,d)如果dep[S]>dep[P],则S在c−d的路径上
如果 d e p [ S ] > d e p [ P ] 且 满 足 l c a ( S , c ) = = S 或 者 l c a ( S , d ) = = S , 则 会 相 遇 dep[S]>dep[P] 且满足lca(S,c)==S或者lca(S,d)==S,则会相遇 dep[S]>dep[P]且满足lca(S,c)==S或者lca(S,d)==S,则会相遇
理由:因为 S S S一定在 c − d c-d c−d的路径上
Code
#include<bits/stdc++.h>
#define rep(i,a,b) for(register int (i)=(a);(i)<=(b);(i)++)
#define don(i,a,b) for(register int (i)=(a);(i)>=(b);(i)--)
using namespace std;
const int maxn=100000+15 ;
const int maxm=1e3+10;
int n,m,q,minn,cnt,rt=0;
int head[maxn],root[maxn],w[maxn];
int son[maxn],top[maxn],size[maxn],id[maxn],wt[maxn],fa[maxn],dep[maxn];
struct node{
int v,nex,w;
}e[maxn<<1];
template <class t> inline void read(t &x)
{
x=0;int f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
while(isdigit(ch)){x=10*x+ch-'0';ch=getchar();}
x*=f;
}
void add(int u,int v) {
e[++cnt].v=v;
e[cnt].nex=head[u];
head[u]=cnt;
}
void dfs1(int u,int f,int deep) {
size[u]=1;
fa[u]=f;
dep[u]=deep;
int maxson=-1;
for(int i=head[u];~i;i=e[i].nex) {
int v=e[i].v;
if(v==f) continue;
dfs1(v,u,deep+1);
size[u]+=size[v];
if(size[v]>maxson) {
son[u]=v;
maxson=size[v];
}
}
}
void dfs2(int u,int topf) {
top[u]=topf;
id[u]=++cnt;
wt[cnt]=u;
if(!son[u]) return;
dfs2(son[u],topf);
for(int i=head[u];~i;i=e[i].nex) {
int v=e[i].v;
if(v==fa[u] || v==son[u]) continue;
dfs2(v,v);
}
}
void readdata() {
memset(head,-1,sizeof(head));
read(n),read(m);
rep(i,1,n-1) {
int x,y;
read(x),read(y);
root[y]++;
add(x,y);
add(y,x);
}
cnt=0;
dfs1(1,0,1);
dfs2(1,1);
}
inline int LCA(int x,int y){
while(top[x]!=top[y]) {
if(dep[top[x]]<dep[top[y]]) swap(x,y);
x=fa[top[x]];
}
if(dep[x]>dep[y]) swap(x,y);
return x;
}
void work() {
rep(i,1,m) {
int a,b,c,d;
cin>>a>>b>>c>>d;
int S=LCA(a,b);
int T=LCA(c,d);
/* printf("%d %d\n",S,T);*/
if(dep[S]<dep[T]){
swap(S,T);
swap(a,c);
swap(b,d);
}
if(LCA(S,c)==S||LCA(S,d)==S) cout<<"Y"<<endl;
else cout<<"N"<<endl;
}
}
int main() {
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
readdata();
work();
return 0;
}