第一个测试点warning
查看原帖
第一个测试点warning
1165449
Februrary楼主2023/12/17 17:43

只有第一个测试点无法通过,求教。


求解距离的思路是,先找到两者的最近的公共祖先,然后通过这三个点的深度求路径长度。

#include <iostream>
#include <cstring>
using namespace std;
struct node {
    int right;
    int left;
    int father;
} tree[105];
int n;
int sx, sy;
int root;
int de[105];
int maxDepth;
int maxK;
int rootD, syD, sxD;
void dfs(int index, int depth) {

    if(index == 0) {
        maxDepth = max(maxDepth, depth);
        return;
    }
    if(index == sx) sxD = depth;
    if(index == sy) syD = depth;
    if(index == root) rootD = depth; 
    de[depth]++;
    dfs(tree[index].left, depth + 1);
    dfs(tree[index].right, depth + 1);


}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    
    //memset(tree, 0, sizeof(tree));
    //memset(de, 0, sizeof(de));
    cin >> n;

    for(int i = 0; i < n - 1; i++) {
        int father = 0, child = 0;
        cin >> father >> child;
        if(tree[father].left == 0) {
            tree[father].left = child;
        }
        else {
            tree[father].right = child;
        }

        tree[child].father = father;
    }

    cin >> sx >> sy;

    int father_sx = sx, father_sy = sy;
    while(father_sx != father_sy) {
        if(father_sx < father_sy) {
            father_sy = tree[father_sy].father;
        }
        else if(father_sx > father_sy) {
            father_sx = tree[father_sx].father;
        }
    }
    root = father_sx;
    // cout << root << endl;
    dfs(1, 1);
    for(int i = 0; i < 105; i++) {
        maxK = max(maxK, de[i]);
    }

    cout << maxDepth - 1 << endl;
    cout << maxK << endl;
    cout << 2 * (sxD - rootD) + (syD - rootD) << endl;
    return 0;
}
2023/12/17 17:43
加载中...