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 @ 2022-12-08 15:28  cxy8  阅读(26)  评论(0)    收藏  举报