聚会

题目描述(https://loj.ac/problem/10136)

思路

3个节点a,b,c选择(a,b)(a,c)(b,c)公共祖先深度最大的节点,3个节点的最大距离为每个节点到公共祖先的距离和 / 2;

代码

#include <cstdio>
#include <algorithm>

const int MAX = 5e5 + 5;
int n, m;
int head[MAX], ver[MAX << 1], nt[MAX << 1], ht;
int f[MAX][21], dep[MAX];
int ans, res, dps;

inline int read() {
    int s = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9') ch = getchar();
    while (ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
    return s;
}

void add(int x, int y) {
    nt[++ht] = head[x], head[x] = ht, ver[ht] = y;
}
void dfs_lca(int x, int y) {
    dep[x] = dep[y] + 1;
    f[x][0] = y;
    for (int i = 1; i <= 19; ++i) f[x][i] = f[f[x][i - 1]][i - 1];
    for (int i = head[x], j; i; i = nt[i]) {
        j = ver[i];
        if (j == y) continue;
        dfs_lca(j, x);
    }
}
int lca(int x, int y) {
    if (dep[x] < dep[y]) std::swap(x, y);
    for (int i = 19; i >= 0; --i) {
        if (dep[f[x][i]] >= dep[y]) {
            x = f[x][i];
            ans += (1 << i);
        }
    }
    if (x == y) {
        if (dps < dep[x]) res = x, dps = dep[x];
        return x;
    }
    for (int i = 19; i >= 0; --i) {
        if (f[x][i] != f[y][i]) {
            x = f[x][i], y = f[y][i];
            ans += 1 << (i + 1);
        }
    }
    ans += 2;
    if (dps < dep[f[x][0]]) res = f[x][0], dps = dep[f[x][0]];
    return f[x][0];
}
int main() {
    n = read(), m = read();
    for (int i = 1, a, b; i < n; ++i) {
        a = read(), b = read();
        add(a, b), add(b, a);
    }
    dfs_lca(1, 0);
    for (int i = 1, a, b, c; i <= m; ++i) {
        a = read(), b = read(), c = read(), ans = 0, dps = 0;
        int ab = lca(a, b), ac = lca(a, c), bc = lca(b, c);
        // printf("lca:%d %d %d\n", ab, ac, bc);
        printf("%d %d\n", res, ans >> 1);
    }
    return 0;
}

转载于:https://www.cnblogs.com/liuzz-20180701/p/11509985.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值