1 条题解

  • 0
    @ 2024-7-30 12:40:53

    参考答案:

    #include<iostream>
    #include<queue>
    #include<cstring>
    using namespace std;
    const int N = 40010 * 2, M = 17;
    int e[N], ne[N], h[N], idx;
    int f[N][M];
    int depth[N];
    int st[N];
    int n, m;
    queue<int> q;
    void add(int a, int b)
    {
        e[idx] = b, ne[idx] = h[a], h[a] = idx++;
    }
    void bfs(int root)
    {
        depth[0] = 0, depth[root] = 1;
        q.push(root);
        st[root] = 1;
        while (q.size())
        {
            int t = q.front();
            q.pop();
            for (int i = h[t]; ~i; i = ne[i])
            {
                int j = e[i];
                if (!st[j])
                {
                    depth[j] = depth[t] + 1;
                    f[j][0] = t;
                    for (int k = 1; k <= 16; ++k)
                    {
                        f[j][k] = f[f[j][k - 1]][k - 1];
                    }
                    q.push(j);
                    st[j] = 1;
                }
            }
        }
    }
    int lca(int a, int b)
    {
        if (depth[a] < depth[b]) swap(a, b);
        for (int k = 16; k >= 0; --k)
        {
            if (depth[f[a][k]] >= depth[b]) a = f[a][k];
        }
        if (a == b) return a;
        for (int k = 16; k >= 0; --k)
        {
            if (f[a][k] != f[b][k])
            {
                a = f[a][k];
                b = f[b][k];
            }
        }
        return f[a][0];
    }
    int main()
    {
        memset(h, -1, sizeof(h));
        cin >> n;
        int root = 0;
        for (int i = 0; i < n; ++i)
        {
            int a, b;
            cin >> a >> b;
            if (b == -1)
            {
                root = a;
                continue;
            }
            add(a, b);
            add(b, a);
        }
    
        bfs(root);
        cin >> m;
        for (int i = 0; i < m; ++i)
        {
            int x, y;
            cin >> x >> y;
            int p = lca(x, y);
            if (p == x) puts("1");
            else if (p == y) puts("2");
            else puts("0");
        }
        return 0;
    }
    
    • 1

    信息

    ID
    1491
    时间
    1000ms
    内存
    128MiB
    难度
    10
    标签
    (无)
    递交数
    5
    已通过
    2
    上传者