LCA函数中
for (register inti=lg[depth[x]]-1; i>=0; --i)
这段代码改为
for (register inti=lg[depth[x]]-1; i; --i)
本地IDE运行会出错
请问为什么qwq
#include <bits/stdc++.h>
using namespace std;
int lg[10086];
int edge[10086], head[10086], nex[10086];
int tot;
void add (int x, int y)
{
edge[++tot] = y; nex[tot] = head[x]; head[x] = tot;
edge[++tot] = x; nex[tot] = head[y]; head[y] = tot;
}
int depth[10086], f[10086][10086];
void solve (int now, int father)
{
f[now][0] = father;
++depth[now] += depth[father];
for (register int i=1; i<=lg[depth[now]]; ++i)
f[now][i] = f[f[now][i-1]][i-1];
for (register int i=head[now]; i; i=nex[i])
if(edge[i]!=father)
solve(edge[i], now);
}
int LCA (int x, int y)
{
if (depth[x]<depth[y])
swap(x, y);
while (depth[x]>depth[y])
x = f[x][lg[depth[x]-depth[y]]-1];
if (x==y)
return x;
for (register int i=lg[depth[x]]-1; i>=0; --i)
if (f[x][i]!=f[y][i])
x = f[x][i],y=f[y][i];
return f[x][0];
}
signed main (void)
{
cin.tie(0);
ios::sync_with_stdio(false);
int n, m, s;
cin >> n >> m >> s;
for (register int i=1; i<n; ++i)
{
int x, y;
cin >> x >> y;
add(x,y);
}
lg[0] = -1;
for (register int i=1; i<=n; ++i)
{
lg[i] = lg[i>>1] + 1;
}
solve(s,0);
for (register int i=1; i<=m; ++i)
{
int x, y;
cin >> x >> y;
cout << LCA(x,y) << endl;
}
return 0;
}
LCA函数中
for (register inti=lg[depth[x]]-1; i>=0; --i)
这段代码改为
for (register inti=lg[depth[x]]-1; i; --i)
本地IDE运行会出错
请问为什么qwq