P3398 仓鼠找sugar

3 篇文章 0 订阅
3 篇文章 0 订阅

传送门(洛谷)

树链剖分(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]Scd

如果 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)==Slca(S,d)==S

理由:因为 S S S一定在 c − d c-d cd的路径上

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值