constint N = 40010, M = 2*N; int depth[N], f[N][16], h[N], e[M], ne[M], idx;
voidadd(int a, int b){ e[idx] = b, ne[idx] = h[a], h[a] = idx++; }
voiddfs(int u, int father){ depth[u] = depth[father] + 1; f[u][0] = father; for (int k = 1; k <= 15; k++) f[u][k] = f[f[u][k-1]][k-1]; for (int i = h[u]; ~i; i = ne[i]) { int j = e[i]; if (!depth[j]) dfs(j, u); } }
intlca(int a, int b){ // 保证 a 比 b 深 if (depth[a] < depth[b]) swap(a, b); for (int k = 15; k >= 0; k--) { if (depth[f[a][k]] >= depth[b]) a = f[a][k]; } if (a == b) return a; for (int k = 15; k >= 0; k--) { if (f[a][k] != f[b][k]) a = f[a][k], b = f[b][k]; } return f[a][0]; }
intmain(){ int n, m, root; memset(h, -1, sizeof h); cin >> n; while (n--) { int a, b; cin >> a >> b; if (b == -1) root = a; elseadd(a, b), add(b, a); } dfs(root, 0); cin >> m; while (m--) { int a, b; cin >> a >> b; int p = lca(a, b); if (p == a) puts("1"); elseif (p == b) puts("2"); elseputs("0"); } return0; }
constint N = 10010, M = 20010; int h[N], e[M], ne[M], idx; int fa[N][15], depth[N]; int n;
voidadd(int a, int b){ e[idx] = b, ne[idx] = h[a], h[a] = idx++; }
voiddfs(int u, int f){ depth[u] = depth[f] + 1; fa[u][0] = f; for (int k = 1; k < 15; k++) fa[u][k] = fa[fa[u][k-1]][k-1];
for (int i = h[u]; ~i; i = ne[i]) { int j = e[i]; if (j == f) continue; dfs(j, u); } }
intlca(int a, int b){ if (depth[a] < depth[b]) swap(a, b); for (int k = 14; k >= 0; k--) { if (depth[fa[a][k]] >= depth[b]) a = fa[a][k]; } if (a == b) return a; for (int k = 14; k >= 0; k--) { if (fa[a][k] != fa[b][k]) a = fa[a][k], b = fa[b][k]; } return fa[a][0]; }
intLCA(int u, int v, int w){ int p = lca(u, v), a = lca(w, u), b = lca(w, v); if (a == b) return p; if (depth[a] > depth[b]) return a; return b; }
intmain(){ memset(h, -1, sizeof h); scanf("%d", &n); for (int i = 1, j; i <= n; i++) { scanf("%d", &j); if (j) add(i, j), add(j, i); } int q, u, v, w; scanf("%d", &q); dfs(1, 0); while (q--) { scanf("%d%d%d", &u, &v, &w); printf("%d\n", LCA(u, v, w)); } return0; }
intmain(){ srand(time(0)); int n = rand() % 10000 + 1; fa[1] = 0; for (int i = 2; i <= n; i++) { int f; fa[i] = rand() % (i-1) + 1; } printf("%d\n", n); for (int i = 1; i <= n; i++) printf("%d ", fa[i]); printf("\n"); int q = rand() % 10000 + 1; printf("%d\n", q); for (int i = 1, u, v, w; i <= q; i++) { u = rand() % n + 1, v = rand() % n + 1, w = rand() % n + 1; printf("%d %d %d\n", u, v, w); } return0; }