[LCA]P3398 仓鼠找sugar

P3398 仓鼠找sugar

如果两条路径相交,那么一定有一条路径的LCA在另一条路径上

而判断一个节点x,是否在路径s-t上需要满足如下几个条件

    - deep[x]>=deep[LCA(s,t)]

    - LCA(s,x)=x或LCA(t,x)=x;
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<vector>
#include<stdlib.h>
#include <math.h>
#define  LL long long
using namespace std;
const int maxn = 5e5 + 10;
int n, m, s;
int k = 0;
int head[maxn], de[maxn], Fa[maxn][21];//de表示节点深度,Fa表示该节点的2的x次方的父节点
int tot = 0;
struct node {
	int nxt;
	int to;
}e[maxn*2];

inline void add(int u, int v) {
	e[++tot].to = v;
	e[tot].nxt = head[u];
	head[u] = tot;
}

inline void dfs(int u, int fa) {
	de[u] = de[fa] + 1;
	Fa[u][0] = fa;
	for (int i = 1; (1 << i) <= de[u]; i++) {
		Fa[u][i] = Fa[Fa[u][i - 1]][i - 1];
	}

	for (int i = head[u], v; i != -1; i = e[i].nxt) {
		v = e[i].to;
		if (v != fa) {
			dfs( v,u );
		}
	}
}
int lca(int a, int b) {
	if (de[a] > de[b]) {
		swap(a, b);
	}
	for (int i = 20; i >= 0; i--) {
		if (de[a] <= de[b]-(1<<i)) {
			b = Fa[b][i];
		}
	}
	if (a == b) return a;
	for (int i = 20; i >= 0; i--) {
		if (Fa[a][i] == Fa[b][i]) {
			continue;
		}
		else {
			a = Fa[a][i];
			b = Fa[b][i];
		}
	}
	return Fa[a][0];

}



int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	memset(head, -1, sizeof(head));
	cin >> n >> m;
	for (int i = 1,x,y; i < n; i++) {
		cin >> x >> y;
		add(x, y);
		add(y, x);
	}
	dfs(1, 0);


	for (int i = 1,a,b,c,d; i <= m; i++) {
		cin >> a >> b >> c >> d;
		int s = lca(a, b); int t = lca(c, d);
		if (de[s] > de[t]) {
			if (lca(c, s) == s || lca(s, d) == s) {
				cout << 'Y' << endl;
			}
			else cout << 'N' << endl;
		}
		else {
			if (lca(a, t) == t || lca(t, b) == t) {
				cout << 'Y' << endl;
			}
			else cout << 'N' << endl;
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值