C++ 努力识别我的解决方案中缺失的步骤,从在线法官那里获得WA

C++ 努力识别我的解决方案中缺失的步骤,从在线法官那里获得WA,c++,graph,tree,lowest-common-ancestor,C++,Graph,Tree,Lowest Common Ancestor,在codechef上的竞赛之后,我解决了这个问题。在观看解决方案并参考测试人员的解决方案后,我实现了与我所看到的解决方案略有不同的解决方案(相信它将在我理解的范围内工作) 让我带你浏览一下我的代码,给你一个我相信我在做什么的抽象视图 首先,我在给定的查询节点中查找相对于节点1最深的节点,然后在查询节点形成的最小子树中查找距离最深节点最远的其他节点。一旦我们知道了节点之间的最远距离(即直径,比如D),我就找到了最深节点的第二个祖先 下面是更详细的解释 我正在使用邻接列表构建一棵树,然后我正在进行D

codechef上的竞赛之后,我解决了这个问题。在观看解决方案并参考测试人员的解决方案后,我实现了与我所看到的解决方案略有不同的解决方案(相信它将在我理解的范围内工作)

让我带你浏览一下我的代码,给你一个我相信我在做什么的抽象视图

首先,我在给定的查询节点中查找相对于节点1最深的节点,然后在查询节点形成的最小子树中查找距离最深节点最远的其他节点。一旦我们知道了节点之间的最远距离(
即直径,比如D
),我就找到了最深节点的第二个祖先

下面是更详细的解释

我正在使用邻接列表构建一棵树,然后我正在进行DFS遍历以进行预处理 顶点的深度,这里是它的代码片段。这里
P
是父节点,
C
是子节点

void find_depth(int P = 0, int C = 1) {
    up[C][0] = P;
    for (auto& v : tree[C]) {
        if (P != v) {
            depth[v] = depth[C] + 1;
            find_depth(C, v);
        }
    }
}
这里
up[v][j]
将为您提供
2^j
th祖先(您猜对了)

下面是我对二进制提升的实现

 void binary_lifting() {
    LOG = 0;
    while ((1LL << LOG) <= N) LOG++;

    up = vector<vector<int>>(N + 1, vector<int>(LOG));

    find_depth(0, 1);
    up[1][0] = 1;
    for (int v { 1 }; v <= N; ++v) {
        for (int jump { 1 }; jump < LOG; ++jump) {
            up[v][jump] = up[up[v][jump - 1]][jump - 1];
        }
    }
}
我需要介绍的最后一个函数是LCA,它应该找到
a
b

int LCA(int a, int b) {
    if (a != b) {
        if (depth[a] < depth[b]) {
            swap(a, b);
        }
        
        a = binary_jump(a, depth[a] - depth[b]);
        if(a == b){
            return a;
        }
        for (int i { LOG - 1 }; i >= 0; i = i - 1) {
            if (up[a][i] != up[b][i]) {
                a = up[a][i];
                b = up[b][i];
            }
        }
        return up[a][0];
    }
    return a;
}
寻找最深顶点

int deepest_v { -1 };
int max_depth { -1 };

for (auto& v : x) {
    if (depth[v] > max_depth) {
        max_depth = depth[v];
        deepest_v = v;
    }
}
找到直径的时间到了这是代码

int diameter { -1 };
for (auto& v : x) {
    int store {
        depth[deepest_v] + depth[v] - 2 * depth[LCA(deepest_v, v)]
    };
            
    if (diameter < store) {
        diameter = store;
    }
}
这是我所了解的全部内容,其中有些错误,我没有从在线评委处获得AC,请帮助我更正此解决方案

int deepest_v { -1 };
int max_depth { -1 };

for (auto& v : x) {
    if (depth[v] > max_depth) {
        max_depth = depth[v];
        deepest_v = v;
    }
}
int diameter { -1 };
for (auto& v : x) {
    int store {
        depth[deepest_v] + depth[v] - 2 * depth[LCA(deepest_v, v)]
    };
            
    if (diameter < store) {
        diameter = store;
    }
}
int Jump = diameter / 2;
  
int ans = binary_jump(deepest_v, Jump);
   
if (diameter & 1) {
    cout << 2 << sp << min(ans, up[ans][0]) << sp << max(ans, up[ans][0]) << nl;
} else {
    cout << 1 << sp << ans << nl;
}