得分100,RE两个点,hydroOJ上提交是AC的,搞不懂,求神犇调代码
#include <bits/stdc++.h>
using namespace std;
int n, m, root;
vector<vector<int>> g, anc;
vector<int> dep, lg2;
int maxd = 0;
void dfs(int x,int fa,int d) {
dep[x] = d;
maxd = max(maxd, d);
anc[x][0] = fa;
for (auto&& i : g[x])
if (i != fa) dfs(i, x, d + 1);
}
int LCA(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
while (dep[x] > dep[y]) x = anc[x][lg2[dep[x] - dep[y]]];
if (x == y) return x;
for (int i = lg2[dep[x]-1]; i >= 0; i--)
if (anc[x][i] != anc[y][i]) x = anc[x][i], y = anc[y][i];
return anc[x][0];
}
int main() {
scanf("%d %d %d", &n, &m, &root);
dep.resize(n + 1), g.resize(n + 1), anc.resize(n + 1, vector<int>(1));
for (int i = 0; i < n - 1; i++)
{
int x, y;
scanf("%d %d", &x, &y);
g[x].push_back(y), g[y].push_back(x);
}
dfs(root, 0, 1);
lg2.resize(maxd);
for (int i = 1; i < maxd; i++)
lg2[i] = lg2[i - 1] + (1 << (lg2[i - 1] + 1) == i);
maxd = lg2[maxd - 1];
for (int i = 1; i <= maxd; i++)
for (int j = 1; j <= n; j++)
if (dep[j] - 1 >= (1 << i)) anc[j].push_back(anc[anc[j][i - 1]][i - 1]);
for (int i = 0; i < m; i++)
{
int x, y;
scanf("%d %d", &x, &y);
printf("%d\n", LCA(x, y));
}
return 0;
}