#include <bits/stdc++.h>
using namespace std;
const int N=500005;
vector<int> a[N];
int n, m, s, u1, v1, dep[N], f[N][27];
void dfs(int u, int fa)
{
dep[u]=dep[fa]+1;
f[u][0]=fa;
for (int i=1; i<=25; i++) f[u][i]=f[f[u][i-1]][i-1];
for (int i=0; i<a[u].size(); i++)
{
int v=a[u][i];
if (v==fa) continue;
dfs(v, u);
}
}
int Lca(int x, int y)
{
if (dep[x]<dep[y]) swap(x, y);
for (int i=25; i>=0; i--)
if (dep[f[x][i]]>=dep[y]) x=f[x][i];
if (x==y) return x;
for (int i=25; i>=0; i--)
if (f[x][i]!=f[y][i]) x=f[x][i], y=f[y][i];
return f[x][0];
}
int main()
{
scanf("%d%d%d", &n, &m, &s);
for (int i=1; i<n; i++)
{
scanf("%d%d", &u1, &v1);
a[u1].push_back(v1);
a[v1].push_back(u1);
}
dfs(s, 0);
while (m--)
{
scanf("%d%d", &u1, &v1);
printf("%d\n", Lca(u1, v1));
}
return 0;
}
上面的代码可以AC。下面的却不行
#include <bits/stdc++.h>
using namespace std;
const int N=500005;
vector<int> a[N];
int n, m, s, u1, v1, dep[N], f[N][27];
void dfs(int u, int fa)
{
f[u][0]=fa;
for (int i=1; i<=25; i++) f[u][i]=f[f[u][i-1]][i-1];
for (int i=0; i<a[u].size(); i++)
{
int v=a[u][i];
if (v==fa) continue;
dep[v]=dep[u]+1;
dfs(v, u);
}
}
int Lca(int x, int y)
{
if (dep[x]<dep[y]) swap(x, y);
for (int i=25; i>=0; i--)
if (dep[f[x][i]]>=dep[y]) x=f[x][i];
if (x==y) return x;
for (int i=25; i>=0; i--)
if (f[x][i]!=f[y][i]) x=f[x][i], y=f[y][i];
return f[x][0];
}
int main()
{
scanf("%d%d%d", &n, &m, &s);
for (int i=1; i<n; i++)
{
scanf("%d%d", &u1, &v1);
a[u1].push_back(v1);
a[v1].push_back(u1);
}
dfs(s, 0);
while (m--)
{
scanf("%d%d", &u1, &v1);
printf("%d\n", Lca(u1, v1));
}
return 0;
}
二者唯一的区别在于更新dep数组的不同。我感觉没影响啊。