Cod sursa(job #2771411)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 27 august 2021 10:52:48
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

const int mxN = 1e5 + 5, mxLOG = 17;

int up[mxN][mxLOG], depth[mxN];

vector<int> fiu[mxN];

void dfs(int x) {
    for (int vecin : fiu[x]) {
        if (depth[vecin] == 0) {
            depth[vecin] = depth[x] + 1;
            dfs(vecin);
        }
    }
}

int main() {
    ios::sync_with_stdio(false), fin.tie(nullptr), fout.tie(nullptr);
    int n, m; fin >> n >> m;
    for (int i = 1; i < n; ++i) {
        fin >> up[i + 1][0];
        fiu[up[i + 1][0]].push_back(i + 1);
    }
    depth[1] = 1;
    dfs(1);
    for (int j = 1; j < mxLOG; ++j) {
        for (int i = 1; i <= n; ++i) {
            up[i][j] = up[up[i][j - 1]][j - 1];
        }
    }
    while (m--) {
        int x, y; fin >> x >> y;
        if (depth[y] > depth[x]) {
            swap(x, y);
        }
        int length = depth[x] - depth[y];
        for (int i = 31; i >= 0; --i) {
            if ((length & (1 << i))) {
                x = up[x][i];
            }
        }
        if (x == y) {
            fout << x << '\n';
            continue;
        }
        for (int i = 16; i >= 0; --i) {
            if (up[x][i] != up[y][i]) {
                x = up[x][i];
                y = up[y][i];
            }
        }
        fout << up[x][0] << '\n';
    }
    return 0;
}