这也能死循环?测了是indepth有问题但是目测并不会死循环。。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e5 + 5;
const int maxm = 5e5 + 5;
inline int read() {
int ret = 0, f = 1;char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -f;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
ret = (ret << 1) + (ret << 3) + (ch ^ 48);
ch = getchar();
}
return ret * f;
}
int tot, head[maxn], to[maxm], nxt[maxm];
void add(int u, int v) {
tot++;
nxt[tot] = head[u];
head[u] = tot;
to[tot] = v;
}
int n, m, s;
int dep[maxn], fa[maxn][31];
void indepth(int now, int root) {
fa[now][0] = root;
dep[now] = dep[fa[now][0]] + 1;
for (int i = 1;(1 << i) <= n;i++) {
fa[now][i] = fa[fa[now][i - 1]][i - 1];
}
for (int i = head[now];i;i = nxt[i]) {
int v = to[i];
if (v == root) continue;
indepth(v, now);
}
return;
}
int LCA(int x, int y) {
if (dep[x] > dep[y]) swap(x, y);
int ans = 0;
while (dep[x] < dep[y]) x = fa[x][0], ans++;
for (int i = 1;(1 << i) <= dep[x];i++) {
if (fa[x][0] == fa[y][0]) break;
x = fa[x][i];
y = fa[y][i];
ans += (1 << i);
}
return ans;
}
int main() {
n = read(), m = read(), s = read();
for (int i = 1;i <= n;i++) {
int a = read(), b = read();
add(a, b), add(b, a);
}
for (int i = head[s];i;i = nxt[i]) {
int v = to[i];indepth(v, s);
}
for (int i = 1;i <= m;i++) {
int a = read(), b = read();
int ans = LCA(a, b);
if (ans == 0) puts("-1");
else printf("%d\n", ans);
}
return 0;
}