#include<bits/stdc++.h> #define N 500010 usingnamespace std;
structEdge { int to, ne; } edges[N << 1]; int h[N], idx = 0;
int fa[N][22]; int dep[N];
int root = 0;
voidadd(int a, int b){ idx++; edges[idx].to = b; edges[idx].ne = h[a]; h[a] = idx; }
voidinit(){ memset(dep, 0x3f, sizeof dep); queue<int> q; dep[0] = 0; dep[root] = 1; q.push(root); while (!q.empty()) { int t = q.front(); q.pop(); for (int i = h[t]; ~i; i = edges[i].ne) { int j = edges[i].to; if (dep[j] > dep[t] + 1) { dep[j] = dep[t] + 1; fa[j][0] = t; q.push(j); for (int k = 1; k <= 21; k++) { fa[j][k] = fa[fa[j][k - 1]][k - 1]; } } } } }
intLCA(int a, int b){ if (dep[a] < dep[b]) swap(a, b); for (int k = 21; k >= 0; k--) { if (dep[fa[a][k]] >= dep[b]) a = fa[a][k]; } if (a == b) return a; for (int k = 21; k >= 0; k--) { if (fa[a][k] != fa[b][k]) { a = fa[a][k]; b = fa[b][k]; } } return fa[a][0]; }
memset(h, -1, sizeof h); int n, m; cin >> n >> m >> root; for (int i = 1; i < n; i++) { int x, y; cin >> x >> y; add(x, y); add(y, x); } init(); while (m--) { int a, b; cin >> a >> b; cout << LCA(a, b) << endl; } return0; }
queue<int> q; depth[0] = 0; depth[root] = 1; q.push(1); while (!q.empty()) { int t = q.front(); q.pop(); for (int i = h[t]; ~i; i = edges[i].ne) { int j = edges[i].to; if (depth[j] > depth[t] + 1) { depth[j] = depth[t] + 1; fa[j][0] = t; q.push(j); for (int k = 1; k <= 19; k++) { fa[j][k] = fa[fa[j][k - 1]][k - 1]; } } } } }
intLCA(int a, int b){ if (depth[a] < depth[b]) swap(a, b); for (int k = 19; k >= 0; k--) { if (depth[fa[a][k]] >= depth[b]) a = fa[a][k]; } if (a == b) return a; for (int k = 19; k >= 0; k--) { if (fa[a][k] != fa[b][k]) { a = fa[a][k]; b = fa[b][k]; } } return fa[a][0]; }
intdfs(int u, int f){ int res = dist[u]; // 当前记录的差分权 for (int i = h[u]; ~i; i = edges[i].ne) { int j = edges[i].to; if (j == f) continue; int t = dfs(j, u); // 获得子树的差分权值 if (t == 0) ans += m; elseif (t == 1) ans++; res += t; // 向上更新,累加子树差分权 } return res; }
int n; cin >> n >> m; for (int i = 1; i < n; i++) { int a, b; cin >> a >> b; add(a, b); add(b, a); } init(1); for (int i = 1; i <= m; i++) { int a, b; cin >> a >> b; int p = LCA(a, b); dist[a]++, dist[b]++, dist[p] -= 2; // 维护树上差分 } dfs(1, -1); cout << ans << endl; return0; }