Cod sursa(job #3293454)

Utilizator _andrei4567Stan Andrei _andrei4567 Data 11 aprilie 2025 18:18:27
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
#include <algorithm>

using namespace std;

ifstream cin ("lca.in");
ofstream cout ("lca.out");

const int N = 1e5;
int dp[N + 1][30], h[N + 1];

vector <int> g[N + 1];

int n, m, x, y;

void dfs (int node, int tata)
{
    h[node] = h[tata] + 1;
    for (auto it : g[node])
        dfs (it, node);
}

int lca (int x, int y)
{
    if (h[x] > h[y])
        swap (x, y);
    int dif = h[y] - h[x];
    for (int i = 0; (1 << i) <= dif; ++i)
        if ((1 << i) & dif)
            y = dp[y][i];
    if (x == y)
        return x;
    for (int i = __lg(h[x]); i >= 0; --i)
        if (dp[x][i] != dp[y][i])
            x = dp[x][i], y = dp[y][i];
    return dp[x][0];
}

int main()
{
    cin >> n >> m;
    for (int i = 2; i <= n; ++i)
        cin >> dp[i][0], g[dp[i][0]].push_back(i);
    dfs (1, 0);
    for (int i = 1; (1 << i) <= n; ++i)
        for (int j = 1; j <= n; ++j)
            dp[j][i] = dp[dp[j][i - 1]][i - 1];
    for (int i = 1; i <= m; ++i)
    {
        cin >> x >> y;
        cout << lca (x, y) << '\n';
    }
    return 0;
}