萌新30pts+RE求助
查看原帖
萌新30pts+RE求助
254574
谢朝阳楼主2022/10/17 17:23
#include <bits/stdc++.h>

using namespace std;

int n, m, s;
struct Node
{
    int dep;
    vector<int> fa;
    vector<int> to;
};

vector<Node> node;

void dfs(int root, int fa)
{
    Node &now = node[root];
    now.fa.push_back(fa);

    now.dep = node[fa].dep + 1;

    for (int i = 1; i <= now.dep; i++)
    {
        now.fa.push_back(node[now.fa[i - 1]].fa[i - 1]);
    }

    for (int i : now.to)
    {
        if (i == fa)
        {
            continue;
        }
        dfs(i, root);
    }
}

int lca(int x, int y)
{
    if (node[x].dep > node[y].dep)
    {
        swap(x, y);
    }

    int tmp = node[y].dep - node[x].dep;

    for (int i = 0; tmp; i++, tmp >>= 1)
    {
        if (tmp & 1)
        {
            y = node[y].fa[i];
        }
    }

    if (y == x)
    {
        return x;
    }

    for (int i = node[y].fa.size() - 1; i >= 0; i--)
    {
        if (node[x].fa[i] != node[y].fa[i])
        {
            x = node[x].fa[i];
            y = node[y].fa[i];
        }
    }
    return node[y].fa[0];
}

int main()
{
    ios_base::sync_with_stdio(false);

    cin >> n >> m >> s;
    node.resize(n + 1);

    for (int i = 1; i < n; i++)
    {
        int u, v;
        cin >> u >> v;
        node[u].to.push_back(v);
        node[v].to.push_back(u);
    }

    node[1].to.push_back(0);
    node[0].to.push_back(1);
    node[0].fa.resize(31);
    node[0].dep = 0;

    dfs(s, 0);

    while (m--)
    {
        int x, y;
        cin >> x >> y;
        cout << lca(x, y) << endl;
    }

    return 0;
}

rt,写的倍增LCA,求大佬指正错误

2022/10/17 17:23
加载中...