Skip to content
Author: lllyouo
Date: 20250322
tag: 最近公共祖先
link: https://www.luogu.com.cn/problem/P4281

问题描述

link

分析

树上任意两点间的距离:dis(x,y)=d(x)+d(y)2×d(lca(x,y))

其中 d(x) 表示节点 x 距离根节点的距离。

参考代码

cpp
#include <bits/stdc++.h>
using namespace std;

const int N = 5e5 + 10, M = 2 * N;
int h[N], e[M], ne[M], idx;
int d[N], f[N][20];
int n, m, t;

void add(int x, int y) {
    e[idx] = y;
    ne[idx] = h[x];
    h[x] = idx++;
}

void bfs() {
    queue<int> q;
    q.push(1);
    d[1] = 1;

    while (q.size()) {
        int x = q.front();
        q.pop();

        for (int i = h[x]; i != -1; i = ne[i]) {
            int y = e[i];
            if (d[y]) continue;

            f[y][0] = x;
            d[y] = d[x] + 1;
            for (int k = 1; k <= t; k++) {
                f[y][k] = f[f[y][k - 1]][k - 1];
            }
            q.push(y);
        }
    }
}

int lca(int x, int y) {
    if (d[x] < d[y]) swap(x, y);
    for (int i = t; i >= 0; i--) {
        if (d[f[x][i]] >= d[y]) x = f[x][i];
    }
    if (x == y) return x;

    for (int i = t; i >= 0; i--) {
        if (f[x][i] != f[y][i]) {
            x = f[x][i];
            y = f[y][i];
        }
    }

    return f[x][0];
}

int main() {
    memset(h, -1, sizeof h);
    scanf("%d%d", &n, &m);
    for (int i = 1; i < n; i++) {
        int a, b; scanf("%d%d", &a, &b);
        add(a, b); add(b, a);
    }

    t = int(log(n) / log(2)) + 1;
    bfs();

    while (m--) {
        int x, y, z; scanf("%d%d%d", &x, &y, &z);

        // 三个公共祖先中必有两个是同一个
        int pos = lca(x, y) ^ lca(x, z) ^ lca(y, z);
        int dis = d[x] + d[y] + d[z] - d[lca(x, y)] - d[lca(x, z)] - d[lca(y, z)];

        printf("%d %d\n", pos, dis);
    }

    return 0;
}