其他分享
首页 > 其他分享> > 【luogu P4320】道路相遇(圆方树)

【luogu P4320】道路相遇(圆方树)

作者:互联网

道路相遇

题目链接:luogu P4320

题目大意

给你一个无向连通图,无重边自环,然后每次给你两点,问你有多少个点是两点间路径必有的。

思路

圆方树pre模板题?

圆方树怎么做这里不说,看铁人两项的博客。

那我们知道圆方树的性质就是圆点方点是固定的,而且圆点是原图的点。
那代表着圆点的数量就是必须走的点的数量,也就是(链的数量+1)/2。
没了。

代码

#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>

using namespace std;

const int N = 5e5 + 100;
int n, m, q;
vector <int> G[N];

struct YF_tree {
	int dfn[N], low[N], deg[N << 1], fa[N << 1][21], sta[N], tot;
	vector <int> GG[N << 1];
	
	void link(int x, int y) {GG[x].push_back(y); GG[y].push_back(x);}
	
	void tarjan(int now) {
		dfn[now] = low[now] = ++dfn[0]; sta[++sta[0]] = now;
		for (int i = 0; i < G[now].size(); i++) {int x = G[now][i];
			if (!dfn[x]) {
				tarjan(x); low[now] = min(low[now], low[x]);
				if (dfn[now] == low[x]) {
					tot++;
					while (sta[sta[0]] != x) {
						link(tot, sta[sta[0]]);
						sta[0]--;
					}
					link(tot, sta[sta[0]]); sta[0]--;
					link(tot, now);
				}
			}
			else low[now] = min(low[now], dfn[x]);
		}
	}
	
	void dfs(int now, int father) {
		deg[now] = deg[father] + 1; fa[now][0] = father;
		for (int i = 1; i <= 20; i++) fa[now][i] = fa[fa[now][i - 1]][i - 1];
		for (int i = 0; i < GG[now].size(); i++) {int x = GG[now][i];
			if (x != father) {
				dfs(x, now);
			}
		}
	}
	
	void Init() {
		tot = n;
		for (int i = 1; i <= n; i++) if (!dfn[i]) tarjan(i), dfs(i, 0);
	}
	
	int LCA(int x, int y) {
		if (deg[x] < deg[y]) swap(x, y);
		for (int i = 20; i >= 0; i--)
			if (deg[fa[x][i]] >= deg[y]) x = fa[x][i];
		if (x == y) return x;
		for (int i = 20; i >= 0; i--) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
		return fa[x][0];
	}
	
	int quest(int x, int y) {
		int lca = LCA(x, y), dis = deg[x] + deg[y] - deg[fa[lca][0]] * 2;
		return (dis + 1) / 2;
	}
}T;

int main() {
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= m; i++) {
		int x, y; scanf("%d %d", &x, &y);
		G[x].push_back(y); G[y].push_back(x);
	}
	
	T.Init();
	
	scanf("%d", &q);
	for (int i = 1; i <= q; i++) {
		int x, y; scanf("%d %d", &x, &y);
		printf("%d\n", T.quest(x, y));
	}
	
	return 0;
}

标签:return,int,luogu,fa,圆方树,P4320,include,deg
来源: https://www.cnblogs.com/Sakura-TJH/p/luogu_P4320.html