代码:【模板】最近公共祖先(LCA)

【模板】最近公共祖先(LCA)
链接:https://www.luogu.com.cn/problem/P3379
来源:洛谷

题目描述:
如题,给定一棵有根多叉树,请求出指定两个点直接最近的公共祖先。

输入格式:
第一行包含三个正整数 N,M,S,分别表示树的结点个数、询问的个数和树根结点的序号。
接下来 N−1 行每行包含两个正整数 x,y,表示 x 结点和 y 结点之间有一条直接连接的边(数据保证可以构成树)。
接下来 M 行每行包含两个正整数 a,b,表示询问 a 结点和 b 结点的最近公共祖先。

输出格式:
输出包含 M 行,每行包含一个正整数,依次为每一个询问的结果。

//交题真就玄学,快读+O(2)优化==AC(滑稽.jpg)
#include <bits/stdc++.h>
using namespace std;
const int MAX = 500001;
int ancestor[MAX][20], deep[MAX];
vector<int> edge[MAX];
int n, m, s;
void dfs(int u)
{
    deep[u] = deep[ancestor[u][0]] + 1;
    for (int i = 0; ancestor[u][i]; i++)
        ancestor[u][i + 1] = ancestor[ancestor[u][i]][i];
    for (int i = 0; i < edge[u].size(); i++)
        if (!deep[edge[u][i]])
        {
            ancestor[edge[u][i]][0] = u;
            dfs(edge[u][i]);
        }
}
int lca(int u, int v)
{
    if (deep[u] < deep[v])
        swap(u, v);
    for (int i = 19; i >= 0; i--)
        if (deep[ancestor[u][i]] >= deep[v])
            u = ancestor[u][i];
    if (u == v)
        return u;
    for (int i = 19; i >= 0; i--)
        if (ancestor[u][i] != ancestor[v][i])
        {
            u = ancestor[u][i];
            v = ancestor[v][i];
        }
    return ancestor[u][0];
}
int read()
{
    int k = 0, f = 1;
    char c = getchar();
    for (; !isdigit(c); c = getchar())
        if (c == '-')
            f = -1;
    for (; isdigit(c); c = getchar())
        k = k * 10 + c - '0';
    return k * f;
}
int main()
{
    n = read();
    m = read();
    s = read();
    int x, y;
    for (int i = 1; i < n; i++)
    {
        x = read();
        y = read();
        edge[x].push_back(y);
        edge[y].push_back(x);
    }
    dfs(s);
    for (int i = 1; i <= m; i++)
    {
        x = read();
        y = read();
        cout << lca(x, y) << "\n";
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值