Cod sursa(job #3227075)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 25 aprilie 2024 10:12:14
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>

const int mxN = 1e5 + 5;
const int mxLOG = 17;
int p[mxN][mxLOG];
int visited[mxN], nivel[mxN];
std::vector<int> edges[mxN];

void dfs(int node, int level) {
    nivel[node] = level;

    for (auto elem : edges[node]) {
        if (!nivel[elem]) {
            dfs(elem, level + 1);
        }
    }
}

int main() {
    std::ifstream fin("lca.in");
    std::ofstream fout("lca.out");
    int n, m;
    fin >> n >> m;

    for (int i = 1; i < n; ++i) {
        fin >> p[i + 1][0];
        edges[p[i + 1][0]].push_back(i + 1);
    }

    for (int j = 1; j < 17; ++j) {
        for (int i = 1; i <= n; ++i) {
            p[i][j] = p[p[i][j - 1]][j - 1];
        }
    }

    dfs(1, 1);
    while (m--) {
        int x, y;
        fin >> x >> y;

        if (nivel[y] > nivel[x]) {
            std::swap(x, y);
        }

        int len = nivel[x] - nivel[y];
        for (int i = 16; i >= 0; --i) {
            if (len & (1 << i)) {
                x = p[x][i];
            }
        }

        if (x == y) {
            fout << x << '\n';
        } else {
            for (int i = 16; i >= 0; --i) {
                if (p[x][i] != p[y][i]) {
                    x = p[x][i];
                    y = p[y][i];
                }
            }
            fout << p[x][0] << '\n';
        }
    }
}