洛谷 3398 仓鼠找sugar 【模板】判断树上两链有交
2024-09-30 22:54:15
【题解】
题意就是判断树上两条链是否有交。口诀是“判有交,此链有彼祖”。即其中一条链的端点的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 ;
}
最新文章
- Android的setVisibility(View.GONE)无效的问题及原因分析(转)
- 【荐】怎么用PHP发送HTTP请求(POST请求、GET请求)?
- 【笔记】select2的使用
- U3D assetbundle加载
- java 判断某一天是当年的哪一天
- Web —— 小技巧集
- SQL 中的好习惯和坏习惯
- CAS实现单点登录流程
- uva 10245 近期点对问题
- Java filter拦截器的使用
- python2和python3的一些差别
- TypeScript系列 - 什么是TypeScript
- js 获取随机数 Math.random()
- Linux磁盘性能分析(CentOS)
- Cracking The Coding Interview 1.7
- js 加alert后才能执行方法
- DOM API详解
- sessionStorage 、localStorage、cookie
- SQLSERVER SQL备份还原代码C#
- I.MX6 Manufacturing Tool V2 (MFGTool2) ucl2.xml hacking
热门文章
- bzoj3884
- Ubuntu搭建Eclipse+JDK+SDK的Android (转载)
- P4128 [SHOI2006]有色图
- 使用printf和String.format格式化输出
- JS制作一个创意数字时钟
- Java多线程(八) synchronized 抛出异常锁自动解除
- PowerDesigner连接Oracle数据库(32位)反向生成物理数据模型
- 299 Bulls and Cows 猜数字游戏
- JOptionPane.showMessageDialog出现在浏览器下面的解决方法
- Laravel5.1学习笔记23 Eloquent 序列化