LCA

2024-08-15

使用Tarjan算法,求解树上任意两节点的最近公共祖先

#include <bits/stdc++.h>
#define io cin.tie(0), cout.tie(0), ios::sync_with_stdio(false)
#define LL long long
#define ULL unsigned long long
#define EPS 1e-8
#define INF 0x7fffffff
#define SUB -INF - 1
using namespace std;
const int N = 500005;
int fa[N], head[N], cnt, head_query[N], cnt_query, ans[N];
bool vis[N];
struct edge
{
    int to, next, num;
} edge[2 * N], query[2 * N];
void init()
{
    for (int i = 0; i < 2 * N; i++)
    {
        edge[i].next = -1;
        head[i] = -1;
        query[i].next = -1;
        head_query[i] = -1;
    }
    cnt = 0;
    cnt_query = 0;
}
void addedge(int u, int v)
{
    edge[cnt].to = v;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
void add_query(int x, int y, int num)
{
    query[cnt_query].to = y;
    query[cnt_query].num = num;
    query[cnt_query].next = head_query[x];
    head_query[x] = cnt_query++;
}
int find_set(int x) { return fa[x] == x ? x : find_set(fa[x]); }
void tarjan(int x)
{
    vis[x] = true;
    for (int i = head[x]; ~i; i = edge[i].next)
    {
        int y = edge[i].to;
        if (!vis[y])
        {
            tarjan(y);
            fa[y] = x;
        }
    }
    for (int i = head_query[x]; ~i; i = query[i].next)
    {
        int y = query[i].to;
        if (vis[y])
            ans[query[i].num] = find_set(y);
    }
}
int main()
{
    init();
    memset(vis, 0, sizeof(vis));
    int n, m, root;
    scanf("%d%d%d", &n, &m, &root);
    for (int i = 1; i < n; i++)
    {
        fa[i] = i;
        int u, v;
        scanf("%d%d", &u, &v);
        addedge(u, v);
        addedge(v, u);
    }
    fa[n] = n;
    for (int i = 1; i <= m; i++)
    {
        int a, b;
        scanf("%d%d", &a, &b);
        add_query(a, b, i);
        add_query(b, a, i);
    }
    tarjan(root);
    for (int i = 1; i <= m; i++)
        printf("%d\n", ans[i]);
    return 0;
}