为什么我的lca输出全是零
查看原帖
为什么我的lca输出全是零
134519
qwq自动机楼主2021/7/11 20:31

rt,对着书打的,思路也能理解,但是为什么输出的都是零?

#include <bits/stdc++.h>
using namespace std;
struct Edge
{
    int to;
    int nxt;
} edge[500010];
int head[500010], tail = 1;
int dep[500010], pre[500010][20];
int n, m, s, lgn;
void add(int x, int y)
{
    edge[tail].to = y;
    edge[tail].nxt = head[x];
    head[x] = tail;
    tail++;
}
void preprocessing()
{
    lgn = int(log(n) / log(2)) + 1;
    memset(dep, 0, sizeof(dep));
    queue<int> q;
    q.push(s);
    dep[s] = 1;
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        for (int i = head[x]; i; i = edge[i].nxt)
        {
            if (dep[edge[i].to])
                continue;
            int y = edge[i].to;
            dep[y] = dep[x] + 1;
            pre[y][0] = x;
            for (int i = 1; i <= lgn; i++)
                pre[y][i] = pre[pre[y][i - 1]][i - 1];
            q.push(y);
        }
    }
}
int lca(int x, int y)
{
    if (dep[x] > dep[y])
        swap(x, y);
    for (int i = lgn; i >= 0; i--)
        if (dep[pre[y][i]] <= dep[x])
            y = pre[y][i];
    for (int i = lgn; i >= 0; i--)
        if (pre[y][i] != pre[x][i])
        {
            y = pre[y][i];
            x = pre[x][i];
        }
    return pre[y][0];
}
int main()
{
    scanf("%d%d%d", &n, &m, &s);
    for (int i = 1; i < n; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        add(x, y);
    }
    preprocessing();
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        printf("%d\n", lca(x, y));
    }
    return 0;
}

是的没错又是我qwq

2021/7/11 20:31
加载中...