一样远
题目背景:
分析:LCA + 情况讨论
对于两个点A,B我们来找它的路径中点,如果不是LCA那么显然的满足条件的就是LCA以及它的不是A的祖先,也不是B的祖先的儿子的size和,如果是LCA,那么就是LCA的size减去是A的祖先的儿子的size,再减去是B的祖先的儿子的size,那么如何找到这个儿子呢,我们考虑倍增,先找LCA然后找到AB间的距离dis,当dis为奇数的时候,显然不存在这样的点,当dis为偶数的时候,将AB两个点中,深度较深的点往上倍增跳(dis / 2 - 1)步,判断它的父亲是否为LCA即可。
Source:
/*
created by scarlyw
*/
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cctype>
#include <set>
#include <map>
#include <vector>
#include <queue>
const int MAXN = 100000 + 10;
int n, q, x, y, z, dis;
int size[MAXN], dep[MAXN], father[MAXN][18];
std::vector<int> edge[MAXN];
inline void add_edge(int x, int y) {
edge[x].push_back(y), edge[y].push_back(x);
}
inline void dfs(int cur, int fa) {
size[cur] = 1, dep[cur] = dep[fa] + 1, father[cur][0] = fa;
for (int i = 1; i < 18; ++i)
father[cur][i] = father[father[cur][i - 1]][i - 1];
for (int p = 0; p < edge[cur].size(); ++p) {
int v = edge[cur][p];
if (v != fa) dfs(v, cur), size[cur] += size[v];
}
}
inline int query_lca(int u, int v) {
if (dep[u] < dep[v]) std::swap(u, v);
for (int i = 17; i >= 0; --i)
if (dep[father[u][i]] >= dep[v])
u = father[u][i];
if (u == v) return u;
for (int i = 17; i >= 0; --i)
if (father[u][i] != father[v][i])
u = father[u][i], v = father[v][i];
return father[u][0];
}
inline int get_on(int x, int dis) {
for (int i = 17; i >= 0; --i)
if (dis >= (1 << i)) x = father[x][i], dis -= (1 << i);
return x;
}
inline void solve_query() {
scanf("%d", &q), dfs(1, 0);
while (q--) {
scanf("%d%d", &x, &y);
if (x == y) {
std::cout << n << '\n';
continue ;
}
z = query_lca(x, y), dis = (dep[x] + dep[y] - 2 * dep[z]);
if (dep[x] < dep[y]) std::swap(x, y);
if (dis & 1) {
std::cout << "0" << '\n';
continue ;
}
dis /= 2, x = get_on(x, dis - 1);
if (father[x][0] != z) std::cout << size[father[x][0]] - size[x];
else y = get_on(y, dis - 1), std::cout << n - size[x] - size[y];
std::cout << '\n';
}
}
inline void read_in() {
scanf("%d", &n);
for (int i = 1; i < n; ++i) scanf("%d%d", &x, &y), add_edge(x, y);
}
int main() {
// freopen("equal.in", "r", stdin);
// freopen("equal.out", "w", stdout);
read_in();
solve_query();
return 0;
}