LCA

最近公共祖先

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <iostream>
#include <cmath>

using namespace std;

const int N = 110, M = 2 * N;
int h[N], e[M], ne[M], idx;

int k, x, y, n, depth, breath;
int d[N], b[N], f[N][N];

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

void bfs()
{
    d[1] = 1;
    queue<int>q;
    q.push(1);
    while(q.size())
    {
        auto t = q.front(); q.pop();
        for(int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if(d[j])    continue;
            d[j] = d[t] + 1;
            b[d[j]] ++;
            depth = max(depth, d[j]);
            breath = max(breath, b[d[j]]); 
            f[j][0] = t;
            for(int m = 1; m <= k; ++ m)
                f[j][m] = f[f[j][m - 1]][m - 1];
            q.push(j);
        }
    }
}

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

    for(int i = k; 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);
    cin >> n;
    k = (int) (log(n) / log(2)) + 1;
    for(int i = 0; i < n - 1; ++ i)
    {
        int a, b; 
        cin >> a >> b;
        add(a, b); add(b, a);
    }
    cin >> x >> y;
    bfs();
    cout << depth << endl;
    cout << breath << endl;
    cout << (d[x] - d[lca(x, y)]) * 2 + d[y] - d[lca(x, y)]; 
    return 0;
}
posted @   cxy8  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示