【题解】

  题意就是判断树上两条链是否有交。口诀是“判有交,此链有彼祖”。即其中一条链的端点的Lca在另一条链上。

  我们设两条链的端点的Lca中深度较大的为L2,对L2与另一条链的两个端点分别求Lca,若满足其中一个Lca等于L2,即表示两链有交。

  

 #include<cstdio>
#include<algorithm>
#include<cstring>
#define LL long long
#define rg register
#define N 500010
using namespace std;
int n,m,tot,last[N],siz[N],fa[N],dep[N],hvy[N],top[N];
struct edge{
int to,pre;
}e[N<<];
inline int read(){
int k=,f=; char c=getchar();
while(c<''||c>'')c=='-'&&(f=-),c=getchar();
while(''<=c&&c<='')k=k*+c-'',c=getchar();
return k*f;
}
void dfs1(int x){
siz[x]=; dep[x]=dep[fa[x]]+;
for(rg int i=last[x],to;i;i=e[i].pre)if((to=e[i].to)!=fa[x]){
fa[to]=x; dfs1(to); siz[x]+=siz[to];
if(siz[to]>siz[hvy[x]]) hvy[x]=to;
}
}
void dfs2(int x,int tp){
top[x]=tp;
if(hvy[x]) dfs2(hvy[x],tp);
for(rg int i=last[x],to;i;i=e[i].pre)if((to=e[i].to)!=fa[x]&&to!=hvy[x])
dfs2(to,to);
}
inline int lca(int x,int y){
int t1=top[x],t2=top[y];
while(t1!=t2){
if(dep[t1]<dep[t2]) swap(t1,t2),swap(x,y);
x=fa[t1]; t1=top[x];
}
return dep[x]<dep[y]?x:y;
}
int main(){
n=read(); m=read();
for(rg int i=;i<n;i++){
int u=read(),v=read();
e[++tot]=(edge){v,last[u]}; last[u]=tot;
e[++tot]=(edge){u,last[v]}; last[v]=tot;
}
dfs1(); dfs2(,);
while(m--){
int a=read(),b=read(),x=read(),y=read();
int L1=lca(a,b),L2=lca(x,y);
if(dep[L1]>dep[L2]) swap(L1,L2),swap(a,x),swap(b,y);
puts(lca(L2,a)==L2||lca(L2,b)==L2?"Y":"N");
}
return ;
}

  

最新文章

  1. Android的setVisibility(View.GONE)无效的问题及原因分析(转)
  2. 【荐】怎么用PHP发送HTTP请求(POST请求、GET请求)?
  3. 【笔记】select2的使用
  4. U3D assetbundle加载
  5. java 判断某一天是当年的哪一天
  6. Web —— 小技巧集
  7. SQL 中的好习惯和坏习惯
  8. CAS实现单点登录流程
  9. uva 10245 近期点对问题
  10. Java filter拦截器的使用
  11. python2和python3的一些差别
  12. TypeScript系列 - 什么是TypeScript
  13. js 获取随机数 Math.random()
  14. Linux磁盘性能分析(CentOS)
  15. Cracking The Coding Interview 1.7
  16. js 加alert后才能执行方法
  17. DOM API详解
  18. sessionStorage 、localStorage、cookie
  19. SQLSERVER SQL备份还原代码C#
  20. I.MX6 Manufacturing Tool V2 (MFGTool2) ucl2.xml hacking

热门文章

  1. bzoj3884
  2. Ubuntu搭建Eclipse+JDK+SDK的Android (转载)
  3. P4128 [SHOI2006]有色图
  4. 使用printf和String.format格式化输出
  5. JS制作一个创意数字时钟
  6. Java多线程(八) synchronized 抛出异常锁自动解除
  7. PowerDesigner连接Oracle数据库(32位)反向生成物理数据模型
  8. 299 Bulls and Cows 猜数字游戏
  9. JOptionPane.showMessageDialog出现在浏览器下面的解决方法
  10. Laravel5.1学习笔记23 Eloquent 序列化