求树上任意两个点的距离lca

前言:一开始看到这个题目的时候,感觉就和lca有关,但是没有想到具体的公式

d = d e p [ x ] + d e p [ y ] − 2 ∗ d e p [ l c a ( x , y ) ] d = dep[x] + dep[y] - 2*dep[lca(x,y)] d=dep[x]+dep[y]−2∗dep[lca(x,y)]

并且我们这个题目还是一个进阶版本的题,我们还会存在电缆,我们还有两种选择的可能,这也是要考虑在内的


题目地址

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
#define ll long long

const int N = (int)5e5;
int n;
int e[N * 2], ne[N * 2], h[N], idx = 0;
int px, py;
int dep[N], fa[N][20];

inline int read()
{
	int x = 0, f = 1;
	char c = getchar();
	while (c < '0' || c>'9') { if (c == '-') f = -1; c = getchar(); }
	while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0', c = getchar();
	return f * x;
}

void add(int a, int b) {
	e[++idx] = b, ne[idx] = h[a], h[a] = idx;
}

void dfs(int u, int father) {
	dep[u] = dep[father] + 1;
	fa[u][0] = father;
	for (int i = 1; i < 20; i++) {
		fa[u][i] = fa[fa[u][i - 1]][i - 1];
	}
	for (int i = h[u]; i; i = ne[i]) {
		int to = e[i];
		if (to == father) continue;
		dfs(to, u);
	}
}

int lca(int u, int v) {
	if (dep[u] < dep[v]) swap(u, v);
	// 先跳到同一层
	for (int i = 19; i >= 0; i--) {
		if (dep[fa[u][i]] >= dep[v]) u = fa[u][i];
	}
	if (u == v) return u;
	for (int i = 19; i >= 0; i--) {
		if (fa[u][i] != fa[v][i]) {
			u = fa[u][i], v = fa[v][i];
		}
	}return fa[u][0];
}

int fun(int x, int y) {
	return dep[x] + dep[y] - 2 * dep[lca(x, y)];
}

int main() {
	cin >> n;
	for (int i = 1; i < n; i++) {
		int x, y; 
		//cin >> x >> y;
		x = read(); y = read();
		add(x, y), add(y, x);
	}
	cin >> px >> py;
	int q; cin >> q;
	dfs(1, 0);
	while (q--) {
		int x, y; 
		//cin >> x >> y;
		x = read(); y = read();
		int d = min({ fun(x,y),fun(x,px) + fun(y,py),fun(x,py) + fun(y,px) });
		//cout << d << endl;
		printf("%d\n", d);
	}return 0;
}
相关推荐
hweiyu005 分钟前
C++设计模式,高级开发,算法原理实战,系统设计与实战(视频教程)
c++·算法·设计模式
大千AI助手24 分钟前
粒子群优化(PSO)算法详解:从鸟群行为到强大优化工具
人工智能·算法·优化算法·pso·粒子群优化
我叫汪枫1 小时前
C语言深度入门系列:第十一篇 - 动态内存管理与数据结构:程序世界的高效算法大师
c语言·数据结构·算法
Li_7695321 小时前
优选算法100 题 ——1 双指针
算法
77qqqiqi1 小时前
算法——数学基础
算法
啊?啊?1 小时前
7 排序算法通关指南:从 O (n²)(选择 / 冒泡)到 O (nlogn)(快排 / 归并)+ 计数排序
数据结构·算法·排序算法
张较瘦_1 小时前
[论文阅读] 算法 | 抗量子+紧凑!SM3-OTS:基于国产哈希算法的一次签名新方案
论文阅读·算法·哈希算法
芒克芒克1 小时前
LeetCode 面试经典 150 题:多数元素(摩尔投票法详解 + 多解法对比)
算法·leetcode·面试
wow_DG1 小时前
【Vue2 ✨】Vue2 入门之旅 · 进阶篇(二):虚拟 DOM 与 Diff 算法
开发语言·javascript·vue.js·算法·前端框架
和光同尘 、Y_____1 小时前
BRepMesh_IncrementalMesh 重构生效问题
c++·算法·图形渲染