洛谷P3398 仓鼠找sugar

(Large extbf{Description: } large{一棵n个节点的树,有q次询问,每次给出两组出发点与终点,输出这两组路径有没有交点。(n, q leq 10^{5})}\)

(Large extbf{Solution: } large{我们很容易证明:如果两条路径相交,那么一定有一条路径的LCA在另一条路径上。\有了这个结论,我们只需分类讨论一下。}\)

(Large extbf{Code: })

#include <cstdio>
#include <algorithm>
#define LL long long
#define gc() getchar()
#define rep(i, a, b) for (int i = (a); i <= (b); ++i)
using namespace std;
const int N = 1e5 + 5;
int n, cnt, m, head[N], dep[N], lg[N], f[N][20];

struct Edge {
	int to, next;	
}e[N << 1];

inline int read() {
	char ch = gc();
	int ans = 0;
	while (ch > '9' || ch < '0') ch = gc();
	while (ch >= '0' && ch <= '9') ans = (ans << 1 ) + (ans << 3) + ch - '0', ch = gc();
	return ans;
}

inline void add(int x, int y) {
	e[++cnt].to = y;
	e[cnt].next = head[x];
	head[x] = cnt;	
}

inline void dfs(int x, int fa) {
	dep[x] = dep[fa] + 1;
	f[x][0] = fa;
	for (int i = 1; (1 << i) <= dep[x]; ++i) f[x][i] = f[f[x][i - 1]][i - 1];
	for (int i = head[x]; i ; i = e[i].next) if (e[i].to != fa) dfs(e[i].to, x);
}

inline int lca(int x, int y) {
	if (dep[x] < dep[y]) swap(x, y);
	while (dep[x] > dep[y]) x = f[x][lg[dep[x] - dep[y]]];
	if (x == y) return x;
	for (int i = lg[dep[x]]; i >= 0; --i) if (f[x][i] != f[y][i]) x = f[x][i], y = f[x][i];
	return f[x][0];
}

int main() {
	n = read(), m = read();
	int x, y;
	rep(i, 2, n) x = read(), y = read(), add(x, y), add(y, x), lg[i] = lg[i >> 1] + 1;
	dfs(1, 0);
	int a, b;
	while (m--) {
		x = read(), y = read(), a = read(), b = read();
		int l1 = lca(x, y), l2 = lca(a, b);
		if (dep[l1] < dep[l2]) swap(l1, l2), swap(a, x), swap(b, y);
		if (lca(l1, b) == l1 || lca(l1, a) == l1) printf("Y
");
		else printf("N
");
	}
	return 0;
} 
原文地址:https://www.cnblogs.com/Miraclys/p/12485879.html