点的距离
题目描述
思路
lca 模板题
代码
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX = 1e5 + 5;
int n, m;
int head[MAX], ver[MAX << 1], nxt[MAX << 1], ht;
int dep[MAX], fa[MAX][22];
void add(int x, int y) {
nxt[++ht] = head[x], head[x] = ht, ver[ht] = y;
}
inline int read() {
int s = 0;
char ch = getchar();
while (ch < '0' || ch > '9') ch = getchar();
while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s;
}
void dfs(int x, int u) {
fa[x][0] = u;
dep[x] = dep[u] + 1;
for (int i = 1; i <= 20; ++i) fa[x][i] = fa[fa[x][i - 1]][i - 1];
for (int i = head[x], j; i; i = nxt[i]) {
j = ver[i];
if (j == u) continue;
dfs(j, x);
}
}
int lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
for (int i = 20; i >= 0; --i) {
if (dep[fa[x][i]] >= dep[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 dist(int a, int b) {
return dep[a] + dep[b] - (dep[lca(a, b)] << 1);
}
int main() {
n = read();
for (int i = 1, a, b; i < n; ++i) {
a = read(), b = read();
add(a, b), add(b, a);
}
dfs(1, 0);
m = read();
for (int i = 1, a, b; i <= m; ++i) {
a = read(), b = read();
printf("%d\n", dist(a, b));
}
return 0;
}