1 solutions

  • 0
    @ 2026-11-20 16:48:10

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    
    const int MAXN = 105;
    vector<int> children[MAXN];
    int parent[MAXN], depth[MAXN];
    
    void dfs(int u, int fa) {
        parent[u] = fa;
        depth[u] = depth[fa] + 1;
        for (int v : children[u]) {
            dfs(v, u);
        }
    }
    
    int lca(int a, int b) {
        while (depth[a] > depth[b]) a = parent[a];
        while (depth[b] > depth[a]) b = parent[b];
        while (a != b) {
            a = parent[a];
            b = parent[b];
        }
        return a;
    }
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int n, x, y;
        cin >> n >> x >> y;
    
        for (int i = 1; i < n; i++) {
            int a, b;
            cin >> a >> b;
            children[b].push_back(a);   // b 是父,a 是子
        }
    
        dfs(1, 0);
    
        cout << lca(x, y) << '\n';
        return 0;
    }
    
    • 1

    Information

    ID
    396
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    10
    Tags
    # Submissions
    3
    Accepted
    2
    Uploaded By