P3398 仓鼠找sugar 树上路径相交判断

(color{#0066ff}{题目描述})

小仓鼠的和他的基(mei)友(zi)sugar住在地下洞穴中,每个节点的编号为1~n。地下洞穴是一个树形结构。这一天小仓鼠打算从从他的卧室(a)到餐厅(b),而他的基友同时要从他的卧室(c)到图书馆(d)。他们都会走最短路径。现在小仓鼠希望知道,有没有可能在某个地方,可以碰到他的基友?

小仓鼠那么弱,还要天天被zzq大爷虐,请你快来救救他吧!

(color{#0066ff}{输入格式})

第一行两个正整数n和q,表示这棵树节点的个数和询问的个数。

接下来n-1行,每行两个正整数u和v,表示节点u到节点v之间有一条边。

接下来q行,每行四个正整数a、b、c和d,表示节点编号,也就是一次询问,其意义如上。

(color{#0066ff}{输出格式})

对于每个询问,如果有公共点,输出大写字母“Y”;否则输出“N”。

(color{#0066ff}{输入样例})

5 5
2 5
4 2
1 3
1 4
5 1 5 1
2 2 1 4
4 1 3 4
3 1 1 5
3 5 1 4

(color{#0066ff}{输出样例})

Y
N
Y
Y
Y

(color{#0066ff}{数据范围与提示})

本题时限1s,内存限制128M,因新评测机速度较为接近NOIP评测机速度,请注意常数问题带来的影响。

20%的数据 n<=200,q<=200

40%的数据 n<=2000,q<=2000

70%的数据 n<=50000,q<=50000

100%的数据 n<=100000,q<=100000

(color{#0066ff}{题解})

容易发现, 两条路径相交,那么一定有一条路径的LCA在另一条路径上

判断x是否在s到t的路径上,要满足两个条件

1、x比s和t的lca深

2、x和s 或 x和t 的lca等于x

所以分情况讨论就行了

#include <bits/stdc++.h>

#define LL long long

const int maxn = 100500;

LL in() {
	char ch; LL x = 0, f = 1;
	while(!isdigit(ch = getchar()))(ch == '-') && (f = -f);
	while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
	return x * f;
}

struct node {
	int to;
	node *nxt;
	node(int to = 0, node *nxt = NULL):to(to), nxt(nxt) {}
	void *operator new (size_t) {
		static node *S = NULL, *T = NULL;
		return (S == T) && (T = (S = new node[1024]) + 1024), S++;
	}
};

node *head[maxn];
int f[maxn][25], dep[maxn];
int n, q;

void add(int from, int to) {
	node *o = new node(to, head[from]);
	head[from] = o;
}

void dfs(int x, int fa) {
	dep[x] = dep[fa] + 1;
	f[x][0] = fa;
	for(node *i = head[x]; i; i = i->nxt)
		if(i->to != fa) dfs(i->to, x);
}

void beizeng() {
	dfs(1, 0);
	for(int j = 1; j <= 21; j++)
		for(int i = 1; i <= n; i++)
			f[i][j] = f[f[i][j - 1]][j - 1];
}

int LCA(int x, int y) {
	if(dep[x] < dep[y]) std::swap(x, y);
	for(int i = 21; ~i; i--) if(dep[f[x][i]] >= dep[y]) x = f[x][i];
	if(x == y) return x;
	for(int i = 21; ~i; i--) if(f[x][i] != f[y][i]) x = f[x][i], y = f[y][i];
	return f[x][0];
}

int main() {
	n = in(), q = in();
	int x, y, s, t, lca1, lca2;
	for(int i = 1; i < n; i++) {
		x = in(), y = in();
		add(x, y), add(y, x);
	}
	beizeng();
	while(q--) {
		x = in(), y = in(), s = in(), t = in();
		lca1 = LCA(x, y);
		lca2 = LCA(s, t);
		if(dep[lca1] < dep[lca2]) {
			std::swap(lca1, lca2);
			std::swap(x, s);
			std::swap(y, t);
		}
		if(LCA(lca1, s) == lca1 || LCA(lca1, t) == lca1) printf("Y
");
		else printf("N
");
	}
	return 0;
}
原文地址:https://www.cnblogs.com/olinr/p/10139970.html