《原神攻略》故事線順序回聲海螺收集攻略
阿新 • • 發佈:2021-06-26
鄰接表存圖。
struct node{...}; void add(...){} ll dep[500010], fa[500010][21], lg[500002]; ll head[500010], tot; ll n, m, s; void dfs(ll now, ll fath) { fa[now][0] = fath; dep[now] = dep[fath] + 1; for (int i = 1; i <= lg[dep[now]]; ++i) fa[now][i] = fa[fa[now][i - 1]][i - 1]; for (int i = head[now]; i; i = t[i].nxt) if (t[i].to != fath) dfs(t[i].to, now); } ll LCA(ll x, ll y) { if (dep[x] < dep[y]) swap(x, y); while (dep[x] > dep[y]) x = fa[x][lg[dep[x] - dep[y]] - 1]; if (x == y) return x; for (int k = lg[dep[x]] - 1; k >= 0; --k) if (fa[x][k] != fa[y][k]) x = fa[x][k], y = fa[y][k]; return fa[x][0]; } int main() { n = read(); m = read(); s = read(); for (int i = 1; i <= n; ++i) lg[i] = lg[i - 1] + (1 << lg[i - 1] == i); for (int i = 1; i < n; ++i) { ll x = read(), y = read(); add(x, y); add(y, x); } dfs(s, 0); for (int i = 1; i <= m; ++i) { ll x = read(), y = read(); printf("%lld\n", LCA(x, y)); } return 0; }